blob: 8543e1090a9a09d1e6743b113316adc60af5fcbb [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))
1476 return self
1477
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
1497 return 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 Batista353750c2007-09-13 18:13:15 +00001510 return self
1511
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
1554 return 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:
1681 return self
1682 if other_is_nan:
1683 return other
1684 return modulo
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
2163
Facundo Batista353750c2007-09-13 18:13:15 +00002164 def quantize(self, exp, rounding=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002165 """Quantize self so its exponent is the same as that of exp.
2166
2167 Similar to self._rescale(exp._exp) but with error checking.
2168 """
Facundo Batista353750c2007-09-13 18:13:15 +00002169 if context is None:
2170 context = getcontext()
2171 if rounding is None:
2172 rounding = context.rounding
2173
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002174 if self._is_special or exp._is_special:
2175 ans = self._check_nans(exp, context)
2176 if ans:
2177 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002178
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002179 if exp._isinfinity() or self._isinfinity():
2180 if exp._isinfinity() and self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00002181 return self # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002182 return context._raise_error(InvalidOperation,
2183 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002184
2185 # exp._exp should be between Etiny and Emax
2186 if not (context.Etiny() <= exp._exp <= context.Emax):
2187 return context._raise_error(InvalidOperation,
2188 'target exponent out of bounds in quantize')
2189
2190 if not self:
2191 ans = Decimal((self._sign, (0,), exp._exp))
2192 return ans._fix(context)
2193
2194 self_adjusted = self.adjusted()
2195 if self_adjusted > context.Emax:
2196 return context._raise_error(InvalidOperation,
2197 'exponent of quantize result too large for current context')
2198 if self_adjusted - exp._exp + 1 > context.prec:
2199 return context._raise_error(InvalidOperation,
2200 'quantize result has too many digits for current context')
2201
2202 ans = self._rescale(exp._exp, rounding)
2203 if ans.adjusted() > context.Emax:
2204 return context._raise_error(InvalidOperation,
2205 'exponent of quantize result too large for current context')
2206 if len(ans._int) > context.prec:
2207 return context._raise_error(InvalidOperation,
2208 'quantize result has too many digits for current context')
2209
2210 # raise appropriate flags
2211 if ans._exp > self._exp:
2212 context._raise_error(Rounded)
2213 if ans != self:
2214 context._raise_error(Inexact)
2215 if ans and ans.adjusted() < context.Emin:
2216 context._raise_error(Subnormal)
2217
2218 # call to fix takes care of any necessary folddown
2219 ans = ans._fix(context)
2220 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002221
2222 def same_quantum(self, other):
2223 """Test whether self and other have the same exponent.
2224
2225 same as self._exp == other._exp, except NaN == sNaN
2226 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002227 if self._is_special or other._is_special:
2228 if self._isnan() or other._isnan():
2229 return self._isnan() and other._isnan() and True
2230 if self._isinfinity() or other._isinfinity():
2231 return self._isinfinity() and other._isinfinity() and True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002232 return self._exp == other._exp
2233
Facundo Batista353750c2007-09-13 18:13:15 +00002234 def _rescale(self, exp, rounding):
2235 """Rescale self so that the exponent is exp, either by padding with zeros
2236 or by truncating digits, using the given rounding mode.
2237
2238 Specials are returned without change. This operation is
2239 quiet: it raises no flags, and uses no information from the
2240 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002241
2242 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002243 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002244 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002245 if self._is_special:
Facundo Batista353750c2007-09-13 18:13:15 +00002246 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002247 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002248 return Decimal((self._sign, (0,), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002249
Facundo Batista353750c2007-09-13 18:13:15 +00002250 if self._exp >= exp:
2251 # pad answer with zeros if necessary
2252 return Decimal((self._sign, self._int + (0,)*(self._exp - exp), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002253
Facundo Batista353750c2007-09-13 18:13:15 +00002254 # too many digits; round and lose data. If self.adjusted() <
2255 # exp-1, replace self by 10**(exp-1) before rounding
2256 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002257 if digits < 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002258 self = Decimal((self._sign, (1,), exp-1))
2259 digits = 0
2260 this_function = getattr(self, self._pick_rounding_function[rounding])
2261 return this_function(digits)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002262
Facundo Batista353750c2007-09-13 18:13:15 +00002263 def to_integral_exact(self, rounding=None, context=None):
2264 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002265
Facundo Batista353750c2007-09-13 18:13:15 +00002266 If no rounding mode is specified, take the rounding mode from
2267 the context. This method raises the Rounded and Inexact flags
2268 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002269
Facundo Batista353750c2007-09-13 18:13:15 +00002270 See also: to_integral_value, which does exactly the same as
2271 this method except that it doesn't raise Inexact or Rounded.
2272 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002273 if self._is_special:
2274 ans = self._check_nans(context=context)
2275 if ans:
2276 return ans
Facundo Batista353750c2007-09-13 18:13:15 +00002277 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002278 if self._exp >= 0:
2279 return self
Facundo Batista353750c2007-09-13 18:13:15 +00002280 if not self:
2281 return Decimal((self._sign, (0,), 0))
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002282 if context is None:
2283 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002284 if rounding is None:
2285 rounding = context.rounding
2286 context._raise_error(Rounded)
2287 ans = self._rescale(0, rounding)
2288 if ans != self:
2289 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002290 return ans
2291
Facundo Batista353750c2007-09-13 18:13:15 +00002292 def to_integral_value(self, rounding=None, context=None):
2293 """Rounds to the nearest integer, without raising inexact, rounded."""
2294 if context is None:
2295 context = getcontext()
2296 if rounding is None:
2297 rounding = context.rounding
2298 if self._is_special:
2299 ans = self._check_nans(context=context)
2300 if ans:
2301 return ans
2302 return self
2303 if self._exp >= 0:
2304 return self
2305 else:
2306 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002307
Facundo Batista353750c2007-09-13 18:13:15 +00002308 # the method name changed, but we provide also the old one, for compatibility
2309 to_integral = to_integral_value
2310
2311 def sqrt(self, context=None):
2312 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002313 if self._is_special:
2314 ans = self._check_nans(context=context)
2315 if ans:
2316 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002317
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002318 if self._isinfinity() and self._sign == 0:
2319 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002320
2321 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002322 # exponent = self._exp // 2. sqrt(-0) = -0
2323 ans = Decimal((self._sign, (0,), self._exp // 2))
2324 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002325
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002326 if context is None:
2327 context = getcontext()
2328
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002329 if self._sign == 1:
2330 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2331
Facundo Batista353750c2007-09-13 18:13:15 +00002332 # At this point self represents a positive number. Let p be
2333 # the desired precision and express self in the form c*100**e
2334 # with c a positive real number and e an integer, c and e
2335 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2336 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2337 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2338 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2339 # the closest integer to sqrt(c) with the even integer chosen
2340 # in the case of a tie.
2341 #
2342 # To ensure correct rounding in all cases, we use the
2343 # following trick: we compute the square root to an extra
2344 # place (precision p+1 instead of precision p), rounding down.
2345 # Then, if the result is inexact and its last digit is 0 or 5,
2346 # we increase the last digit to 1 or 6 respectively; if it's
2347 # exact we leave the last digit alone. Now the final round to
2348 # p places (or fewer in the case of underflow) will round
2349 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002350
Facundo Batista353750c2007-09-13 18:13:15 +00002351 # use an extra digit of precision
2352 prec = context.prec+1
2353
2354 # write argument in the form c*100**e where e = self._exp//2
2355 # is the 'ideal' exponent, to be used if the square root is
2356 # exactly representable. l is the number of 'digits' of c in
2357 # base 100, so that 100**(l-1) <= c < 100**l.
2358 op = _WorkRep(self)
2359 e = op.exp >> 1
2360 if op.exp & 1:
2361 c = op.int * 10
2362 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002363 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002364 c = op.int
2365 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002366
Facundo Batista353750c2007-09-13 18:13:15 +00002367 # rescale so that c has exactly prec base 100 'digits'
2368 shift = prec-l
2369 if shift >= 0:
2370 c *= 100**shift
2371 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002372 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002373 c, remainder = divmod(c, 100**-shift)
2374 exact = not remainder
2375 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002376
Facundo Batista353750c2007-09-13 18:13:15 +00002377 # find n = floor(sqrt(c)) using Newton's method
2378 n = 10**prec
2379 while True:
2380 q = c//n
2381 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002382 break
Facundo Batista353750c2007-09-13 18:13:15 +00002383 else:
2384 n = n + q >> 1
2385 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002386
Facundo Batista353750c2007-09-13 18:13:15 +00002387 if exact:
2388 # result is exact; rescale to use ideal exponent e
2389 if shift >= 0:
2390 # assert n % 10**shift == 0
2391 n //= 10**shift
2392 else:
2393 n *= 10**-shift
2394 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002395 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002396 # result is not exact; fix last digit as described above
2397 if n % 5 == 0:
2398 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002399
Facundo Batista353750c2007-09-13 18:13:15 +00002400 ans = Decimal((0, map(int, str(n)), e))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002401
Facundo Batista353750c2007-09-13 18:13:15 +00002402 # round, and fit to current context
2403 context = context._shallow_copy()
2404 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002405 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002406 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002407
Facundo Batista353750c2007-09-13 18:13:15 +00002408 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002409
2410 def max(self, other, context=None):
2411 """Returns the larger value.
2412
Facundo Batista353750c2007-09-13 18:13:15 +00002413 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002414 NaN (and signals if one is sNaN). Also rounds.
2415 """
Facundo Batista353750c2007-09-13 18:13:15 +00002416 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002417
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002418 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002419 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002420 # number is always returned
2421 sn = self._isnan()
2422 on = other._isnan()
2423 if sn or on:
2424 if on == 1 and sn != 2:
2425 return self
2426 if sn == 1 and on != 2:
2427 return other
2428 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002429
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002430 c = self.__cmp__(other)
2431 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002432 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002433 # then an ordering is applied:
2434 #
Facundo Batista59c58842007-04-10 12:58:45 +00002435 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002436 # positive sign and min returns the operand with the negative sign
2437 #
Facundo Batista59c58842007-04-10 12:58:45 +00002438 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002439 # the result. This is exactly the ordering used in compare_total.
2440 c = self.compare_total(other)
2441
2442 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002443 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002444 else:
2445 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002446
2447 if context is None:
2448 context = getcontext()
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002449 if context._rounding_decision == ALWAYS_ROUND:
2450 return ans._fix(context)
2451 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002452
2453 def min(self, other, context=None):
2454 """Returns the smaller value.
2455
Facundo Batista59c58842007-04-10 12:58:45 +00002456 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002457 NaN (and signals if one is sNaN). Also rounds.
2458 """
Facundo Batista353750c2007-09-13 18:13:15 +00002459 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002460
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002461 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002462 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002463 # number is always returned
2464 sn = self._isnan()
2465 on = other._isnan()
2466 if sn or on:
2467 if on == 1 and sn != 2:
2468 return self
2469 if sn == 1 and on != 2:
2470 return other
2471 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002472
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002473 c = self.__cmp__(other)
2474 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002475 c = self.compare_total(other)
2476
2477 if c == -1:
2478 ans = self
2479 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002480 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002481
2482 if context is None:
2483 context = getcontext()
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002484 if context._rounding_decision == ALWAYS_ROUND:
2485 return ans._fix(context)
2486 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002487
2488 def _isinteger(self):
2489 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002490 if self._is_special:
2491 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002492 if self._exp >= 0:
2493 return True
2494 rest = self._int[self._exp:]
2495 return rest == (0,)*len(rest)
2496
2497 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002498 """Returns True if self is even. Assumes self is an integer."""
2499 if not self or self._exp > 0:
2500 return True
Raymond Hettinger61992ef2004-08-06 23:42:16 +00002501 return self._int[-1+self._exp] & 1 == 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002502
2503 def adjusted(self):
2504 """Return the adjusted exponent of self"""
2505 try:
2506 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002507 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002508 except TypeError:
2509 return 0
2510
Facundo Batista353750c2007-09-13 18:13:15 +00002511 def canonical(self, context=None):
2512 """Returns the same Decimal object.
2513
2514 As we do not have different encodings for the same number, the
2515 received object already is in its canonical form.
2516 """
2517 return self
2518
2519 def compare_signal(self, other, context=None):
2520 """Compares self to the other operand numerically.
2521
2522 It's pretty much like compare(), but all NaNs signal, with signaling
2523 NaNs taking precedence over quiet NaNs.
2524 """
2525 if context is None:
2526 context = getcontext()
2527
2528 self_is_nan = self._isnan()
2529 other_is_nan = other._isnan()
2530 if self_is_nan == 2:
2531 return context._raise_error(InvalidOperation, 'sNaN',
2532 1, self)
2533 if other_is_nan == 2:
2534 return context._raise_error(InvalidOperation, 'sNaN',
2535 1, other)
2536 if self_is_nan:
2537 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2538 1, self)
2539 if other_is_nan:
2540 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2541 1, other)
2542 return self.compare(other, context=context)
2543
2544 def compare_total(self, other):
2545 """Compares self to other using the abstract representations.
2546
2547 This is not like the standard compare, which use their numerical
2548 value. Note that a total ordering is defined for all possible abstract
2549 representations.
2550 """
2551 # if one is negative and the other is positive, it's easy
2552 if self._sign and not other._sign:
2553 return Dec_n1
2554 if not self._sign and other._sign:
2555 return Dec_p1
2556 sign = self._sign
2557
2558 # let's handle both NaN types
2559 self_nan = self._isnan()
2560 other_nan = other._isnan()
2561 if self_nan or other_nan:
2562 if self_nan == other_nan:
2563 if self._int < other._int:
2564 if sign:
2565 return Dec_p1
2566 else:
2567 return Dec_n1
2568 if self._int > other._int:
2569 if sign:
2570 return Dec_n1
2571 else:
2572 return Dec_p1
2573 return Dec_0
2574
2575 if sign:
2576 if self_nan == 1:
2577 return Dec_n1
2578 if other_nan == 1:
2579 return Dec_p1
2580 if self_nan == 2:
2581 return Dec_n1
2582 if other_nan == 2:
2583 return Dec_p1
2584 else:
2585 if self_nan == 1:
2586 return Dec_p1
2587 if other_nan == 1:
2588 return Dec_n1
2589 if self_nan == 2:
2590 return Dec_p1
2591 if other_nan == 2:
2592 return Dec_n1
2593
2594 if self < other:
2595 return Dec_n1
2596 if self > other:
2597 return Dec_p1
2598
2599 if self._exp < other._exp:
2600 if sign:
2601 return Dec_p1
2602 else:
2603 return Dec_n1
2604 if self._exp > other._exp:
2605 if sign:
2606 return Dec_n1
2607 else:
2608 return Dec_p1
2609 return Dec_0
2610
2611
2612 def compare_total_mag(self, other):
2613 """Compares self to other using abstract repr., ignoring sign.
2614
2615 Like compare_total, but with operand's sign ignored and assumed to be 0.
2616 """
2617 s = self.copy_abs()
2618 o = other.copy_abs()
2619 return s.compare_total(o)
2620
2621 def copy_abs(self):
2622 """Returns a copy with the sign set to 0. """
2623 return Decimal((0, self._int, self._exp))
2624
2625 def copy_negate(self):
2626 """Returns a copy with the sign inverted."""
2627 if self._sign:
2628 return Decimal((0, self._int, self._exp))
2629 else:
2630 return Decimal((1, self._int, self._exp))
2631
2632 def copy_sign(self, other):
2633 """Returns self with the sign of other."""
2634 return Decimal((other._sign, self._int, self._exp))
2635
2636 def exp(self, context=None):
2637 """Returns e ** self."""
2638
2639 if context is None:
2640 context = getcontext()
2641
2642 # exp(NaN) = NaN
2643 ans = self._check_nans(context=context)
2644 if ans:
2645 return ans
2646
2647 # exp(-Infinity) = 0
2648 if self._isinfinity() == -1:
2649 return Dec_0
2650
2651 # exp(0) = 1
2652 if not self:
2653 return Dec_p1
2654
2655 # exp(Infinity) = Infinity
2656 if self._isinfinity() == 1:
2657 return Decimal(self)
2658
2659 # the result is now guaranteed to be inexact (the true
2660 # mathematical result is transcendental). There's no need to
2661 # raise Rounded and Inexact here---they'll always be raised as
2662 # a result of the call to _fix.
2663 p = context.prec
2664 adj = self.adjusted()
2665
2666 # we only need to do any computation for quite a small range
2667 # of adjusted exponents---for example, -29 <= adj <= 10 for
2668 # the default context. For smaller exponent the result is
2669 # indistinguishable from 1 at the given precision, while for
2670 # larger exponent the result either overflows or underflows.
2671 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2672 # overflow
2673 ans = Decimal((0, (1,), context.Emax+1))
2674 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2675 # underflow to 0
2676 ans = Decimal((0, (1,), context.Etiny()-1))
2677 elif self._sign == 0 and adj < -p:
2678 # p+1 digits; final round will raise correct flags
2679 ans = Decimal((0, (1,) + (0,)*(p-1) + (1,), -p))
2680 elif self._sign == 1 and adj < -p-1:
2681 # p+1 digits; final round will raise correct flags
2682 ans = Decimal((0, (9,)*(p+1), -p-1))
2683 # general case
2684 else:
2685 op = _WorkRep(self)
2686 c, e = op.int, op.exp
2687 if op.sign == 1:
2688 c = -c
2689
2690 # compute correctly rounded result: increase precision by
2691 # 3 digits at a time until we get an unambiguously
2692 # roundable result
2693 extra = 3
2694 while True:
2695 coeff, exp = _dexp(c, e, p+extra)
2696 if coeff % (5*10**(len(str(coeff))-p-1)):
2697 break
2698 extra += 3
2699
2700 ans = Decimal((0, map(int, str(coeff)), exp))
2701
2702 # at this stage, ans should round correctly with *any*
2703 # rounding mode, not just with ROUND_HALF_EVEN
2704 context = context._shallow_copy()
2705 rounding = context._set_rounding(ROUND_HALF_EVEN)
2706 ans = ans._fix(context)
2707 context.rounding = rounding
2708
2709 return ans
2710
2711 def is_canonical(self):
2712 """Returns 1 if self is canonical; otherwise returns 0."""
2713 return Dec_p1
2714
2715 def is_finite(self):
2716 """Returns 1 if self is finite, otherwise returns 0.
2717
2718 For it to be finite, it must be neither infinite nor a NaN.
2719 """
2720 if self._is_special:
2721 return Dec_0
2722 else:
2723 return Dec_p1
2724
2725 def is_infinite(self):
2726 """Returns 1 if self is an Infinite, otherwise returns 0."""
2727 if self._isinfinity():
2728 return Dec_p1
2729 else:
2730 return Dec_0
2731
2732 def is_nan(self):
2733 """Returns 1 if self is qNaN or sNaN, otherwise returns 0."""
2734 if self._isnan():
2735 return Dec_p1
2736 else:
2737 return Dec_0
2738
2739 def is_normal(self, context=None):
2740 """Returns 1 if self is a normal number, otherwise returns 0."""
2741 if self._is_special:
2742 return Dec_0
2743 if not self:
2744 return Dec_0
2745 if context is None:
2746 context = getcontext()
2747 if context.Emin <= self.adjusted() <= context.Emax:
2748 return Dec_p1
2749 else:
2750 return Dec_0
2751
2752 def is_qnan(self):
2753 """Returns 1 if self is a quiet NaN, otherwise returns 0."""
2754 if self._isnan() == 1:
2755 return Dec_p1
2756 else:
2757 return Dec_0
2758
2759 def is_signed(self):
2760 """Returns 1 if self is negative, otherwise returns 0."""
2761 return Decimal(self._sign)
2762
2763 def is_snan(self):
2764 """Returns 1 if self is a signaling NaN, otherwise returns 0."""
2765 if self._isnan() == 2:
2766 return Dec_p1
2767 else:
2768 return Dec_0
2769
2770 def is_subnormal(self, context=None):
2771 """Returns 1 if self is subnormal, otherwise returns 0."""
2772 if self._is_special:
2773 return Dec_0
2774 if not self:
2775 return Dec_0
2776 if context is None:
2777 context = getcontext()
2778
2779 r = self._exp + len(self._int)
2780 if r <= context.Emin:
2781 return Dec_p1
2782 return Dec_0
2783
2784 def is_zero(self):
2785 """Returns 1 if self is a zero, otherwise returns 0."""
2786 if self:
2787 return Dec_0
2788 else:
2789 return Dec_p1
2790
2791 def _ln_exp_bound(self):
2792 """Compute a lower bound for the adjusted exponent of self.ln().
2793 In other words, compute r such that self.ln() >= 10**r. Assumes
2794 that self is finite and positive and that self != 1.
2795 """
2796
2797 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2798 adj = self._exp + len(self._int) - 1
2799 if adj >= 1:
2800 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2801 return len(str(adj*23//10)) - 1
2802 if adj <= -2:
2803 # argument <= 0.1
2804 return len(str((-1-adj)*23//10)) - 1
2805 op = _WorkRep(self)
2806 c, e = op.int, op.exp
2807 if adj == 0:
2808 # 1 < self < 10
2809 num = str(c-10**-e)
2810 den = str(c)
2811 return len(num) - len(den) - (num < den)
2812 # adj == -1, 0.1 <= self < 1
2813 return e + len(str(10**-e - c)) - 1
2814
2815
2816 def ln(self, context=None):
2817 """Returns the natural (base e) logarithm of self."""
2818
2819 if context is None:
2820 context = getcontext()
2821
2822 # ln(NaN) = NaN
2823 ans = self._check_nans(context=context)
2824 if ans:
2825 return ans
2826
2827 # ln(0.0) == -Infinity
2828 if not self:
2829 return negInf
2830
2831 # ln(Infinity) = Infinity
2832 if self._isinfinity() == 1:
2833 return Inf
2834
2835 # ln(1.0) == 0.0
2836 if self == Dec_p1:
2837 return Dec_0
2838
2839 # ln(negative) raises InvalidOperation
2840 if self._sign == 1:
2841 return context._raise_error(InvalidOperation,
2842 'ln of a negative value')
2843
2844 # result is irrational, so necessarily inexact
2845 op = _WorkRep(self)
2846 c, e = op.int, op.exp
2847 p = context.prec
2848
2849 # correctly rounded result: repeatedly increase precision by 3
2850 # until we get an unambiguously roundable result
2851 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2852 while True:
2853 coeff = _dlog(c, e, places)
2854 # assert len(str(abs(coeff)))-p >= 1
2855 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2856 break
2857 places += 3
2858 ans = Decimal((int(coeff<0), map(int, str(abs(coeff))), -places))
2859
2860 context = context._shallow_copy()
2861 rounding = context._set_rounding(ROUND_HALF_EVEN)
2862 ans = ans._fix(context)
2863 context.rounding = rounding
2864 return ans
2865
2866 def _log10_exp_bound(self):
2867 """Compute a lower bound for the adjusted exponent of self.log10().
2868 In other words, find r such that self.log10() >= 10**r.
2869 Assumes that self is finite and positive and that self != 1.
2870 """
2871
2872 # For x >= 10 or x < 0.1 we only need a bound on the integer
2873 # part of log10(self), and this comes directly from the
2874 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2875 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2876 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2877
2878 adj = self._exp + len(self._int) - 1
2879 if adj >= 1:
2880 # self >= 10
2881 return len(str(adj))-1
2882 if adj <= -2:
2883 # self < 0.1
2884 return len(str(-1-adj))-1
2885 op = _WorkRep(self)
2886 c, e = op.int, op.exp
2887 if adj == 0:
2888 # 1 < self < 10
2889 num = str(c-10**-e)
2890 den = str(231*c)
2891 return len(num) - len(den) - (num < den) + 2
2892 # adj == -1, 0.1 <= self < 1
2893 num = str(10**-e-c)
2894 return len(num) + e - (num < "231") - 1
2895
2896 def log10(self, context=None):
2897 """Returns the base 10 logarithm of self."""
2898
2899 if context is None:
2900 context = getcontext()
2901
2902 # log10(NaN) = NaN
2903 ans = self._check_nans(context=context)
2904 if ans:
2905 return ans
2906
2907 # log10(0.0) == -Infinity
2908 if not self:
2909 return negInf
2910
2911 # log10(Infinity) = Infinity
2912 if self._isinfinity() == 1:
2913 return Inf
2914
2915 # log10(negative or -Infinity) raises InvalidOperation
2916 if self._sign == 1:
2917 return context._raise_error(InvalidOperation,
2918 'log10 of a negative value')
2919
2920 # log10(10**n) = n
2921 if self._int[0] == 1 and self._int[1:] == (0,)*(len(self._int) - 1):
2922 # answer may need rounding
2923 ans = Decimal(self._exp + len(self._int) - 1)
2924 else:
2925 # result is irrational, so necessarily inexact
2926 op = _WorkRep(self)
2927 c, e = op.int, op.exp
2928 p = context.prec
2929
2930 # correctly rounded result: repeatedly increase precision
2931 # until result is unambiguously roundable
2932 places = p-self._log10_exp_bound()+2
2933 while True:
2934 coeff = _dlog10(c, e, places)
2935 # assert len(str(abs(coeff)))-p >= 1
2936 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2937 break
2938 places += 3
2939 ans = Decimal((int(coeff<0), map(int, str(abs(coeff))), -places))
2940
2941 context = context._shallow_copy()
2942 rounding = context._set_rounding(ROUND_HALF_EVEN)
2943 ans = ans._fix(context)
2944 context.rounding = rounding
2945 return ans
2946
2947 def logb(self, context=None):
2948 """ Returns the exponent of the magnitude of self's MSD.
2949
2950 The result is the integer which is the exponent of the magnitude
2951 of the most significant digit of self (as though it were truncated
2952 to a single digit while maintaining the value of that digit and
2953 without limiting the resulting exponent).
2954 """
2955 # logb(NaN) = NaN
2956 ans = self._check_nans(context=context)
2957 if ans:
2958 return ans
2959
2960 if context is None:
2961 context = getcontext()
2962
2963 # logb(+/-Inf) = +Inf
2964 if self._isinfinity():
2965 return Inf
2966
2967 # logb(0) = -Inf, DivisionByZero
2968 if not self:
2969 return context._raise_error(DivisionByZero, 'logb(0)', -1)
2970
2971 # otherwise, simply return the adjusted exponent of self, as a
2972 # Decimal. Note that no attempt is made to fit the result
2973 # into the current context.
2974 return Decimal(self.adjusted())
2975
2976 def _islogical(self):
2977 """Return True if self is a logical operand.
2978
2979 For being logical, it must be a finite numbers with a sign of 0,
2980 an exponent of 0, and a coefficient whose digits must all be
2981 either 0 or 1.
2982 """
2983 if self._sign != 0 or self._exp != 0:
2984 return False
2985 for dig in self._int:
2986 if dig not in (0, 1):
2987 return False
2988 return True
2989
2990 def _fill_logical(self, context, opa, opb):
2991 dif = context.prec - len(opa)
2992 if dif > 0:
2993 opa = (0,)*dif + opa
2994 elif dif < 0:
2995 opa = opa[-context.prec:]
2996 dif = context.prec - len(opb)
2997 if dif > 0:
2998 opb = (0,)*dif + opb
2999 elif dif < 0:
3000 opb = opb[-context.prec:]
3001 return opa, opb
3002
3003 def logical_and(self, other, context=None):
3004 """Applies an 'and' operation between self and other's digits."""
3005 if context is None:
3006 context = getcontext()
3007 if not self._islogical() or not other._islogical():
3008 return context._raise_error(InvalidOperation)
3009
3010 # fill to context.prec
3011 (opa, opb) = self._fill_logical(context, self._int, other._int)
3012
3013 # make the operation, and clean starting zeroes
3014 result = [a&b for a,b in zip(opa,opb)]
3015 for i,d in enumerate(result):
3016 if d == 1:
3017 break
3018 result = tuple(result[i:])
3019
3020 # if empty, we must have at least a zero
3021 if not result:
3022 result = (0,)
3023 return Decimal((0, result, 0))
3024
3025 def logical_invert(self, context=None):
3026 """Invert all its digits."""
3027 if context is None:
3028 context = getcontext()
3029 return self.logical_xor(Decimal((0,(1,)*context.prec,0)), context)
3030
3031 def logical_or(self, other, context=None):
3032 """Applies an 'or' operation between self and other's digits."""
3033 if context is None:
3034 context = getcontext()
3035 if not self._islogical() or not other._islogical():
3036 return context._raise_error(InvalidOperation)
3037
3038 # fill to context.prec
3039 (opa, opb) = self._fill_logical(context, self._int, other._int)
3040
3041 # make the operation, and clean starting zeroes
3042 result = [a|b for a,b in zip(opa,opb)]
3043 for i,d in enumerate(result):
3044 if d == 1:
3045 break
3046 result = tuple(result[i:])
3047
3048 # if empty, we must have at least a zero
3049 if not result:
3050 result = (0,)
3051 return Decimal((0, result, 0))
3052
3053 def logical_xor(self, other, context=None):
3054 """Applies an 'xor' operation between self and other's digits."""
3055 if context is None:
3056 context = getcontext()
3057 if not self._islogical() or not other._islogical():
3058 return context._raise_error(InvalidOperation)
3059
3060 # fill to context.prec
3061 (opa, opb) = self._fill_logical(context, self._int, other._int)
3062
3063 # make the operation, and clean starting zeroes
3064 result = [a^b for a,b in zip(opa,opb)]
3065 for i,d in enumerate(result):
3066 if d == 1:
3067 break
3068 result = tuple(result[i:])
3069
3070 # if empty, we must have at least a zero
3071 if not result:
3072 result = (0,)
3073 return Decimal((0, result, 0))
3074
3075 def max_mag(self, other, context=None):
3076 """Compares the values numerically with their sign ignored."""
3077 other = _convert_other(other, raiseit=True)
3078
3079 if self._is_special or other._is_special:
3080 # If one operand is a quiet NaN and the other is number, then the
3081 # number is always returned
3082 sn = self._isnan()
3083 on = other._isnan()
3084 if sn or on:
3085 if on == 1 and sn != 2:
3086 return self
3087 if sn == 1 and on != 2:
3088 return other
3089 return self._check_nans(other, context)
3090
3091 c = self.copy_abs().__cmp__(other.copy_abs())
3092 if c == 0:
3093 c = self.compare_total(other)
3094
3095 if c == -1:
3096 ans = other
3097 else:
3098 ans = self
3099
3100 if context is None:
3101 context = getcontext()
3102 if context._rounding_decision == ALWAYS_ROUND:
3103 return ans._fix(context)
3104 return ans
3105
3106 def min_mag(self, other, context=None):
3107 """Compares the values numerically with their sign ignored."""
3108 other = _convert_other(other, raiseit=True)
3109
3110 if self._is_special or other._is_special:
3111 # If one operand is a quiet NaN and the other is number, then the
3112 # number is always returned
3113 sn = self._isnan()
3114 on = other._isnan()
3115 if sn or on:
3116 if on == 1 and sn != 2:
3117 return self
3118 if sn == 1 and on != 2:
3119 return other
3120 return self._check_nans(other, context)
3121
3122 c = self.copy_abs().__cmp__(other.copy_abs())
3123 if c == 0:
3124 c = self.compare_total(other)
3125
3126 if c == -1:
3127 ans = self
3128 else:
3129 ans = other
3130
3131 if context is None:
3132 context = getcontext()
3133 if context._rounding_decision == ALWAYS_ROUND:
3134 return ans._fix(context)
3135 return ans
3136
3137 def next_minus(self, context=None):
3138 """Returns the largest representable number smaller than itself."""
3139 if context is None:
3140 context = getcontext()
3141
3142 ans = self._check_nans(context=context)
3143 if ans:
3144 return ans
3145
3146 if self._isinfinity() == -1:
3147 return negInf
3148 if self._isinfinity() == 1:
3149 return Decimal((0, (9,)*context.prec, context.Etop()))
3150
3151 context = context.copy()
3152 context._set_rounding(ROUND_FLOOR)
3153 context._ignore_all_flags()
3154 new_self = self._fix(context)
3155 if new_self != self:
3156 return new_self
3157 return self.__sub__(Decimal((0, (1,), context.Etiny()-1)), context)
3158
3159 def next_plus(self, context=None):
3160 """Returns the smallest representable number larger than itself."""
3161 if context is None:
3162 context = getcontext()
3163
3164 ans = self._check_nans(context=context)
3165 if ans:
3166 return ans
3167
3168 if self._isinfinity() == 1:
3169 return Inf
3170 if self._isinfinity() == -1:
3171 return Decimal((1, (9,)*context.prec, context.Etop()))
3172
3173 context = context.copy()
3174 context._set_rounding(ROUND_CEILING)
3175 context._ignore_all_flags()
3176 new_self = self._fix(context)
3177 if new_self != self:
3178 return new_self
3179 return self.__add__(Decimal((0, (1,), context.Etiny()-1)), context)
3180
3181 def next_toward(self, other, context=None):
3182 """Returns the number closest to self, in the direction towards other.
3183
3184 The result is the closest representable number to self
3185 (excluding self) that is in the direction towards other,
3186 unless both have the same value. If the two operands are
3187 numerically equal, then the result is a copy of self with the
3188 sign set to be the same as the sign of other.
3189 """
3190 other = _convert_other(other, raiseit=True)
3191
3192 if context is None:
3193 context = getcontext()
3194
3195 ans = self._check_nans(other, context)
3196 if ans:
3197 return ans
3198
3199 comparison = self.__cmp__(other)
3200 if comparison == 0:
3201 return Decimal((other._sign, self._int, self._exp))
3202
3203 if comparison == -1:
3204 ans = self.next_plus(context)
3205 else: # comparison == 1
3206 ans = self.next_minus(context)
3207
3208 # decide which flags to raise using value of ans
3209 if ans._isinfinity():
3210 context._raise_error(Overflow,
3211 'Infinite result from next_toward',
3212 ans._sign)
3213 context._raise_error(Rounded)
3214 context._raise_error(Inexact)
3215 elif ans.adjusted() < context.Emin:
3216 context._raise_error(Underflow)
3217 context._raise_error(Subnormal)
3218 context._raise_error(Rounded)
3219 context._raise_error(Inexact)
3220 # if precision == 1 then we don't raise Clamped for a
3221 # result 0E-Etiny.
3222 if not ans:
3223 context._raise_error(Clamped)
3224
3225 return ans
3226
3227 def number_class(self, context=None):
3228 """Returns an indication of the class of self.
3229
3230 The class is one of the following strings:
3231 -sNaN
3232 -NaN
3233 -Infinity
3234 -Normal
3235 -Subnormal
3236 -Zero
3237 +Zero
3238 +Subnormal
3239 +Normal
3240 +Infinity
3241 """
3242 if self.is_snan():
3243 return "sNaN"
3244 if self.is_qnan():
3245 return "NaN"
3246 inf = self._isinfinity()
3247 if inf == 1:
3248 return "+Infinity"
3249 if inf == -1:
3250 return "-Infinity"
3251 if self.is_zero():
3252 if self._sign:
3253 return "-Zero"
3254 else:
3255 return "+Zero"
3256 if context is None:
3257 context = getcontext()
3258 if self.is_subnormal(context=context):
3259 if self._sign:
3260 return "-Subnormal"
3261 else:
3262 return "+Subnormal"
3263 # just a normal, regular, boring number, :)
3264 if self._sign:
3265 return "-Normal"
3266 else:
3267 return "+Normal"
3268
3269 def radix(self):
3270 """Just returns 10, as this is Decimal, :)"""
3271 return Decimal(10)
3272
3273 def rotate(self, other, context=None):
3274 """Returns a rotated copy of self, value-of-other times."""
3275 if context is None:
3276 context = getcontext()
3277
3278 ans = self._check_nans(other, context)
3279 if ans:
3280 return ans
3281
3282 if other._exp != 0:
3283 return context._raise_error(InvalidOperation)
3284 if not (-context.prec <= int(other) <= context.prec):
3285 return context._raise_error(InvalidOperation)
3286
3287 if self._isinfinity():
3288 return self
3289
3290 # get values, pad if necessary
3291 torot = int(other)
3292 rotdig = self._int
3293 topad = context.prec - len(rotdig)
3294 if topad:
3295 rotdig = ((0,)*topad) + rotdig
3296
3297 # let's rotate!
3298 rotated = rotdig[torot:] + rotdig[:torot]
3299
3300 # clean starting zeroes
3301 for i,d in enumerate(rotated):
3302 if d != 0:
3303 break
3304 rotated = rotated[i:]
3305
3306 return Decimal((self._sign, rotated, self._exp))
3307
3308
3309 def scaleb (self, other, context=None):
3310 """Returns self operand after adding the second value to its exp."""
3311 if context is None:
3312 context = getcontext()
3313
3314 ans = self._check_nans(other, context)
3315 if ans:
3316 return ans
3317
3318 if other._exp != 0:
3319 return context._raise_error(InvalidOperation)
3320 liminf = -2 * (context.Emax + context.prec)
3321 limsup = 2 * (context.Emax + context.prec)
3322 if not (liminf <= int(other) <= limsup):
3323 return context._raise_error(InvalidOperation)
3324
3325 if self._isinfinity():
3326 return self
3327
3328 d = Decimal((self._sign, self._int, self._exp + int(other)))
3329 d = d._fix(context)
3330 return d
3331
3332 def shift(self, other, context=None):
3333 """Returns a shifted copy of self, value-of-other times."""
3334 if context is None:
3335 context = getcontext()
3336
3337 ans = self._check_nans(other, context)
3338 if ans:
3339 return ans
3340
3341 if other._exp != 0:
3342 return context._raise_error(InvalidOperation)
3343 if not (-context.prec <= int(other) <= context.prec):
3344 return context._raise_error(InvalidOperation)
3345
3346 if self._isinfinity():
3347 return self
3348
3349 # get values, pad if necessary
3350 torot = int(other)
3351 if not torot:
3352 return self
3353 rotdig = self._int
3354 topad = context.prec - len(rotdig)
3355 if topad:
3356 rotdig = ((0,)*topad) + rotdig
3357
3358 # let's shift!
3359 if torot < 0:
3360 rotated = rotdig[:torot]
3361 else:
3362 rotated = (rotdig + ((0,) * torot))
3363 rotated = rotated[-context.prec:]
3364
3365 # clean starting zeroes
3366 if rotated:
3367 for i,d in enumerate(rotated):
3368 if d != 0:
3369 break
3370 rotated = rotated[i:]
3371 else:
3372 rotated = (0,)
3373
3374 return Decimal((self._sign, rotated, self._exp))
3375
3376
Facundo Batista59c58842007-04-10 12:58:45 +00003377 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003378 def __reduce__(self):
3379 return (self.__class__, (str(self),))
3380
3381 def __copy__(self):
3382 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003383 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003384 return self.__class__(str(self))
3385
3386 def __deepcopy__(self, memo):
3387 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003388 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003389 return self.__class__(str(self))
3390
Facundo Batista59c58842007-04-10 12:58:45 +00003391##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003392
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003393
3394# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003395rounding_functions = [name for name in Decimal.__dict__.keys()
3396 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003397for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003398 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003399 globalname = name[1:].upper()
3400 val = globals()[globalname]
3401 Decimal._pick_rounding_function[val] = name
3402
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003403del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003404
Nick Coghlanced12182006-09-02 03:54:17 +00003405class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003406 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003407
Nick Coghlanced12182006-09-02 03:54:17 +00003408 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003409 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003410 """
3411 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003412 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003413 def __enter__(self):
3414 self.saved_context = getcontext()
3415 setcontext(self.new_context)
3416 return self.new_context
3417 def __exit__(self, t, v, tb):
3418 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003419
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003420class Context(object):
3421 """Contains the context for a Decimal instance.
3422
3423 Contains:
3424 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003425 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003426 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003427 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003428 raised when it is caused. Otherwise, a value is
3429 substituted in.
3430 flags - When an exception is caused, flags[exception] is incremented.
3431 (Whether or not the trap_enabler is set)
3432 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003433 Emin - Minimum exponent
3434 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003435 capitals - If 1, 1*10^1 is printed as 1E+1.
3436 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003437 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003438 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003439
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003440 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003441 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003442 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003443 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003444 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003445 _ignored_flags=None):
3446 if flags is None:
3447 flags = []
3448 if _ignored_flags is None:
3449 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003450 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003451 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003452 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003453 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003454 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003455 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003456 for name, val in locals().items():
3457 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003458 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003459 else:
3460 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003461 del self.self
3462
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003463 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003464 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003465 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003466 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3467 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3468 % vars(self))
3469 names = [f.__name__ for f, v in self.flags.items() if v]
3470 s.append('flags=[' + ', '.join(names) + ']')
3471 names = [t.__name__ for t, v in self.traps.items() if v]
3472 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003473 return ', '.join(s) + ')'
3474
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003475 def clear_flags(self):
3476 """Reset all flags to zero"""
3477 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003478 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003479
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003480 def _shallow_copy(self):
3481 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003482 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003483 self._rounding_decision, self.Emin, self.Emax,
3484 self.capitals, self._clamp, self._ignored_flags)
3485 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003486
3487 def copy(self):
3488 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003489 nc = Context(self.prec, self.rounding, self.traps.copy(),
3490 self.flags.copy(), self._rounding_decision, self.Emin,
3491 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003492 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003493 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003494
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003495 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003496 """Handles an error
3497
3498 If the flag is in _ignored_flags, returns the default response.
3499 Otherwise, it increments the flag, then, if the corresponding
3500 trap_enabler is set, it reaises the exception. Otherwise, it returns
3501 the default value after incrementing the flag.
3502 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003503 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003504 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003505 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003506 return error().handle(self, *args)
3507
3508 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003509 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003510 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003511 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003512
3513 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003514 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003515 raise error, explanation
3516
3517 def _ignore_all_flags(self):
3518 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003519 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003520
3521 def _ignore_flags(self, *flags):
3522 """Ignore the flags, if they are raised"""
3523 # Do not mutate-- This way, copies of a context leave the original
3524 # alone.
3525 self._ignored_flags = (self._ignored_flags + list(flags))
3526 return list(flags)
3527
3528 def _regard_flags(self, *flags):
3529 """Stop ignoring the flags, if they are raised"""
3530 if flags and isinstance(flags[0], (tuple,list)):
3531 flags = flags[0]
3532 for flag in flags:
3533 self._ignored_flags.remove(flag)
3534
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003535 def __hash__(self):
3536 """A Context cannot be hashed."""
3537 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003538 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003539
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003540 def Etiny(self):
3541 """Returns Etiny (= Emin - prec + 1)"""
3542 return int(self.Emin - self.prec + 1)
3543
3544 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003545 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003546 return int(self.Emax - self.prec + 1)
3547
3548 def _set_rounding_decision(self, type):
3549 """Sets the rounding decision.
3550
3551 Sets the rounding decision, and returns the current (previous)
3552 rounding decision. Often used like:
3553
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003554 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003555 # That so you don't change the calling context
3556 # if an error occurs in the middle (say DivisionImpossible is raised).
3557
3558 rounding = context._set_rounding_decision(NEVER_ROUND)
3559 instance = instance / Decimal(2)
3560 context._set_rounding_decision(rounding)
3561
3562 This will make it not round for that operation.
3563 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003564
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003565 rounding = self._rounding_decision
3566 self._rounding_decision = type
3567 return rounding
3568
3569 def _set_rounding(self, type):
3570 """Sets the rounding type.
3571
3572 Sets the rounding type, and returns the current (previous)
3573 rounding type. Often used like:
3574
3575 context = context.copy()
3576 # so you don't change the calling context
3577 # if an error occurs in the middle.
3578 rounding = context._set_rounding(ROUND_UP)
3579 val = self.__sub__(other, context=context)
3580 context._set_rounding(rounding)
3581
3582 This will make it round up for that operation.
3583 """
3584 rounding = self.rounding
3585 self.rounding= type
3586 return rounding
3587
Raymond Hettingerfed52962004-07-14 15:41:57 +00003588 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003589 """Creates a new Decimal instance but using self as context."""
3590 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003591 if d._isnan() and len(d._int) > self.prec - self._clamp:
3592 return self._raise_error(ConversionSyntax,
3593 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003594 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003595
Facundo Batista59c58842007-04-10 12:58:45 +00003596 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003597 def abs(self, a):
3598 """Returns the absolute value of the operand.
3599
3600 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003601 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003602 the plus operation on the operand.
3603
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003604 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003605 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003606 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003607 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003608 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003609 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003610 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003611 Decimal("101.5")
3612 """
3613 return a.__abs__(context=self)
3614
3615 def add(self, a, b):
3616 """Return the sum of the two operands.
3617
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003618 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003619 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003620 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003621 Decimal("1.02E+4")
3622 """
3623 return a.__add__(b, context=self)
3624
3625 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003626 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003627
Facundo Batista353750c2007-09-13 18:13:15 +00003628 def canonical(self, a):
3629 """Returns the same Decimal object.
3630
3631 As we do not have different encodings for the same number, the
3632 received object already is in its canonical form.
3633
3634 >>> ExtendedContext.canonical(Decimal('2.50'))
3635 Decimal("2.50")
3636 """
3637 return a.canonical(context=self)
3638
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003639 def compare(self, a, b):
3640 """Compares values numerically.
3641
3642 If the signs of the operands differ, a value representing each operand
3643 ('-1' if the operand is less than zero, '0' if the operand is zero or
3644 negative zero, or '1' if the operand is greater than zero) is used in
3645 place of that operand for the comparison instead of the actual
3646 operand.
3647
3648 The comparison is then effected by subtracting the second operand from
3649 the first and then returning a value according to the result of the
3650 subtraction: '-1' if the result is less than zero, '0' if the result is
3651 zero or negative zero, or '1' if the result is greater than zero.
3652
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003653 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003654 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003655 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003656 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003657 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003658 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003659 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003660 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003661 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003662 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003663 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003664 Decimal("-1")
3665 """
3666 return a.compare(b, context=self)
3667
Facundo Batista353750c2007-09-13 18:13:15 +00003668 def compare_signal(self, a, b):
3669 """Compares the values of the two operands numerically.
3670
3671 It's pretty much like compare(), but all NaNs signal, with signaling
3672 NaNs taking precedence over quiet NaNs.
3673
3674 >>> c = ExtendedContext
3675 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3676 Decimal("-1")
3677 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3678 Decimal("0")
3679 >>> c.flags[InvalidOperation] = 0
3680 >>> print c.flags[InvalidOperation]
3681 0
3682 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3683 Decimal("NaN")
3684 >>> print c.flags[InvalidOperation]
3685 1
3686 >>> c.flags[InvalidOperation] = 0
3687 >>> print c.flags[InvalidOperation]
3688 0
3689 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3690 Decimal("NaN")
3691 >>> print c.flags[InvalidOperation]
3692 1
3693 """
3694 return a.compare_signal(b, context=self)
3695
3696 def compare_total(self, a, b):
3697 """Compares two operands using their abstract representation.
3698
3699 This is not like the standard compare, which use their numerical
3700 value. Note that a total ordering is defined for all possible abstract
3701 representations.
3702
3703 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3704 Decimal("-1")
3705 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3706 Decimal("-1")
3707 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3708 Decimal("-1")
3709 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3710 Decimal("0")
3711 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3712 Decimal("1")
3713 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3714 Decimal("-1")
3715 """
3716 return a.compare_total(b)
3717
3718 def compare_total_mag(self, a, b):
3719 """Compares two operands using their abstract representation ignoring sign.
3720
3721 Like compare_total, but with operand's sign ignored and assumed to be 0.
3722 """
3723 return a.compare_total_mag(b)
3724
3725 def copy_abs(self, a):
3726 """Returns a copy of the operand with the sign set to 0.
3727
3728 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3729 Decimal("2.1")
3730 >>> ExtendedContext.copy_abs(Decimal('-100'))
3731 Decimal("100")
3732 """
3733 return a.copy_abs()
3734
3735 def copy_decimal(self, a):
3736 """Returns a copy of the decimal objet.
3737
3738 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3739 Decimal("2.1")
3740 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3741 Decimal("-1.00")
3742 """
3743 return a
3744
3745 def copy_negate(self, a):
3746 """Returns a copy of the operand with the sign inverted.
3747
3748 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3749 Decimal("-101.5")
3750 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3751 Decimal("101.5")
3752 """
3753 return a.copy_negate()
3754
3755 def copy_sign(self, a, b):
3756 """Copies the second operand's sign to the first one.
3757
3758 In detail, it returns a copy of the first operand with the sign
3759 equal to the sign of the second operand.
3760
3761 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3762 Decimal("1.50")
3763 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3764 Decimal("1.50")
3765 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3766 Decimal("-1.50")
3767 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3768 Decimal("-1.50")
3769 """
3770 return a.copy_sign(b)
3771
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003772 def divide(self, a, b):
3773 """Decimal division in a specified context.
3774
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003775 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003776 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003777 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003778 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003779 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003780 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003781 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003782 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003783 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003784 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003785 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003786 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003787 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003788 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003789 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003790 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003791 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003792 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003793 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003794 Decimal("1.20E+6")
3795 """
3796 return a.__div__(b, context=self)
3797
3798 def divide_int(self, a, b):
3799 """Divides two numbers and returns the integer part of the result.
3800
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003801 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003802 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003803 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003804 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003805 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003806 Decimal("3")
3807 """
3808 return a.__floordiv__(b, context=self)
3809
3810 def divmod(self, a, b):
3811 return a.__divmod__(b, context=self)
3812
Facundo Batista353750c2007-09-13 18:13:15 +00003813 def exp(self, a):
3814 """Returns e ** a.
3815
3816 >>> c = ExtendedContext.copy()
3817 >>> c.Emin = -999
3818 >>> c.Emax = 999
3819 >>> c.exp(Decimal('-Infinity'))
3820 Decimal("0")
3821 >>> c.exp(Decimal('-1'))
3822 Decimal("0.367879441")
3823 >>> c.exp(Decimal('0'))
3824 Decimal("1")
3825 >>> c.exp(Decimal('1'))
3826 Decimal("2.71828183")
3827 >>> c.exp(Decimal('0.693147181'))
3828 Decimal("2.00000000")
3829 >>> c.exp(Decimal('+Infinity'))
3830 Decimal("Infinity")
3831 """
3832 return a.exp(context=self)
3833
3834 def fma(self, a, b, c):
3835 """Returns a multiplied by b, plus c.
3836
3837 The first two operands are multiplied together, using multiply,
3838 the third operand is then added to the result of that
3839 multiplication, using add, all with only one final rounding.
3840
3841 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3842 Decimal("22")
3843 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3844 Decimal("-8")
3845 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3846 Decimal("1.38435736E+12")
3847 """
3848 return a.fma(b, c, context=self)
3849
3850 def is_canonical(self, a):
3851 """Returns 1 if the operand is canonical; otherwise returns 0.
3852
3853 >>> ExtendedContext.is_canonical(Decimal('2.50'))
3854 Decimal("1")
3855 """
3856 return Dec_p1
3857
3858 def is_finite(self, a):
3859 """Returns 1 if the operand is finite, otherwise returns 0.
3860
3861 For it to be finite, it must be neither infinite nor a NaN.
3862
3863 >>> ExtendedContext.is_finite(Decimal('2.50'))
3864 Decimal("1")
3865 >>> ExtendedContext.is_finite(Decimal('-0.3'))
3866 Decimal("1")
3867 >>> ExtendedContext.is_finite(Decimal('0'))
3868 Decimal("1")
3869 >>> ExtendedContext.is_finite(Decimal('Inf'))
3870 Decimal("0")
3871 >>> ExtendedContext.is_finite(Decimal('NaN'))
3872 Decimal("0")
3873 """
3874 return a.is_finite()
3875
3876 def is_infinite(self, a):
3877 """Returns 1 if the operand is an Infinite, otherwise returns 0.
3878
3879 >>> ExtendedContext.is_infinite(Decimal('2.50'))
3880 Decimal("0")
3881 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
3882 Decimal("1")
3883 >>> ExtendedContext.is_infinite(Decimal('NaN'))
3884 Decimal("0")
3885 """
3886 return a.is_infinite()
3887
3888 def is_nan(self, a):
3889 """Returns 1 if the operand is qNaN or sNaN, otherwise returns 0.
3890
3891 >>> ExtendedContext.is_nan(Decimal('2.50'))
3892 Decimal("0")
3893 >>> ExtendedContext.is_nan(Decimal('NaN'))
3894 Decimal("1")
3895 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
3896 Decimal("1")
3897 """
3898 return a.is_nan()
3899
3900 def is_normal(self, a):
3901 """Returns 1 if the operand is a normal number, otherwise returns 0.
3902
3903 >>> c = ExtendedContext.copy()
3904 >>> c.Emin = -999
3905 >>> c.Emax = 999
3906 >>> c.is_normal(Decimal('2.50'))
3907 Decimal("1")
3908 >>> c.is_normal(Decimal('0.1E-999'))
3909 Decimal("0")
3910 >>> c.is_normal(Decimal('0.00'))
3911 Decimal("0")
3912 >>> c.is_normal(Decimal('-Inf'))
3913 Decimal("0")
3914 >>> c.is_normal(Decimal('NaN'))
3915 Decimal("0")
3916 """
3917 return a.is_normal(context=self)
3918
3919 def is_qnan(self, a):
3920 """Returns 1 if the operand is a quiet NaN, otherwise returns 0.
3921
3922 >>> ExtendedContext.is_qnan(Decimal('2.50'))
3923 Decimal("0")
3924 >>> ExtendedContext.is_qnan(Decimal('NaN'))
3925 Decimal("1")
3926 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
3927 Decimal("0")
3928 """
3929 return a.is_qnan()
3930
3931 def is_signed(self, a):
3932 """Returns 1 if the operand is negative, otherwise returns 0.
3933
3934 >>> ExtendedContext.is_signed(Decimal('2.50'))
3935 Decimal("0")
3936 >>> ExtendedContext.is_signed(Decimal('-12'))
3937 Decimal("1")
3938 >>> ExtendedContext.is_signed(Decimal('-0'))
3939 Decimal("1")
3940 """
3941 return a.is_signed()
3942
3943 def is_snan(self, a):
3944 """Returns 1 if the operand is a signaling NaN, otherwise returns 0.
3945
3946 >>> ExtendedContext.is_snan(Decimal('2.50'))
3947 Decimal("0")
3948 >>> ExtendedContext.is_snan(Decimal('NaN'))
3949 Decimal("0")
3950 >>> ExtendedContext.is_snan(Decimal('sNaN'))
3951 Decimal("1")
3952 """
3953 return a.is_snan()
3954
3955 def is_subnormal(self, a):
3956 """Returns 1 if the operand is subnormal, otherwise returns 0.
3957
3958 >>> c = ExtendedContext.copy()
3959 >>> c.Emin = -999
3960 >>> c.Emax = 999
3961 >>> c.is_subnormal(Decimal('2.50'))
3962 Decimal("0")
3963 >>> c.is_subnormal(Decimal('0.1E-999'))
3964 Decimal("1")
3965 >>> c.is_subnormal(Decimal('0.00'))
3966 Decimal("0")
3967 >>> c.is_subnormal(Decimal('-Inf'))
3968 Decimal("0")
3969 >>> c.is_subnormal(Decimal('NaN'))
3970 Decimal("0")
3971 """
3972 return a.is_subnormal(context=self)
3973
3974 def is_zero(self, a):
3975 """Returns 1 if the operand is a zero, otherwise returns 0.
3976
3977 >>> ExtendedContext.is_zero(Decimal('0'))
3978 Decimal("1")
3979 >>> ExtendedContext.is_zero(Decimal('2.50'))
3980 Decimal("0")
3981 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
3982 Decimal("1")
3983 """
3984 return a.is_zero()
3985
3986 def ln(self, a):
3987 """Returns the natural (base e) logarithm of the operand.
3988
3989 >>> c = ExtendedContext.copy()
3990 >>> c.Emin = -999
3991 >>> c.Emax = 999
3992 >>> c.ln(Decimal('0'))
3993 Decimal("-Infinity")
3994 >>> c.ln(Decimal('1.000'))
3995 Decimal("0")
3996 >>> c.ln(Decimal('2.71828183'))
3997 Decimal("1.00000000")
3998 >>> c.ln(Decimal('10'))
3999 Decimal("2.30258509")
4000 >>> c.ln(Decimal('+Infinity'))
4001 Decimal("Infinity")
4002 """
4003 return a.ln(context=self)
4004
4005 def log10(self, a):
4006 """Returns the base 10 logarithm of the operand.
4007
4008 >>> c = ExtendedContext.copy()
4009 >>> c.Emin = -999
4010 >>> c.Emax = 999
4011 >>> c.log10(Decimal('0'))
4012 Decimal("-Infinity")
4013 >>> c.log10(Decimal('0.001'))
4014 Decimal("-3")
4015 >>> c.log10(Decimal('1.000'))
4016 Decimal("0")
4017 >>> c.log10(Decimal('2'))
4018 Decimal("0.301029996")
4019 >>> c.log10(Decimal('10'))
4020 Decimal("1")
4021 >>> c.log10(Decimal('70'))
4022 Decimal("1.84509804")
4023 >>> c.log10(Decimal('+Infinity'))
4024 Decimal("Infinity")
4025 """
4026 return a.log10(context=self)
4027
4028 def logb(self, a):
4029 """ Returns the exponent of the magnitude of the operand's MSD.
4030
4031 The result is the integer which is the exponent of the magnitude
4032 of the most significant digit of the operand (as though the
4033 operand were truncated to a single digit while maintaining the
4034 value of that digit and without limiting the resulting exponent).
4035
4036 >>> ExtendedContext.logb(Decimal('250'))
4037 Decimal("2")
4038 >>> ExtendedContext.logb(Decimal('2.50'))
4039 Decimal("0")
4040 >>> ExtendedContext.logb(Decimal('0.03'))
4041 Decimal("-2")
4042 >>> ExtendedContext.logb(Decimal('0'))
4043 Decimal("-Infinity")
4044 """
4045 return a.logb(context=self)
4046
4047 def logical_and(self, a, b):
4048 """Applies the logical operation 'and' between each operand's digits.
4049
4050 The operands must be both logical numbers.
4051
4052 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4053 Decimal("0")
4054 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4055 Decimal("0")
4056 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4057 Decimal("0")
4058 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4059 Decimal("1")
4060 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4061 Decimal("1000")
4062 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4063 Decimal("10")
4064 """
4065 return a.logical_and(b, context=self)
4066
4067 def logical_invert(self, a):
4068 """Invert all the digits in the operand.
4069
4070 The operand must be a logical number.
4071
4072 >>> ExtendedContext.logical_invert(Decimal('0'))
4073 Decimal("111111111")
4074 >>> ExtendedContext.logical_invert(Decimal('1'))
4075 Decimal("111111110")
4076 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4077 Decimal("0")
4078 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4079 Decimal("10101010")
4080 """
4081 return a.logical_invert(context=self)
4082
4083 def logical_or(self, a, b):
4084 """Applies the logical operation 'or' between each operand's digits.
4085
4086 The operands must be both logical numbers.
4087
4088 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4089 Decimal("0")
4090 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4091 Decimal("1")
4092 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4093 Decimal("1")
4094 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4095 Decimal("1")
4096 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4097 Decimal("1110")
4098 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4099 Decimal("1110")
4100 """
4101 return a.logical_or(b, context=self)
4102
4103 def logical_xor(self, a, b):
4104 """Applies the logical operation 'xor' between each operand's digits.
4105
4106 The operands must be both logical numbers.
4107
4108 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4109 Decimal("0")
4110 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4111 Decimal("1")
4112 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4113 Decimal("1")
4114 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4115 Decimal("0")
4116 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4117 Decimal("110")
4118 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4119 Decimal("1101")
4120 """
4121 return a.logical_xor(b, context=self)
4122
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004123 def max(self, a,b):
4124 """max compares two values numerically and returns the maximum.
4125
4126 If either operand is a NaN then the general rules apply.
4127 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004128 operation. If they are numerically equal then the left-hand operand
4129 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004130 infinity) of the two operands is chosen as the result.
4131
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004132 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004133 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004134 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004135 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004136 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004137 Decimal("1")
4138 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4139 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004140 """
4141 return a.max(b, context=self)
4142
Facundo Batista353750c2007-09-13 18:13:15 +00004143 def max_mag(self, a, b):
4144 """Compares the values numerically with their sign ignored."""
4145 return a.max_mag(b, context=self)
4146
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004147 def min(self, a,b):
4148 """min compares two values numerically and returns the minimum.
4149
4150 If either operand is a NaN then the general rules apply.
4151 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004152 operation. If they are numerically equal then the left-hand operand
4153 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004154 infinity) of the two operands is chosen as the result.
4155
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004156 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004157 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004158 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004159 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004160 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004161 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004162 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4163 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004164 """
4165 return a.min(b, context=self)
4166
Facundo Batista353750c2007-09-13 18:13:15 +00004167 def min_mag(self, a, b):
4168 """Compares the values numerically with their sign ignored."""
4169 return a.min_mag(b, context=self)
4170
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004171 def minus(self, a):
4172 """Minus corresponds to unary prefix minus in Python.
4173
4174 The operation is evaluated using the same rules as subtract; the
4175 operation minus(a) is calculated as subtract('0', a) where the '0'
4176 has the same exponent as the operand.
4177
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004178 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004179 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004180 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004181 Decimal("1.3")
4182 """
4183 return a.__neg__(context=self)
4184
4185 def multiply(self, a, b):
4186 """multiply multiplies two operands.
4187
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004188 If either operand is a special value then the general rules apply.
4189 Otherwise, the operands are multiplied together ('long multiplication'),
4190 resulting in a number which may be as long as the sum of the lengths
4191 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004192
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004193 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004194 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004195 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004196 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004197 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004198 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004199 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004200 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004201 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004202 Decimal("4.28135971E+11")
4203 """
4204 return a.__mul__(b, context=self)
4205
Facundo Batista353750c2007-09-13 18:13:15 +00004206 def next_minus(self, a):
4207 """Returns the largest representable number smaller than a.
4208
4209 >>> c = ExtendedContext.copy()
4210 >>> c.Emin = -999
4211 >>> c.Emax = 999
4212 >>> ExtendedContext.next_minus(Decimal('1'))
4213 Decimal("0.999999999")
4214 >>> c.next_minus(Decimal('1E-1007'))
4215 Decimal("0E-1007")
4216 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4217 Decimal("-1.00000004")
4218 >>> c.next_minus(Decimal('Infinity'))
4219 Decimal("9.99999999E+999")
4220 """
4221 return a.next_minus(context=self)
4222
4223 def next_plus(self, a):
4224 """Returns the smallest representable number larger than a.
4225
4226 >>> c = ExtendedContext.copy()
4227 >>> c.Emin = -999
4228 >>> c.Emax = 999
4229 >>> ExtendedContext.next_plus(Decimal('1'))
4230 Decimal("1.00000001")
4231 >>> c.next_plus(Decimal('-1E-1007'))
4232 Decimal("-0E-1007")
4233 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4234 Decimal("-1.00000002")
4235 >>> c.next_plus(Decimal('-Infinity'))
4236 Decimal("-9.99999999E+999")
4237 """
4238 return a.next_plus(context=self)
4239
4240 def next_toward(self, a, b):
4241 """Returns the number closest to a, in direction towards b.
4242
4243 The result is the closest representable number from the first
4244 operand (but not the first operand) that is in the direction
4245 towards the second operand, unless the operands have the same
4246 value.
4247
4248 >>> c = ExtendedContext.copy()
4249 >>> c.Emin = -999
4250 >>> c.Emax = 999
4251 >>> c.next_toward(Decimal('1'), Decimal('2'))
4252 Decimal("1.00000001")
4253 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4254 Decimal("-0E-1007")
4255 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4256 Decimal("-1.00000002")
4257 >>> c.next_toward(Decimal('1'), Decimal('0'))
4258 Decimal("0.999999999")
4259 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4260 Decimal("0E-1007")
4261 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4262 Decimal("-1.00000004")
4263 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4264 Decimal("-0.00")
4265 """
4266 return a.next_toward(b, context=self)
4267
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004268 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004269 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004270
4271 Essentially a plus operation with all trailing zeros removed from the
4272 result.
4273
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004274 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004275 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004276 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004277 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004278 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004279 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004280 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004281 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004282 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004283 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004284 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004285 Decimal("0")
4286 """
4287 return a.normalize(context=self)
4288
Facundo Batista353750c2007-09-13 18:13:15 +00004289 def number_class(self, a):
4290 """Returns an indication of the class of the operand.
4291
4292 The class is one of the following strings:
4293 -sNaN
4294 -NaN
4295 -Infinity
4296 -Normal
4297 -Subnormal
4298 -Zero
4299 +Zero
4300 +Subnormal
4301 +Normal
4302 +Infinity
4303
4304 >>> c = Context(ExtendedContext)
4305 >>> c.Emin = -999
4306 >>> c.Emax = 999
4307 >>> c.number_class(Decimal('Infinity'))
4308 '+Infinity'
4309 >>> c.number_class(Decimal('1E-10'))
4310 '+Normal'
4311 >>> c.number_class(Decimal('2.50'))
4312 '+Normal'
4313 >>> c.number_class(Decimal('0.1E-999'))
4314 '+Subnormal'
4315 >>> c.number_class(Decimal('0'))
4316 '+Zero'
4317 >>> c.number_class(Decimal('-0'))
4318 '-Zero'
4319 >>> c.number_class(Decimal('-0.1E-999'))
4320 '-Subnormal'
4321 >>> c.number_class(Decimal('-1E-10'))
4322 '-Normal'
4323 >>> c.number_class(Decimal('-2.50'))
4324 '-Normal'
4325 >>> c.number_class(Decimal('-Infinity'))
4326 '-Infinity'
4327 >>> c.number_class(Decimal('NaN'))
4328 'NaN'
4329 >>> c.number_class(Decimal('-NaN'))
4330 'NaN'
4331 >>> c.number_class(Decimal('sNaN'))
4332 'sNaN'
4333 """
4334 return a.number_class(context=self)
4335
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004336 def plus(self, a):
4337 """Plus corresponds to unary prefix plus in Python.
4338
4339 The operation is evaluated using the same rules as add; the
4340 operation plus(a) is calculated as add('0', a) where the '0'
4341 has the same exponent as the operand.
4342
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004343 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004344 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004345 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004346 Decimal("-1.3")
4347 """
4348 return a.__pos__(context=self)
4349
4350 def power(self, a, b, modulo=None):
4351 """Raises a to the power of b, to modulo if given.
4352
Facundo Batista353750c2007-09-13 18:13:15 +00004353 With two arguments, compute a**b. If a is negative then b
4354 must be integral. The result will be inexact unless b is
4355 integral and the result is finite and can be expressed exactly
4356 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004357
Facundo Batista353750c2007-09-13 18:13:15 +00004358 With three arguments, compute (a**b) % modulo. For the
4359 three argument form, the following restrictions on the
4360 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004361
Facundo Batista353750c2007-09-13 18:13:15 +00004362 - all three arguments must be integral
4363 - b must be nonnegative
4364 - at least one of a or b must be nonzero
4365 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004366
Facundo Batista353750c2007-09-13 18:13:15 +00004367 The result of pow(a, b, modulo) is identical to the result
4368 that would be obtained by computing (a**b) % modulo with
4369 unbounded precision, but is computed more efficiently. It is
4370 always exact.
4371
4372 >>> c = ExtendedContext.copy()
4373 >>> c.Emin = -999
4374 >>> c.Emax = 999
4375 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004376 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004377 >>> c.power(Decimal('-2'), Decimal('3'))
4378 Decimal("-8")
4379 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004380 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004381 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004382 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004383 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4384 Decimal("2.00000000")
4385 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004386 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004387 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004388 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004389 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004390 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004391 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004392 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004393 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004394 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004395 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004396 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004397 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004398 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004399 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004400 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004401
4402 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4403 Decimal("11")
4404 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4405 Decimal("-11")
4406 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4407 Decimal("1")
4408 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4409 Decimal("11")
4410 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4411 Decimal("11729830")
4412 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4413 Decimal("-0")
4414 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4415 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004416 """
4417 return a.__pow__(b, modulo, context=self)
4418
4419 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004420 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004421
4422 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004423 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004424 exponent is being increased), multiplied by a positive power of ten (if
4425 the exponent is being decreased), or is unchanged (if the exponent is
4426 already equal to that of the right-hand operand).
4427
4428 Unlike other operations, if the length of the coefficient after the
4429 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004430 operation condition is raised. This guarantees that, unless there is
4431 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004432 equal to that of the right-hand operand.
4433
4434 Also unlike other operations, quantize will never raise Underflow, even
4435 if the result is subnormal and inexact.
4436
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004437 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004438 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004439 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004440 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004441 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004442 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004443 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004444 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004445 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004446 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004447 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004448 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004449 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004450 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004451 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004452 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004453 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004454 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004455 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004456 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004457 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004458 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004459 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004460 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004461 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004462 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004463 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004464 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004465 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004466 Decimal("2E+2")
4467 """
4468 return a.quantize(b, context=self)
4469
Facundo Batista353750c2007-09-13 18:13:15 +00004470 def radix(self):
4471 """Just returns 10, as this is Decimal, :)
4472
4473 >>> ExtendedContext.radix()
4474 Decimal("10")
4475 """
4476 return Decimal(10)
4477
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004478 def remainder(self, a, b):
4479 """Returns the remainder from integer division.
4480
4481 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004482 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004483 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004484 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004485
4486 This operation will fail under the same conditions as integer division
4487 (that is, if integer division on the same two operands would fail, the
4488 remainder cannot be calculated).
4489
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004490 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004491 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004492 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004493 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004494 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004495 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004496 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004497 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004498 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004499 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004500 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004501 Decimal("1.0")
4502 """
4503 return a.__mod__(b, context=self)
4504
4505 def remainder_near(self, a, b):
4506 """Returns to be "a - b * n", where n is the integer nearest the exact
4507 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004508 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004509 sign of a.
4510
4511 This operation will fail under the same conditions as integer division
4512 (that is, if integer division on the same two operands would fail, the
4513 remainder cannot be calculated).
4514
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004515 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004516 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004517 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004518 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004519 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004520 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004521 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004522 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004523 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004524 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004525 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004526 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004527 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004528 Decimal("-0.3")
4529 """
4530 return a.remainder_near(b, context=self)
4531
Facundo Batista353750c2007-09-13 18:13:15 +00004532 def rotate(self, a, b):
4533 """Returns a rotated copy of a, b times.
4534
4535 The coefficient of the result is a rotated copy of the digits in
4536 the coefficient of the first operand. The number of places of
4537 rotation is taken from the absolute value of the second operand,
4538 with the rotation being to the left if the second operand is
4539 positive or to the right otherwise.
4540
4541 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4542 Decimal("400000003")
4543 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4544 Decimal("12")
4545 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4546 Decimal("891234567")
4547 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4548 Decimal("123456789")
4549 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4550 Decimal("345678912")
4551 """
4552 return a.rotate(b, context=self)
4553
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004554 def same_quantum(self, a, b):
4555 """Returns True if the two operands have the same exponent.
4556
4557 The result is never affected by either the sign or the coefficient of
4558 either operand.
4559
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004560 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004561 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004562 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004563 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004564 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004565 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004566 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004567 True
4568 """
4569 return a.same_quantum(b)
4570
Facundo Batista353750c2007-09-13 18:13:15 +00004571 def scaleb (self, a, b):
4572 """Returns the first operand after adding the second value its exp.
4573
4574 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4575 Decimal("0.0750")
4576 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4577 Decimal("7.50")
4578 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4579 Decimal("7.50E+3")
4580 """
4581 return a.scaleb (b, context=self)
4582
4583 def shift(self, a, b):
4584 """Returns a shifted copy of a, b times.
4585
4586 The coefficient of the result is a shifted copy of the digits
4587 in the coefficient of the first operand. The number of places
4588 to shift is taken from the absolute value of the second operand,
4589 with the shift being to the left if the second operand is
4590 positive or to the right otherwise. Digits shifted into the
4591 coefficient are zeros.
4592
4593 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4594 Decimal("400000000")
4595 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4596 Decimal("0")
4597 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4598 Decimal("1234567")
4599 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4600 Decimal("123456789")
4601 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4602 Decimal("345678900")
4603 """
4604 return a.shift(b, context=self)
4605
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004606 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004607 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004608
4609 If the result must be inexact, it is rounded using the round-half-even
4610 algorithm.
4611
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004612 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004613 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004614 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004615 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004616 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004617 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004618 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004619 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004620 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004621 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004622 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004623 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004624 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004625 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004626 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004627 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004628 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004629 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004630 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004631 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004632 """
4633 return a.sqrt(context=self)
4634
4635 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004636 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004637
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004638 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004639 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004640 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004641 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004642 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004643 Decimal("-0.77")
4644 """
4645 return a.__sub__(b, context=self)
4646
4647 def to_eng_string(self, a):
4648 """Converts a number to a string, using scientific notation.
4649
4650 The operation is not affected by the context.
4651 """
4652 return a.to_eng_string(context=self)
4653
4654 def to_sci_string(self, a):
4655 """Converts a number to a string, using scientific notation.
4656
4657 The operation is not affected by the context.
4658 """
4659 return a.__str__(context=self)
4660
Facundo Batista353750c2007-09-13 18:13:15 +00004661 def to_integral_exact(self, a):
4662 """Rounds to an integer.
4663
4664 When the operand has a negative exponent, the result is the same
4665 as using the quantize() operation using the given operand as the
4666 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4667 of the operand as the precision setting; Inexact and Rounded flags
4668 are allowed in this operation. The rounding mode is taken from the
4669 context.
4670
4671 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4672 Decimal("2")
4673 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4674 Decimal("100")
4675 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4676 Decimal("100")
4677 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4678 Decimal("102")
4679 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4680 Decimal("-102")
4681 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4682 Decimal("1.0E+6")
4683 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4684 Decimal("7.89E+77")
4685 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4686 Decimal("-Infinity")
4687 """
4688 return a.to_integral_exact(context=self)
4689
4690 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004691 """Rounds to an integer.
4692
4693 When the operand has a negative exponent, the result is the same
4694 as using the quantize() operation using the given operand as the
4695 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4696 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004697 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004698
Facundo Batista353750c2007-09-13 18:13:15 +00004699 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004700 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004701 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004702 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004703 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004704 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004705 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004706 Decimal("102")
Facundo Batista353750c2007-09-13 18:13:15 +00004707 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004708 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004709 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004710 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004711 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004712 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004713 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004714 Decimal("-Infinity")
4715 """
Facundo Batista353750c2007-09-13 18:13:15 +00004716 return a.to_integral_value(context=self)
4717
4718 # the method name changed, but we provide also the old one, for compatibility
4719 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004720
4721class _WorkRep(object):
4722 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004723 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004724 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004725 # exp: None, int, or string
4726
4727 def __init__(self, value=None):
4728 if value is None:
4729 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004730 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004731 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004732 elif isinstance(value, Decimal):
4733 self.sign = value._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004734 cum = 0
Raymond Hettinger17931de2004-10-27 06:21:46 +00004735 for digit in value._int:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004736 cum = cum * 10 + digit
4737 self.int = cum
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004738 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004739 else:
4740 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004741 self.sign = value[0]
4742 self.int = value[1]
4743 self.exp = value[2]
4744
4745 def __repr__(self):
4746 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4747
4748 __str__ = __repr__
4749
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004750
4751
4752def _normalize(op1, op2, shouldround = 0, prec = 0):
4753 """Normalizes op1, op2 to have the same exp and length of coefficient.
4754
4755 Done during addition.
4756 """
Facundo Batista353750c2007-09-13 18:13:15 +00004757 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004758 tmp = op2
4759 other = op1
4760 else:
4761 tmp = op1
4762 other = op2
4763
Facundo Batista353750c2007-09-13 18:13:15 +00004764 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4765 # Then adding 10**exp to tmp has the same effect (after rounding)
4766 # as adding any positive quantity smaller than 10**exp; similarly
4767 # for subtraction. So if other is smaller than 10**exp we replace
4768 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4769 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004770 tmp_len = len(str(tmp.int))
4771 other_len = len(str(other.int))
Facundo Batista353750c2007-09-13 18:13:15 +00004772 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4773 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004774 other.int = 1
Facundo Batista353750c2007-09-13 18:13:15 +00004775 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004776
Facundo Batista353750c2007-09-13 18:13:15 +00004777 tmp.int *= 10 ** (tmp.exp - other.exp)
4778 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004779 return op1, op2
4780
4781def _adjust_coefficients(op1, op2):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004782 """Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004783
4784 Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp.
4785
4786 Used on _WorkRep instances during division.
4787 """
4788 adjust = 0
Facundo Batista59c58842007-04-10 12:58:45 +00004789 # If op1 is smaller, make it larger
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004790 while op2.int > op1.int:
4791 op1.int *= 10
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004792 op1.exp -= 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004793 adjust += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004794
Facundo Batista59c58842007-04-10 12:58:45 +00004795 # If op2 is too small, make it larger
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004796 while op1.int >= (10 * op2.int):
4797 op2.int *= 10
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004798 op2.exp -= 1
4799 adjust -= 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004800
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004801 return op1, op2, adjust
4802
Facundo Batista353750c2007-09-13 18:13:15 +00004803
4804##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4805
4806# This function from Tim Peters was taken from here:
4807# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4808# The correction being in the function definition is for speed, and
4809# the whole function is not resolved with math.log because of avoiding
4810# the use of floats.
4811def _nbits(n, correction = {
4812 '0': 4, '1': 3, '2': 2, '3': 2,
4813 '4': 1, '5': 1, '6': 1, '7': 1,
4814 '8': 0, '9': 0, 'a': 0, 'b': 0,
4815 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4816 """Number of bits in binary representation of the positive integer n,
4817 or 0 if n == 0.
4818 """
4819 if n < 0:
4820 raise ValueError("The argument to _nbits should be nonnegative.")
4821 hex_n = "%x" % n
4822 return 4*len(hex_n) - correction[hex_n[0]]
4823
4824def _sqrt_nearest(n, a):
4825 """Closest integer to the square root of the positive integer n. a is
4826 an initial approximation to the square root. Any positive integer
4827 will do for a, but the closer a is to the square root of n the
4828 faster convergence will be.
4829
4830 """
4831 if n <= 0 or a <= 0:
4832 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4833
4834 b=0
4835 while a != b:
4836 b, a = a, a--n//a>>1
4837 return a
4838
4839def _rshift_nearest(x, shift):
4840 """Given an integer x and a nonnegative integer shift, return closest
4841 integer to x / 2**shift; use round-to-even in case of a tie.
4842
4843 """
4844 b, q = 1L << shift, x >> shift
4845 return q + (2*(x & (b-1)) + (q&1) > b)
4846
4847def _div_nearest(a, b):
4848 """Closest integer to a/b, a and b positive integers; rounds to even
4849 in the case of a tie.
4850
4851 """
4852 q, r = divmod(a, b)
4853 return q + (2*r + (q&1) > b)
4854
4855def _ilog(x, M, L = 8):
4856 """Integer approximation to M*log(x/M), with absolute error boundable
4857 in terms only of x/M.
4858
4859 Given positive integers x and M, return an integer approximation to
4860 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4861 between the approximation and the exact result is at most 22. For
4862 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4863 both cases these are upper bounds on the error; it will usually be
4864 much smaller."""
4865
4866 # The basic algorithm is the following: let log1p be the function
4867 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4868 # the reduction
4869 #
4870 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4871 #
4872 # repeatedly until the argument to log1p is small (< 2**-L in
4873 # absolute value). For small y we can use the Taylor series
4874 # expansion
4875 #
4876 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4877 #
4878 # truncating at T such that y**T is small enough. The whole
4879 # computation is carried out in a form of fixed-point arithmetic,
4880 # with a real number z being represented by an integer
4881 # approximation to z*M. To avoid loss of precision, the y below
4882 # is actually an integer approximation to 2**R*y*M, where R is the
4883 # number of reductions performed so far.
4884
4885 y = x-M
4886 # argument reduction; R = number of reductions performed
4887 R = 0
4888 while (R <= L and long(abs(y)) << L-R >= M or
4889 R > L and abs(y) >> R-L >= M):
4890 y = _div_nearest(long(M*y) << 1,
4891 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4892 R += 1
4893
4894 # Taylor series with T terms
4895 T = -int(-10*len(str(M))//(3*L))
4896 yshift = _rshift_nearest(y, R)
4897 w = _div_nearest(M, T)
4898 for k in xrange(T-1, 0, -1):
4899 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4900
4901 return _div_nearest(w*y, M)
4902
4903def _dlog10(c, e, p):
4904 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4905 approximation to 10**p * log10(c*10**e), with an absolute error of
4906 at most 1. Assumes that c*10**e is not exactly 1."""
4907
4908 # increase precision by 2; compensate for this by dividing
4909 # final result by 100
4910 p += 2
4911
4912 # write c*10**e as d*10**f with either:
4913 # f >= 0 and 1 <= d <= 10, or
4914 # f <= 0 and 0.1 <= d <= 1.
4915 # Thus for c*10**e close to 1, f = 0
4916 l = len(str(c))
4917 f = e+l - (e+l >= 1)
4918
4919 if p > 0:
4920 M = 10**p
4921 k = e+p-f
4922 if k >= 0:
4923 c *= 10**k
4924 else:
4925 c = _div_nearest(c, 10**-k)
4926
4927 log_d = _ilog(c, M) # error < 5 + 22 = 27
4928 log_10 = _ilog(10*M, M) # error < 15
4929 log_d = _div_nearest(log_d*M, log_10)
4930 log_tenpower = f*M # exact
4931 else:
4932 log_d = 0 # error < 2.31
4933 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4934
4935 return _div_nearest(log_tenpower+log_d, 100)
4936
4937def _dlog(c, e, p):
4938 """Given integers c, e and p with c > 0, compute an integer
4939 approximation to 10**p * log(c*10**e), with an absolute error of
4940 at most 1. Assumes that c*10**e is not exactly 1."""
4941
4942 # Increase precision by 2. The precision increase is compensated
4943 # for at the end with a division by 100.
4944 p += 2
4945
4946 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4947 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4948 # as 10**p * log(d) + 10**p*f * log(10).
4949 l = len(str(c))
4950 f = e+l - (e+l >= 1)
4951
4952 # compute approximation to 10**p*log(d), with error < 27
4953 if p > 0:
4954 k = e+p-f
4955 if k >= 0:
4956 c *= 10**k
4957 else:
4958 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4959
4960 # _ilog magnifies existing error in c by a factor of at most 10
4961 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4962 else:
4963 # p <= 0: just approximate the whole thing by 0; error < 2.31
4964 log_d = 0
4965
4966 # compute approximation to 10**p*f*log(10), with error < 17
4967 if f:
4968 sign_f = [-1, 1][f > 0]
4969 if p >= 0:
4970 M = 10**p * abs(f)
4971 else:
4972 M = _div_nearest(abs(f), 10**-p) # M = 10**p*|f|, error <= 0.5
4973
4974 if M:
4975 f_log_ten = sign_f*_ilog(10*M, M) # M*log(10), error <= 1.2 + 15 < 17
4976 else:
4977 f_log_ten = 0
4978 else:
4979 f_log_ten = 0
4980
4981 # error in sum < 17+27 = 44; error after division < 0.44 + 0.5 < 1
4982 return _div_nearest(f_log_ten + log_d, 100)
4983
4984def _iexp(x, M, L=8):
4985 """Given integers x and M, M > 0, such that x/M is small in absolute
4986 value, compute an integer approximation to M*exp(x/M). For 0 <=
4987 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4988 is usually much smaller)."""
4989
4990 # Algorithm: to compute exp(z) for a real number z, first divide z
4991 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4992 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4993 # series
4994 #
4995 # expm1(x) = x + x**2/2! + x**3/3! + ...
4996 #
4997 # Now use the identity
4998 #
4999 # expm1(2x) = expm1(x)*(expm1(x)+2)
5000 #
5001 # R times to compute the sequence expm1(z/2**R),
5002 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5003
5004 # Find R such that x/2**R/M <= 2**-L
5005 R = _nbits((long(x)<<L)//M)
5006
5007 # Taylor series. (2**L)**T > M
5008 T = -int(-10*len(str(M))//(3*L))
5009 y = _div_nearest(x, T)
5010 Mshift = long(M)<<R
5011 for i in xrange(T-1, 0, -1):
5012 y = _div_nearest(x*(Mshift + y), Mshift * i)
5013
5014 # Expansion
5015 for k in xrange(R-1, -1, -1):
5016 Mshift = long(M)<<(k+2)
5017 y = _div_nearest(y*(y+Mshift), Mshift)
5018
5019 return M+y
5020
5021def _dexp(c, e, p):
5022 """Compute an approximation to exp(c*10**e), with p decimal places of
5023 precision.
5024
5025 Returns d, f such that:
5026
5027 10**(p-1) <= d <= 10**p, and
5028 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5029
5030 In other words, d*10**f is an approximation to exp(c*10**e) with p
5031 digits of precision, and with an error in d of at most 1. This is
5032 almost, but not quite, the same as the error being < 1ulp: when d
5033 = 10**(p-1) the error could be up to 10 ulp."""
5034
5035 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5036 p += 2
5037
5038 # compute log10 with extra precision = adjusted exponent of c*10**e
5039 extra = max(0, e + len(str(c)) - 1)
5040 q = p + extra
5041 log10 = _dlog(10, 0, q) # error <= 1
5042
5043 # compute quotient c*10**e/(log10/10**q) = c*10**(e+q)/log10,
5044 # rounding down
5045 shift = e+q
5046 if shift >= 0:
5047 cshift = c*10**shift
5048 else:
5049 cshift = c//10**-shift
5050 quot, rem = divmod(cshift, log10)
5051
5052 # reduce remainder back to original precision
5053 rem = _div_nearest(rem, 10**extra)
5054
5055 # error in result of _iexp < 120; error after division < 0.62
5056 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5057
5058def _dpower(xc, xe, yc, ye, p):
5059 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5060 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5061
5062 10**(p-1) <= c <= 10**p, and
5063 (c-1)*10**e < x**y < (c+1)*10**e
5064
5065 in other words, c*10**e is an approximation to x**y with p digits
5066 of precision, and with an error in c of at most 1. (This is
5067 almost, but not quite, the same as the error being < 1ulp: when c
5068 == 10**(p-1) we can only guarantee error < 10ulp.)
5069
5070 We assume that: x is positive and not equal to 1, and y is nonzero.
5071 """
5072
5073 # Find b such that 10**(b-1) <= |y| <= 10**b
5074 b = len(str(abs(yc))) + ye
5075
5076 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5077 lxc = _dlog(xc, xe, p+b+1)
5078
5079 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5080 shift = ye-b
5081 if shift >= 0:
5082 pc = lxc*yc*10**shift
5083 else:
5084 pc = _div_nearest(lxc*yc, 10**-shift)
5085
5086 if pc == 0:
5087 # we prefer a result that isn't exactly 1; this makes it
5088 # easier to compute a correctly rounded result in __pow__
5089 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5090 coeff, exp = 10**(p-1)+1, 1-p
5091 else:
5092 coeff, exp = 10**p-1, -p
5093 else:
5094 coeff, exp = _dexp(pc, -(p+1), p+1)
5095 coeff = _div_nearest(coeff, 10)
5096 exp += 1
5097
5098 return coeff, exp
5099
5100def _log10_lb(c, correction = {
5101 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5102 '6': 23, '7': 16, '8': 10, '9': 5}):
5103 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5104 if c <= 0:
5105 raise ValueError("The argument to _log10_lb should be nonnegative.")
5106 str_c = str(c)
5107 return 100*len(str_c) - correction[str_c[0]]
5108
Facundo Batista59c58842007-04-10 12:58:45 +00005109##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005110
Facundo Batista353750c2007-09-13 18:13:15 +00005111def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005112 """Convert other to Decimal.
5113
5114 Verifies that it's ok to use in an implicit construction.
5115 """
5116 if isinstance(other, Decimal):
5117 return other
5118 if isinstance(other, (int, long)):
5119 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005120 if raiseit:
5121 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005122 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005123
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005124_infinity_map = {
5125 'inf' : 1,
5126 'infinity' : 1,
5127 '+inf' : 1,
5128 '+infinity' : 1,
5129 '-inf' : -1,
5130 '-infinity' : -1
5131}
5132
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005133def _isinfinity(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005134 """Determines whether a string or float is infinity.
5135
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005136 +1 for negative infinity; 0 for finite ; +1 for positive infinity
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005137 """
5138 num = str(num).lower()
5139 return _infinity_map.get(num, 0)
5140
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005141def _isnan(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005142 """Determines whether a string or float is NaN
5143
5144 (1, sign, diagnostic info as string) => NaN
5145 (2, sign, diagnostic info as string) => sNaN
5146 0 => not a NaN
5147 """
5148 num = str(num).lower()
5149 if not num:
5150 return 0
5151
Facundo Batista59c58842007-04-10 12:58:45 +00005152 # Get the sign, get rid of trailing [+-]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005153 sign = 0
5154 if num[0] == '+':
5155 num = num[1:]
Facundo Batista59c58842007-04-10 12:58:45 +00005156 elif num[0] == '-': # elif avoids '+-nan'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005157 num = num[1:]
5158 sign = 1
5159
5160 if num.startswith('nan'):
Facundo Batista59c58842007-04-10 12:58:45 +00005161 if len(num) > 3 and not num[3:].isdigit(): # diagnostic info
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005162 return 0
5163 return (1, sign, num[3:].lstrip('0'))
5164 if num.startswith('snan'):
5165 if len(num) > 4 and not num[4:].isdigit():
5166 return 0
5167 return (2, sign, num[4:].lstrip('0'))
5168 return 0
5169
5170
Facundo Batista59c58842007-04-10 12:58:45 +00005171##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005172
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005173# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005174# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005175
5176DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005177 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005178 traps=[DivisionByZero, Overflow, InvalidOperation],
5179 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005180 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005181 Emax=999999999,
5182 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005183 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005184)
5185
5186# Pre-made alternate contexts offered by the specification
5187# Don't change these; the user should be able to select these
5188# contexts and be able to reproduce results from other implementations
5189# of the spec.
5190
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005191BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005192 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005193 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5194 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005195)
5196
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005197ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005198 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005199 traps=[],
5200 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005201)
5202
5203
Facundo Batista59c58842007-04-10 12:58:45 +00005204##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005205
Facundo Batista59c58842007-04-10 12:58:45 +00005206# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005207Inf = Decimal('Inf')
5208negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005209NaN = Decimal('NaN')
5210Dec_0 = Decimal(0)
5211Dec_p1 = Decimal(1)
5212Dec_n1 = Decimal(-1)
5213Dec_p2 = Decimal(2)
5214Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005215
Facundo Batista59c58842007-04-10 12:58:45 +00005216# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005217Infsign = (Inf, negInf)
5218
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005219
Facundo Batista59c58842007-04-10 12:58:45 +00005220##### crud for parsing strings #############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005221import re
5222
5223# There's an optional sign at the start, and an optional exponent
5224# at the end. The exponent has an optional sign and at least one
5225# digit. In between, must have either at least one digit followed
5226# by an optional fraction, or a decimal point followed by at least
5227# one digit. Yuck.
5228
5229_parser = re.compile(r"""
5230# \s*
5231 (?P<sign>[-+])?
5232 (
5233 (?P<int>\d+) (\. (?P<frac>\d*))?
5234 |
5235 \. (?P<onlyfrac>\d+)
5236 )
5237 ([eE](?P<exp>[-+]? \d+))?
5238# \s*
5239 $
Facundo Batista59c58842007-04-10 12:58:45 +00005240""", re.VERBOSE).match # Uncomment the \s* to allow leading or trailing spaces.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005241
5242del re
5243
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005244def _string2exact(s):
Facundo Batista59c58842007-04-10 12:58:45 +00005245 """Return sign, n, p s.t.
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00005246
Facundo Batista59c58842007-04-10 12:58:45 +00005247 Float string value == -1**sign * n * 10**p exactly
5248 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005249 m = _parser(s)
5250 if m is None:
5251 raise ValueError("invalid literal for Decimal: %r" % s)
5252
5253 if m.group('sign') == "-":
5254 sign = 1
5255 else:
5256 sign = 0
5257
5258 exp = m.group('exp')
5259 if exp is None:
5260 exp = 0
5261 else:
5262 exp = int(exp)
5263
5264 intpart = m.group('int')
5265 if intpart is None:
5266 intpart = ""
5267 fracpart = m.group('onlyfrac')
5268 else:
5269 fracpart = m.group('frac')
5270 if fracpart is None:
5271 fracpart = ""
5272
5273 exp -= len(fracpart)
5274
5275 mantissa = intpart + fracpart
5276 tmp = map(int, mantissa)
5277 backup = tmp
5278 while tmp and tmp[0] == 0:
5279 del tmp[0]
5280
5281 # It's a zero
5282 if not tmp:
5283 if backup:
5284 return (sign, tuple(backup), exp)
5285 return (sign, (0,), exp)
5286 mantissa = tuple(tmp)
5287
5288 return (sign, mantissa, exp)
5289
5290
5291if __name__ == '__main__':
5292 import doctest, sys
5293 doctest.testmod(sys.modules[__name__])