blob: b2bfc567a4e083acf8d9eb99be9d521e51600f98 [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
Facundo Batistabd2fe832007-09-13 18:42:09 +00002163 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002164 """Quantize self so its exponent is the same as that of exp.
2165
2166 Similar to self._rescale(exp._exp) but with error checking.
2167 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002168 exp = _convert_other(exp, raiseit=True)
2169
Facundo Batista353750c2007-09-13 18:13:15 +00002170 if context is None:
2171 context = getcontext()
2172 if rounding is None:
2173 rounding = context.rounding
2174
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002175 if self._is_special or exp._is_special:
2176 ans = self._check_nans(exp, context)
2177 if ans:
2178 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002179
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002180 if exp._isinfinity() or self._isinfinity():
2181 if exp._isinfinity() and self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00002182 return self # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002183 return context._raise_error(InvalidOperation,
2184 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002185
Facundo Batistabd2fe832007-09-13 18:42:09 +00002186 # if we're not watching exponents, do a simple rescale
2187 if not watchexp:
2188 ans = self._rescale(exp._exp, rounding)
2189 # raise Inexact and Rounded where appropriate
2190 if ans._exp > self._exp:
2191 context._raise_error(Rounded)
2192 if ans != self:
2193 context._raise_error(Inexact)
2194 return ans
2195
Facundo Batista353750c2007-09-13 18:13:15 +00002196 # exp._exp should be between Etiny and Emax
2197 if not (context.Etiny() <= exp._exp <= context.Emax):
2198 return context._raise_error(InvalidOperation,
2199 'target exponent out of bounds in quantize')
2200
2201 if not self:
2202 ans = Decimal((self._sign, (0,), exp._exp))
2203 return ans._fix(context)
2204
2205 self_adjusted = self.adjusted()
2206 if self_adjusted > context.Emax:
2207 return context._raise_error(InvalidOperation,
2208 'exponent of quantize result too large for current context')
2209 if self_adjusted - exp._exp + 1 > context.prec:
2210 return context._raise_error(InvalidOperation,
2211 'quantize result has too many digits for current context')
2212
2213 ans = self._rescale(exp._exp, rounding)
2214 if ans.adjusted() > context.Emax:
2215 return context._raise_error(InvalidOperation,
2216 'exponent of quantize result too large for current context')
2217 if len(ans._int) > context.prec:
2218 return context._raise_error(InvalidOperation,
2219 'quantize result has too many digits for current context')
2220
2221 # raise appropriate flags
2222 if ans._exp > self._exp:
2223 context._raise_error(Rounded)
2224 if ans != self:
2225 context._raise_error(Inexact)
2226 if ans and ans.adjusted() < context.Emin:
2227 context._raise_error(Subnormal)
2228
2229 # call to fix takes care of any necessary folddown
2230 ans = ans._fix(context)
2231 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002232
2233 def same_quantum(self, other):
2234 """Test whether self and other have the same exponent.
2235
2236 same as self._exp == other._exp, except NaN == sNaN
2237 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002238 if self._is_special or other._is_special:
2239 if self._isnan() or other._isnan():
2240 return self._isnan() and other._isnan() and True
2241 if self._isinfinity() or other._isinfinity():
2242 return self._isinfinity() and other._isinfinity() and True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002243 return self._exp == other._exp
2244
Facundo Batista353750c2007-09-13 18:13:15 +00002245 def _rescale(self, exp, rounding):
2246 """Rescale self so that the exponent is exp, either by padding with zeros
2247 or by truncating digits, using the given rounding mode.
2248
2249 Specials are returned without change. This operation is
2250 quiet: it raises no flags, and uses no information from the
2251 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002252
2253 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002254 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002255 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002256 if self._is_special:
Facundo Batista353750c2007-09-13 18:13:15 +00002257 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002258 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002259 return Decimal((self._sign, (0,), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002260
Facundo Batista353750c2007-09-13 18:13:15 +00002261 if self._exp >= exp:
2262 # pad answer with zeros if necessary
2263 return Decimal((self._sign, self._int + (0,)*(self._exp - exp), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002264
Facundo Batista353750c2007-09-13 18:13:15 +00002265 # too many digits; round and lose data. If self.adjusted() <
2266 # exp-1, replace self by 10**(exp-1) before rounding
2267 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002268 if digits < 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002269 self = Decimal((self._sign, (1,), exp-1))
2270 digits = 0
2271 this_function = getattr(self, self._pick_rounding_function[rounding])
2272 return this_function(digits)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002273
Facundo Batista353750c2007-09-13 18:13:15 +00002274 def to_integral_exact(self, rounding=None, context=None):
2275 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002276
Facundo Batista353750c2007-09-13 18:13:15 +00002277 If no rounding mode is specified, take the rounding mode from
2278 the context. This method raises the Rounded and Inexact flags
2279 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002280
Facundo Batista353750c2007-09-13 18:13:15 +00002281 See also: to_integral_value, which does exactly the same as
2282 this method except that it doesn't raise Inexact or Rounded.
2283 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002284 if self._is_special:
2285 ans = self._check_nans(context=context)
2286 if ans:
2287 return ans
Facundo Batista353750c2007-09-13 18:13:15 +00002288 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002289 if self._exp >= 0:
2290 return self
Facundo Batista353750c2007-09-13 18:13:15 +00002291 if not self:
2292 return Decimal((self._sign, (0,), 0))
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002293 if context is None:
2294 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002295 if rounding is None:
2296 rounding = context.rounding
2297 context._raise_error(Rounded)
2298 ans = self._rescale(0, rounding)
2299 if ans != self:
2300 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002301 return ans
2302
Facundo Batista353750c2007-09-13 18:13:15 +00002303 def to_integral_value(self, rounding=None, context=None):
2304 """Rounds to the nearest integer, without raising inexact, rounded."""
2305 if context is None:
2306 context = getcontext()
2307 if rounding is None:
2308 rounding = context.rounding
2309 if self._is_special:
2310 ans = self._check_nans(context=context)
2311 if ans:
2312 return ans
2313 return self
2314 if self._exp >= 0:
2315 return self
2316 else:
2317 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002318
Facundo Batista353750c2007-09-13 18:13:15 +00002319 # the method name changed, but we provide also the old one, for compatibility
2320 to_integral = to_integral_value
2321
2322 def sqrt(self, context=None):
2323 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002324 if self._is_special:
2325 ans = self._check_nans(context=context)
2326 if ans:
2327 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002328
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002329 if self._isinfinity() and self._sign == 0:
2330 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002331
2332 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002333 # exponent = self._exp // 2. sqrt(-0) = -0
2334 ans = Decimal((self._sign, (0,), self._exp // 2))
2335 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002336
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002337 if context is None:
2338 context = getcontext()
2339
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002340 if self._sign == 1:
2341 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2342
Facundo Batista353750c2007-09-13 18:13:15 +00002343 # At this point self represents a positive number. Let p be
2344 # the desired precision and express self in the form c*100**e
2345 # with c a positive real number and e an integer, c and e
2346 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2347 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2348 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2349 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2350 # the closest integer to sqrt(c) with the even integer chosen
2351 # in the case of a tie.
2352 #
2353 # To ensure correct rounding in all cases, we use the
2354 # following trick: we compute the square root to an extra
2355 # place (precision p+1 instead of precision p), rounding down.
2356 # Then, if the result is inexact and its last digit is 0 or 5,
2357 # we increase the last digit to 1 or 6 respectively; if it's
2358 # exact we leave the last digit alone. Now the final round to
2359 # p places (or fewer in the case of underflow) will round
2360 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002361
Facundo Batista353750c2007-09-13 18:13:15 +00002362 # use an extra digit of precision
2363 prec = context.prec+1
2364
2365 # write argument in the form c*100**e where e = self._exp//2
2366 # is the 'ideal' exponent, to be used if the square root is
2367 # exactly representable. l is the number of 'digits' of c in
2368 # base 100, so that 100**(l-1) <= c < 100**l.
2369 op = _WorkRep(self)
2370 e = op.exp >> 1
2371 if op.exp & 1:
2372 c = op.int * 10
2373 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002374 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002375 c = op.int
2376 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002377
Facundo Batista353750c2007-09-13 18:13:15 +00002378 # rescale so that c has exactly prec base 100 'digits'
2379 shift = prec-l
2380 if shift >= 0:
2381 c *= 100**shift
2382 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002383 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002384 c, remainder = divmod(c, 100**-shift)
2385 exact = not remainder
2386 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002387
Facundo Batista353750c2007-09-13 18:13:15 +00002388 # find n = floor(sqrt(c)) using Newton's method
2389 n = 10**prec
2390 while True:
2391 q = c//n
2392 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002393 break
Facundo Batista353750c2007-09-13 18:13:15 +00002394 else:
2395 n = n + q >> 1
2396 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002397
Facundo Batista353750c2007-09-13 18:13:15 +00002398 if exact:
2399 # result is exact; rescale to use ideal exponent e
2400 if shift >= 0:
2401 # assert n % 10**shift == 0
2402 n //= 10**shift
2403 else:
2404 n *= 10**-shift
2405 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002406 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002407 # result is not exact; fix last digit as described above
2408 if n % 5 == 0:
2409 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002410
Facundo Batista353750c2007-09-13 18:13:15 +00002411 ans = Decimal((0, map(int, str(n)), e))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002412
Facundo Batista353750c2007-09-13 18:13:15 +00002413 # round, and fit to current context
2414 context = context._shallow_copy()
2415 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002416 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002417 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002418
Facundo Batista353750c2007-09-13 18:13:15 +00002419 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002420
2421 def max(self, other, context=None):
2422 """Returns the larger value.
2423
Facundo Batista353750c2007-09-13 18:13:15 +00002424 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002425 NaN (and signals if one is sNaN). Also rounds.
2426 """
Facundo Batista353750c2007-09-13 18:13:15 +00002427 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002428
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002429 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002430 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002431 # number is always returned
2432 sn = self._isnan()
2433 on = other._isnan()
2434 if sn or on:
2435 if on == 1 and sn != 2:
2436 return self
2437 if sn == 1 and on != 2:
2438 return other
2439 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002440
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002441 c = self.__cmp__(other)
2442 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002443 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002444 # then an ordering is applied:
2445 #
Facundo Batista59c58842007-04-10 12:58:45 +00002446 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002447 # positive sign and min returns the operand with the negative sign
2448 #
Facundo Batista59c58842007-04-10 12:58:45 +00002449 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002450 # the result. This is exactly the ordering used in compare_total.
2451 c = self.compare_total(other)
2452
2453 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002454 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002455 else:
2456 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002457
2458 if context is None:
2459 context = getcontext()
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002460 if context._rounding_decision == ALWAYS_ROUND:
2461 return ans._fix(context)
2462 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002463
2464 def min(self, other, context=None):
2465 """Returns the smaller value.
2466
Facundo Batista59c58842007-04-10 12:58:45 +00002467 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002468 NaN (and signals if one is sNaN). Also rounds.
2469 """
Facundo Batista353750c2007-09-13 18:13:15 +00002470 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002471
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002472 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002473 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002474 # number is always returned
2475 sn = self._isnan()
2476 on = other._isnan()
2477 if sn or on:
2478 if on == 1 and sn != 2:
2479 return self
2480 if sn == 1 and on != 2:
2481 return other
2482 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002483
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002484 c = self.__cmp__(other)
2485 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002486 c = self.compare_total(other)
2487
2488 if c == -1:
2489 ans = self
2490 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002491 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002492
2493 if context is None:
2494 context = getcontext()
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002495 if context._rounding_decision == ALWAYS_ROUND:
2496 return ans._fix(context)
2497 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002498
2499 def _isinteger(self):
2500 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002501 if self._is_special:
2502 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002503 if self._exp >= 0:
2504 return True
2505 rest = self._int[self._exp:]
2506 return rest == (0,)*len(rest)
2507
2508 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002509 """Returns True if self is even. Assumes self is an integer."""
2510 if not self or self._exp > 0:
2511 return True
Raymond Hettinger61992ef2004-08-06 23:42:16 +00002512 return self._int[-1+self._exp] & 1 == 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002513
2514 def adjusted(self):
2515 """Return the adjusted exponent of self"""
2516 try:
2517 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002518 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002519 except TypeError:
2520 return 0
2521
Facundo Batista353750c2007-09-13 18:13:15 +00002522 def canonical(self, context=None):
2523 """Returns the same Decimal object.
2524
2525 As we do not have different encodings for the same number, the
2526 received object already is in its canonical form.
2527 """
2528 return self
2529
2530 def compare_signal(self, other, context=None):
2531 """Compares self to the other operand numerically.
2532
2533 It's pretty much like compare(), but all NaNs signal, with signaling
2534 NaNs taking precedence over quiet NaNs.
2535 """
2536 if context is None:
2537 context = getcontext()
2538
2539 self_is_nan = self._isnan()
2540 other_is_nan = other._isnan()
2541 if self_is_nan == 2:
2542 return context._raise_error(InvalidOperation, 'sNaN',
2543 1, self)
2544 if other_is_nan == 2:
2545 return context._raise_error(InvalidOperation, 'sNaN',
2546 1, other)
2547 if self_is_nan:
2548 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2549 1, self)
2550 if other_is_nan:
2551 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2552 1, other)
2553 return self.compare(other, context=context)
2554
2555 def compare_total(self, other):
2556 """Compares self to other using the abstract representations.
2557
2558 This is not like the standard compare, which use their numerical
2559 value. Note that a total ordering is defined for all possible abstract
2560 representations.
2561 """
2562 # if one is negative and the other is positive, it's easy
2563 if self._sign and not other._sign:
2564 return Dec_n1
2565 if not self._sign and other._sign:
2566 return Dec_p1
2567 sign = self._sign
2568
2569 # let's handle both NaN types
2570 self_nan = self._isnan()
2571 other_nan = other._isnan()
2572 if self_nan or other_nan:
2573 if self_nan == other_nan:
2574 if self._int < other._int:
2575 if sign:
2576 return Dec_p1
2577 else:
2578 return Dec_n1
2579 if self._int > other._int:
2580 if sign:
2581 return Dec_n1
2582 else:
2583 return Dec_p1
2584 return Dec_0
2585
2586 if sign:
2587 if self_nan == 1:
2588 return Dec_n1
2589 if other_nan == 1:
2590 return Dec_p1
2591 if self_nan == 2:
2592 return Dec_n1
2593 if other_nan == 2:
2594 return Dec_p1
2595 else:
2596 if self_nan == 1:
2597 return Dec_p1
2598 if other_nan == 1:
2599 return Dec_n1
2600 if self_nan == 2:
2601 return Dec_p1
2602 if other_nan == 2:
2603 return Dec_n1
2604
2605 if self < other:
2606 return Dec_n1
2607 if self > other:
2608 return Dec_p1
2609
2610 if self._exp < other._exp:
2611 if sign:
2612 return Dec_p1
2613 else:
2614 return Dec_n1
2615 if self._exp > other._exp:
2616 if sign:
2617 return Dec_n1
2618 else:
2619 return Dec_p1
2620 return Dec_0
2621
2622
2623 def compare_total_mag(self, other):
2624 """Compares self to other using abstract repr., ignoring sign.
2625
2626 Like compare_total, but with operand's sign ignored and assumed to be 0.
2627 """
2628 s = self.copy_abs()
2629 o = other.copy_abs()
2630 return s.compare_total(o)
2631
2632 def copy_abs(self):
2633 """Returns a copy with the sign set to 0. """
2634 return Decimal((0, self._int, self._exp))
2635
2636 def copy_negate(self):
2637 """Returns a copy with the sign inverted."""
2638 if self._sign:
2639 return Decimal((0, self._int, self._exp))
2640 else:
2641 return Decimal((1, self._int, self._exp))
2642
2643 def copy_sign(self, other):
2644 """Returns self with the sign of other."""
2645 return Decimal((other._sign, self._int, self._exp))
2646
2647 def exp(self, context=None):
2648 """Returns e ** self."""
2649
2650 if context is None:
2651 context = getcontext()
2652
2653 # exp(NaN) = NaN
2654 ans = self._check_nans(context=context)
2655 if ans:
2656 return ans
2657
2658 # exp(-Infinity) = 0
2659 if self._isinfinity() == -1:
2660 return Dec_0
2661
2662 # exp(0) = 1
2663 if not self:
2664 return Dec_p1
2665
2666 # exp(Infinity) = Infinity
2667 if self._isinfinity() == 1:
2668 return Decimal(self)
2669
2670 # the result is now guaranteed to be inexact (the true
2671 # mathematical result is transcendental). There's no need to
2672 # raise Rounded and Inexact here---they'll always be raised as
2673 # a result of the call to _fix.
2674 p = context.prec
2675 adj = self.adjusted()
2676
2677 # we only need to do any computation for quite a small range
2678 # of adjusted exponents---for example, -29 <= adj <= 10 for
2679 # the default context. For smaller exponent the result is
2680 # indistinguishable from 1 at the given precision, while for
2681 # larger exponent the result either overflows or underflows.
2682 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2683 # overflow
2684 ans = Decimal((0, (1,), context.Emax+1))
2685 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2686 # underflow to 0
2687 ans = Decimal((0, (1,), context.Etiny()-1))
2688 elif self._sign == 0 and adj < -p:
2689 # p+1 digits; final round will raise correct flags
2690 ans = Decimal((0, (1,) + (0,)*(p-1) + (1,), -p))
2691 elif self._sign == 1 and adj < -p-1:
2692 # p+1 digits; final round will raise correct flags
2693 ans = Decimal((0, (9,)*(p+1), -p-1))
2694 # general case
2695 else:
2696 op = _WorkRep(self)
2697 c, e = op.int, op.exp
2698 if op.sign == 1:
2699 c = -c
2700
2701 # compute correctly rounded result: increase precision by
2702 # 3 digits at a time until we get an unambiguously
2703 # roundable result
2704 extra = 3
2705 while True:
2706 coeff, exp = _dexp(c, e, p+extra)
2707 if coeff % (5*10**(len(str(coeff))-p-1)):
2708 break
2709 extra += 3
2710
2711 ans = Decimal((0, map(int, str(coeff)), exp))
2712
2713 # at this stage, ans should round correctly with *any*
2714 # rounding mode, not just with ROUND_HALF_EVEN
2715 context = context._shallow_copy()
2716 rounding = context._set_rounding(ROUND_HALF_EVEN)
2717 ans = ans._fix(context)
2718 context.rounding = rounding
2719
2720 return ans
2721
2722 def is_canonical(self):
2723 """Returns 1 if self is canonical; otherwise returns 0."""
2724 return Dec_p1
2725
2726 def is_finite(self):
2727 """Returns 1 if self is finite, otherwise returns 0.
2728
2729 For it to be finite, it must be neither infinite nor a NaN.
2730 """
2731 if self._is_special:
2732 return Dec_0
2733 else:
2734 return Dec_p1
2735
2736 def is_infinite(self):
2737 """Returns 1 if self is an Infinite, otherwise returns 0."""
2738 if self._isinfinity():
2739 return Dec_p1
2740 else:
2741 return Dec_0
2742
2743 def is_nan(self):
2744 """Returns 1 if self is qNaN or sNaN, otherwise returns 0."""
2745 if self._isnan():
2746 return Dec_p1
2747 else:
2748 return Dec_0
2749
2750 def is_normal(self, context=None):
2751 """Returns 1 if self is a normal number, otherwise returns 0."""
2752 if self._is_special:
2753 return Dec_0
2754 if not self:
2755 return Dec_0
2756 if context is None:
2757 context = getcontext()
2758 if context.Emin <= self.adjusted() <= context.Emax:
2759 return Dec_p1
2760 else:
2761 return Dec_0
2762
2763 def is_qnan(self):
2764 """Returns 1 if self is a quiet NaN, otherwise returns 0."""
2765 if self._isnan() == 1:
2766 return Dec_p1
2767 else:
2768 return Dec_0
2769
2770 def is_signed(self):
2771 """Returns 1 if self is negative, otherwise returns 0."""
2772 return Decimal(self._sign)
2773
2774 def is_snan(self):
2775 """Returns 1 if self is a signaling NaN, otherwise returns 0."""
2776 if self._isnan() == 2:
2777 return Dec_p1
2778 else:
2779 return Dec_0
2780
2781 def is_subnormal(self, context=None):
2782 """Returns 1 if self is subnormal, otherwise returns 0."""
2783 if self._is_special:
2784 return Dec_0
2785 if not self:
2786 return Dec_0
2787 if context is None:
2788 context = getcontext()
2789
2790 r = self._exp + len(self._int)
2791 if r <= context.Emin:
2792 return Dec_p1
2793 return Dec_0
2794
2795 def is_zero(self):
2796 """Returns 1 if self is a zero, otherwise returns 0."""
2797 if self:
2798 return Dec_0
2799 else:
2800 return Dec_p1
2801
2802 def _ln_exp_bound(self):
2803 """Compute a lower bound for the adjusted exponent of self.ln().
2804 In other words, compute r such that self.ln() >= 10**r. Assumes
2805 that self is finite and positive and that self != 1.
2806 """
2807
2808 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2809 adj = self._exp + len(self._int) - 1
2810 if adj >= 1:
2811 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2812 return len(str(adj*23//10)) - 1
2813 if adj <= -2:
2814 # argument <= 0.1
2815 return len(str((-1-adj)*23//10)) - 1
2816 op = _WorkRep(self)
2817 c, e = op.int, op.exp
2818 if adj == 0:
2819 # 1 < self < 10
2820 num = str(c-10**-e)
2821 den = str(c)
2822 return len(num) - len(den) - (num < den)
2823 # adj == -1, 0.1 <= self < 1
2824 return e + len(str(10**-e - c)) - 1
2825
2826
2827 def ln(self, context=None):
2828 """Returns the natural (base e) logarithm of self."""
2829
2830 if context is None:
2831 context = getcontext()
2832
2833 # ln(NaN) = NaN
2834 ans = self._check_nans(context=context)
2835 if ans:
2836 return ans
2837
2838 # ln(0.0) == -Infinity
2839 if not self:
2840 return negInf
2841
2842 # ln(Infinity) = Infinity
2843 if self._isinfinity() == 1:
2844 return Inf
2845
2846 # ln(1.0) == 0.0
2847 if self == Dec_p1:
2848 return Dec_0
2849
2850 # ln(negative) raises InvalidOperation
2851 if self._sign == 1:
2852 return context._raise_error(InvalidOperation,
2853 'ln of a negative value')
2854
2855 # result is irrational, so necessarily inexact
2856 op = _WorkRep(self)
2857 c, e = op.int, op.exp
2858 p = context.prec
2859
2860 # correctly rounded result: repeatedly increase precision by 3
2861 # until we get an unambiguously roundable result
2862 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2863 while True:
2864 coeff = _dlog(c, e, places)
2865 # assert len(str(abs(coeff)))-p >= 1
2866 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2867 break
2868 places += 3
2869 ans = Decimal((int(coeff<0), map(int, str(abs(coeff))), -places))
2870
2871 context = context._shallow_copy()
2872 rounding = context._set_rounding(ROUND_HALF_EVEN)
2873 ans = ans._fix(context)
2874 context.rounding = rounding
2875 return ans
2876
2877 def _log10_exp_bound(self):
2878 """Compute a lower bound for the adjusted exponent of self.log10().
2879 In other words, find r such that self.log10() >= 10**r.
2880 Assumes that self is finite and positive and that self != 1.
2881 """
2882
2883 # For x >= 10 or x < 0.1 we only need a bound on the integer
2884 # part of log10(self), and this comes directly from the
2885 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2886 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2887 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2888
2889 adj = self._exp + len(self._int) - 1
2890 if adj >= 1:
2891 # self >= 10
2892 return len(str(adj))-1
2893 if adj <= -2:
2894 # self < 0.1
2895 return len(str(-1-adj))-1
2896 op = _WorkRep(self)
2897 c, e = op.int, op.exp
2898 if adj == 0:
2899 # 1 < self < 10
2900 num = str(c-10**-e)
2901 den = str(231*c)
2902 return len(num) - len(den) - (num < den) + 2
2903 # adj == -1, 0.1 <= self < 1
2904 num = str(10**-e-c)
2905 return len(num) + e - (num < "231") - 1
2906
2907 def log10(self, context=None):
2908 """Returns the base 10 logarithm of self."""
2909
2910 if context is None:
2911 context = getcontext()
2912
2913 # log10(NaN) = NaN
2914 ans = self._check_nans(context=context)
2915 if ans:
2916 return ans
2917
2918 # log10(0.0) == -Infinity
2919 if not self:
2920 return negInf
2921
2922 # log10(Infinity) = Infinity
2923 if self._isinfinity() == 1:
2924 return Inf
2925
2926 # log10(negative or -Infinity) raises InvalidOperation
2927 if self._sign == 1:
2928 return context._raise_error(InvalidOperation,
2929 'log10 of a negative value')
2930
2931 # log10(10**n) = n
2932 if self._int[0] == 1 and self._int[1:] == (0,)*(len(self._int) - 1):
2933 # answer may need rounding
2934 ans = Decimal(self._exp + len(self._int) - 1)
2935 else:
2936 # result is irrational, so necessarily inexact
2937 op = _WorkRep(self)
2938 c, e = op.int, op.exp
2939 p = context.prec
2940
2941 # correctly rounded result: repeatedly increase precision
2942 # until result is unambiguously roundable
2943 places = p-self._log10_exp_bound()+2
2944 while True:
2945 coeff = _dlog10(c, e, places)
2946 # assert len(str(abs(coeff)))-p >= 1
2947 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2948 break
2949 places += 3
2950 ans = Decimal((int(coeff<0), map(int, str(abs(coeff))), -places))
2951
2952 context = context._shallow_copy()
2953 rounding = context._set_rounding(ROUND_HALF_EVEN)
2954 ans = ans._fix(context)
2955 context.rounding = rounding
2956 return ans
2957
2958 def logb(self, context=None):
2959 """ Returns the exponent of the magnitude of self's MSD.
2960
2961 The result is the integer which is the exponent of the magnitude
2962 of the most significant digit of self (as though it were truncated
2963 to a single digit while maintaining the value of that digit and
2964 without limiting the resulting exponent).
2965 """
2966 # logb(NaN) = NaN
2967 ans = self._check_nans(context=context)
2968 if ans:
2969 return ans
2970
2971 if context is None:
2972 context = getcontext()
2973
2974 # logb(+/-Inf) = +Inf
2975 if self._isinfinity():
2976 return Inf
2977
2978 # logb(0) = -Inf, DivisionByZero
2979 if not self:
2980 return context._raise_error(DivisionByZero, 'logb(0)', -1)
2981
2982 # otherwise, simply return the adjusted exponent of self, as a
2983 # Decimal. Note that no attempt is made to fit the result
2984 # into the current context.
2985 return Decimal(self.adjusted())
2986
2987 def _islogical(self):
2988 """Return True if self is a logical operand.
2989
2990 For being logical, it must be a finite numbers with a sign of 0,
2991 an exponent of 0, and a coefficient whose digits must all be
2992 either 0 or 1.
2993 """
2994 if self._sign != 0 or self._exp != 0:
2995 return False
2996 for dig in self._int:
2997 if dig not in (0, 1):
2998 return False
2999 return True
3000
3001 def _fill_logical(self, context, opa, opb):
3002 dif = context.prec - len(opa)
3003 if dif > 0:
3004 opa = (0,)*dif + opa
3005 elif dif < 0:
3006 opa = opa[-context.prec:]
3007 dif = context.prec - len(opb)
3008 if dif > 0:
3009 opb = (0,)*dif + opb
3010 elif dif < 0:
3011 opb = opb[-context.prec:]
3012 return opa, opb
3013
3014 def logical_and(self, other, context=None):
3015 """Applies an 'and' operation between self and other's digits."""
3016 if context is None:
3017 context = getcontext()
3018 if not self._islogical() or not other._islogical():
3019 return context._raise_error(InvalidOperation)
3020
3021 # fill to context.prec
3022 (opa, opb) = self._fill_logical(context, self._int, other._int)
3023
3024 # make the operation, and clean starting zeroes
3025 result = [a&b for a,b in zip(opa,opb)]
3026 for i,d in enumerate(result):
3027 if d == 1:
3028 break
3029 result = tuple(result[i:])
3030
3031 # if empty, we must have at least a zero
3032 if not result:
3033 result = (0,)
3034 return Decimal((0, result, 0))
3035
3036 def logical_invert(self, context=None):
3037 """Invert all its digits."""
3038 if context is None:
3039 context = getcontext()
3040 return self.logical_xor(Decimal((0,(1,)*context.prec,0)), context)
3041
3042 def logical_or(self, other, context=None):
3043 """Applies an 'or' operation between self and other's digits."""
3044 if context is None:
3045 context = getcontext()
3046 if not self._islogical() or not other._islogical():
3047 return context._raise_error(InvalidOperation)
3048
3049 # fill to context.prec
3050 (opa, opb) = self._fill_logical(context, self._int, other._int)
3051
3052 # make the operation, and clean starting zeroes
3053 result = [a|b for a,b in zip(opa,opb)]
3054 for i,d in enumerate(result):
3055 if d == 1:
3056 break
3057 result = tuple(result[i:])
3058
3059 # if empty, we must have at least a zero
3060 if not result:
3061 result = (0,)
3062 return Decimal((0, result, 0))
3063
3064 def logical_xor(self, other, context=None):
3065 """Applies an 'xor' operation between self and other's digits."""
3066 if context is None:
3067 context = getcontext()
3068 if not self._islogical() or not other._islogical():
3069 return context._raise_error(InvalidOperation)
3070
3071 # fill to context.prec
3072 (opa, opb) = self._fill_logical(context, self._int, other._int)
3073
3074 # make the operation, and clean starting zeroes
3075 result = [a^b for a,b in zip(opa,opb)]
3076 for i,d in enumerate(result):
3077 if d == 1:
3078 break
3079 result = tuple(result[i:])
3080
3081 # if empty, we must have at least a zero
3082 if not result:
3083 result = (0,)
3084 return Decimal((0, result, 0))
3085
3086 def max_mag(self, other, context=None):
3087 """Compares the values numerically with their sign ignored."""
3088 other = _convert_other(other, raiseit=True)
3089
3090 if self._is_special or other._is_special:
3091 # If one operand is a quiet NaN and the other is number, then the
3092 # number is always returned
3093 sn = self._isnan()
3094 on = other._isnan()
3095 if sn or on:
3096 if on == 1 and sn != 2:
3097 return self
3098 if sn == 1 and on != 2:
3099 return other
3100 return self._check_nans(other, context)
3101
3102 c = self.copy_abs().__cmp__(other.copy_abs())
3103 if c == 0:
3104 c = self.compare_total(other)
3105
3106 if c == -1:
3107 ans = other
3108 else:
3109 ans = self
3110
3111 if context is None:
3112 context = getcontext()
3113 if context._rounding_decision == ALWAYS_ROUND:
3114 return ans._fix(context)
3115 return ans
3116
3117 def min_mag(self, other, context=None):
3118 """Compares the values numerically with their sign ignored."""
3119 other = _convert_other(other, raiseit=True)
3120
3121 if self._is_special or other._is_special:
3122 # If one operand is a quiet NaN and the other is number, then the
3123 # number is always returned
3124 sn = self._isnan()
3125 on = other._isnan()
3126 if sn or on:
3127 if on == 1 and sn != 2:
3128 return self
3129 if sn == 1 and on != 2:
3130 return other
3131 return self._check_nans(other, context)
3132
3133 c = self.copy_abs().__cmp__(other.copy_abs())
3134 if c == 0:
3135 c = self.compare_total(other)
3136
3137 if c == -1:
3138 ans = self
3139 else:
3140 ans = other
3141
3142 if context is None:
3143 context = getcontext()
3144 if context._rounding_decision == ALWAYS_ROUND:
3145 return ans._fix(context)
3146 return ans
3147
3148 def next_minus(self, context=None):
3149 """Returns the largest representable number smaller than itself."""
3150 if context is None:
3151 context = getcontext()
3152
3153 ans = self._check_nans(context=context)
3154 if ans:
3155 return ans
3156
3157 if self._isinfinity() == -1:
3158 return negInf
3159 if self._isinfinity() == 1:
3160 return Decimal((0, (9,)*context.prec, context.Etop()))
3161
3162 context = context.copy()
3163 context._set_rounding(ROUND_FLOOR)
3164 context._ignore_all_flags()
3165 new_self = self._fix(context)
3166 if new_self != self:
3167 return new_self
3168 return self.__sub__(Decimal((0, (1,), context.Etiny()-1)), context)
3169
3170 def next_plus(self, context=None):
3171 """Returns the smallest representable number larger than itself."""
3172 if context is None:
3173 context = getcontext()
3174
3175 ans = self._check_nans(context=context)
3176 if ans:
3177 return ans
3178
3179 if self._isinfinity() == 1:
3180 return Inf
3181 if self._isinfinity() == -1:
3182 return Decimal((1, (9,)*context.prec, context.Etop()))
3183
3184 context = context.copy()
3185 context._set_rounding(ROUND_CEILING)
3186 context._ignore_all_flags()
3187 new_self = self._fix(context)
3188 if new_self != self:
3189 return new_self
3190 return self.__add__(Decimal((0, (1,), context.Etiny()-1)), context)
3191
3192 def next_toward(self, other, context=None):
3193 """Returns the number closest to self, in the direction towards other.
3194
3195 The result is the closest representable number to self
3196 (excluding self) that is in the direction towards other,
3197 unless both have the same value. If the two operands are
3198 numerically equal, then the result is a copy of self with the
3199 sign set to be the same as the sign of other.
3200 """
3201 other = _convert_other(other, raiseit=True)
3202
3203 if context is None:
3204 context = getcontext()
3205
3206 ans = self._check_nans(other, context)
3207 if ans:
3208 return ans
3209
3210 comparison = self.__cmp__(other)
3211 if comparison == 0:
3212 return Decimal((other._sign, self._int, self._exp))
3213
3214 if comparison == -1:
3215 ans = self.next_plus(context)
3216 else: # comparison == 1
3217 ans = self.next_minus(context)
3218
3219 # decide which flags to raise using value of ans
3220 if ans._isinfinity():
3221 context._raise_error(Overflow,
3222 'Infinite result from next_toward',
3223 ans._sign)
3224 context._raise_error(Rounded)
3225 context._raise_error(Inexact)
3226 elif ans.adjusted() < context.Emin:
3227 context._raise_error(Underflow)
3228 context._raise_error(Subnormal)
3229 context._raise_error(Rounded)
3230 context._raise_error(Inexact)
3231 # if precision == 1 then we don't raise Clamped for a
3232 # result 0E-Etiny.
3233 if not ans:
3234 context._raise_error(Clamped)
3235
3236 return ans
3237
3238 def number_class(self, context=None):
3239 """Returns an indication of the class of self.
3240
3241 The class is one of the following strings:
3242 -sNaN
3243 -NaN
3244 -Infinity
3245 -Normal
3246 -Subnormal
3247 -Zero
3248 +Zero
3249 +Subnormal
3250 +Normal
3251 +Infinity
3252 """
3253 if self.is_snan():
3254 return "sNaN"
3255 if self.is_qnan():
3256 return "NaN"
3257 inf = self._isinfinity()
3258 if inf == 1:
3259 return "+Infinity"
3260 if inf == -1:
3261 return "-Infinity"
3262 if self.is_zero():
3263 if self._sign:
3264 return "-Zero"
3265 else:
3266 return "+Zero"
3267 if context is None:
3268 context = getcontext()
3269 if self.is_subnormal(context=context):
3270 if self._sign:
3271 return "-Subnormal"
3272 else:
3273 return "+Subnormal"
3274 # just a normal, regular, boring number, :)
3275 if self._sign:
3276 return "-Normal"
3277 else:
3278 return "+Normal"
3279
3280 def radix(self):
3281 """Just returns 10, as this is Decimal, :)"""
3282 return Decimal(10)
3283
3284 def rotate(self, other, context=None):
3285 """Returns a rotated copy of self, value-of-other times."""
3286 if context is None:
3287 context = getcontext()
3288
3289 ans = self._check_nans(other, context)
3290 if ans:
3291 return ans
3292
3293 if other._exp != 0:
3294 return context._raise_error(InvalidOperation)
3295 if not (-context.prec <= int(other) <= context.prec):
3296 return context._raise_error(InvalidOperation)
3297
3298 if self._isinfinity():
3299 return self
3300
3301 # get values, pad if necessary
3302 torot = int(other)
3303 rotdig = self._int
3304 topad = context.prec - len(rotdig)
3305 if topad:
3306 rotdig = ((0,)*topad) + rotdig
3307
3308 # let's rotate!
3309 rotated = rotdig[torot:] + rotdig[:torot]
3310
3311 # clean starting zeroes
3312 for i,d in enumerate(rotated):
3313 if d != 0:
3314 break
3315 rotated = rotated[i:]
3316
3317 return Decimal((self._sign, rotated, self._exp))
3318
3319
3320 def scaleb (self, other, context=None):
3321 """Returns self operand after adding the second value to its exp."""
3322 if context is None:
3323 context = getcontext()
3324
3325 ans = self._check_nans(other, context)
3326 if ans:
3327 return ans
3328
3329 if other._exp != 0:
3330 return context._raise_error(InvalidOperation)
3331 liminf = -2 * (context.Emax + context.prec)
3332 limsup = 2 * (context.Emax + context.prec)
3333 if not (liminf <= int(other) <= limsup):
3334 return context._raise_error(InvalidOperation)
3335
3336 if self._isinfinity():
3337 return self
3338
3339 d = Decimal((self._sign, self._int, self._exp + int(other)))
3340 d = d._fix(context)
3341 return d
3342
3343 def shift(self, other, context=None):
3344 """Returns a shifted copy of self, value-of-other times."""
3345 if context is None:
3346 context = getcontext()
3347
3348 ans = self._check_nans(other, context)
3349 if ans:
3350 return ans
3351
3352 if other._exp != 0:
3353 return context._raise_error(InvalidOperation)
3354 if not (-context.prec <= int(other) <= context.prec):
3355 return context._raise_error(InvalidOperation)
3356
3357 if self._isinfinity():
3358 return self
3359
3360 # get values, pad if necessary
3361 torot = int(other)
3362 if not torot:
3363 return self
3364 rotdig = self._int
3365 topad = context.prec - len(rotdig)
3366 if topad:
3367 rotdig = ((0,)*topad) + rotdig
3368
3369 # let's shift!
3370 if torot < 0:
3371 rotated = rotdig[:torot]
3372 else:
3373 rotated = (rotdig + ((0,) * torot))
3374 rotated = rotated[-context.prec:]
3375
3376 # clean starting zeroes
3377 if rotated:
3378 for i,d in enumerate(rotated):
3379 if d != 0:
3380 break
3381 rotated = rotated[i:]
3382 else:
3383 rotated = (0,)
3384
3385 return Decimal((self._sign, rotated, self._exp))
3386
3387
Facundo Batista59c58842007-04-10 12:58:45 +00003388 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003389 def __reduce__(self):
3390 return (self.__class__, (str(self),))
3391
3392 def __copy__(self):
3393 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003394 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003395 return self.__class__(str(self))
3396
3397 def __deepcopy__(self, memo):
3398 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003399 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003400 return self.__class__(str(self))
3401
Facundo Batista59c58842007-04-10 12:58:45 +00003402##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003403
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003404
3405# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003406rounding_functions = [name for name in Decimal.__dict__.keys()
3407 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003408for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003409 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003410 globalname = name[1:].upper()
3411 val = globals()[globalname]
3412 Decimal._pick_rounding_function[val] = name
3413
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003414del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003415
Nick Coghlanced12182006-09-02 03:54:17 +00003416class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003417 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003418
Nick Coghlanced12182006-09-02 03:54:17 +00003419 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003420 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003421 """
3422 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003423 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003424 def __enter__(self):
3425 self.saved_context = getcontext()
3426 setcontext(self.new_context)
3427 return self.new_context
3428 def __exit__(self, t, v, tb):
3429 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003430
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003431class Context(object):
3432 """Contains the context for a Decimal instance.
3433
3434 Contains:
3435 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003436 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003437 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003438 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003439 raised when it is caused. Otherwise, a value is
3440 substituted in.
3441 flags - When an exception is caused, flags[exception] is incremented.
3442 (Whether or not the trap_enabler is set)
3443 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003444 Emin - Minimum exponent
3445 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003446 capitals - If 1, 1*10^1 is printed as 1E+1.
3447 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003448 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003449 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003450
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003451 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003452 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003453 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003454 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003455 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003456 _ignored_flags=None):
3457 if flags is None:
3458 flags = []
3459 if _ignored_flags is None:
3460 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003461 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003462 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003463 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003464 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003465 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003466 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003467 for name, val in locals().items():
3468 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003469 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003470 else:
3471 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003472 del self.self
3473
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003474 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003475 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003476 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003477 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3478 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3479 % vars(self))
3480 names = [f.__name__ for f, v in self.flags.items() if v]
3481 s.append('flags=[' + ', '.join(names) + ']')
3482 names = [t.__name__ for t, v in self.traps.items() if v]
3483 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003484 return ', '.join(s) + ')'
3485
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003486 def clear_flags(self):
3487 """Reset all flags to zero"""
3488 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003489 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003490
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003491 def _shallow_copy(self):
3492 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003493 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003494 self._rounding_decision, self.Emin, self.Emax,
3495 self.capitals, self._clamp, self._ignored_flags)
3496 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003497
3498 def copy(self):
3499 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003500 nc = Context(self.prec, self.rounding, self.traps.copy(),
3501 self.flags.copy(), self._rounding_decision, self.Emin,
3502 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003503 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003504 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003505
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003506 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003507 """Handles an error
3508
3509 If the flag is in _ignored_flags, returns the default response.
3510 Otherwise, it increments the flag, then, if the corresponding
3511 trap_enabler is set, it reaises the exception. Otherwise, it returns
3512 the default value after incrementing the flag.
3513 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003514 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003515 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003516 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003517 return error().handle(self, *args)
3518
3519 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003520 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003521 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003522 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003523
3524 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003525 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003526 raise error, explanation
3527
3528 def _ignore_all_flags(self):
3529 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003530 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003531
3532 def _ignore_flags(self, *flags):
3533 """Ignore the flags, if they are raised"""
3534 # Do not mutate-- This way, copies of a context leave the original
3535 # alone.
3536 self._ignored_flags = (self._ignored_flags + list(flags))
3537 return list(flags)
3538
3539 def _regard_flags(self, *flags):
3540 """Stop ignoring the flags, if they are raised"""
3541 if flags and isinstance(flags[0], (tuple,list)):
3542 flags = flags[0]
3543 for flag in flags:
3544 self._ignored_flags.remove(flag)
3545
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003546 def __hash__(self):
3547 """A Context cannot be hashed."""
3548 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003549 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003550
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003551 def Etiny(self):
3552 """Returns Etiny (= Emin - prec + 1)"""
3553 return int(self.Emin - self.prec + 1)
3554
3555 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003556 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003557 return int(self.Emax - self.prec + 1)
3558
3559 def _set_rounding_decision(self, type):
3560 """Sets the rounding decision.
3561
3562 Sets the rounding decision, and returns the current (previous)
3563 rounding decision. Often used like:
3564
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003565 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003566 # That so you don't change the calling context
3567 # if an error occurs in the middle (say DivisionImpossible is raised).
3568
3569 rounding = context._set_rounding_decision(NEVER_ROUND)
3570 instance = instance / Decimal(2)
3571 context._set_rounding_decision(rounding)
3572
3573 This will make it not round for that operation.
3574 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003575
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003576 rounding = self._rounding_decision
3577 self._rounding_decision = type
3578 return rounding
3579
3580 def _set_rounding(self, type):
3581 """Sets the rounding type.
3582
3583 Sets the rounding type, and returns the current (previous)
3584 rounding type. Often used like:
3585
3586 context = context.copy()
3587 # so you don't change the calling context
3588 # if an error occurs in the middle.
3589 rounding = context._set_rounding(ROUND_UP)
3590 val = self.__sub__(other, context=context)
3591 context._set_rounding(rounding)
3592
3593 This will make it round up for that operation.
3594 """
3595 rounding = self.rounding
3596 self.rounding= type
3597 return rounding
3598
Raymond Hettingerfed52962004-07-14 15:41:57 +00003599 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003600 """Creates a new Decimal instance but using self as context."""
3601 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003602 if d._isnan() and len(d._int) > self.prec - self._clamp:
3603 return self._raise_error(ConversionSyntax,
3604 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003605 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003606
Facundo Batista59c58842007-04-10 12:58:45 +00003607 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003608 def abs(self, a):
3609 """Returns the absolute value of the operand.
3610
3611 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003612 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003613 the plus operation on the operand.
3614
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003615 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003616 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003617 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003618 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003619 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003620 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003621 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003622 Decimal("101.5")
3623 """
3624 return a.__abs__(context=self)
3625
3626 def add(self, a, b):
3627 """Return the sum of the two operands.
3628
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003629 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003630 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003631 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003632 Decimal("1.02E+4")
3633 """
3634 return a.__add__(b, context=self)
3635
3636 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003637 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003638
Facundo Batista353750c2007-09-13 18:13:15 +00003639 def canonical(self, a):
3640 """Returns the same Decimal object.
3641
3642 As we do not have different encodings for the same number, the
3643 received object already is in its canonical form.
3644
3645 >>> ExtendedContext.canonical(Decimal('2.50'))
3646 Decimal("2.50")
3647 """
3648 return a.canonical(context=self)
3649
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003650 def compare(self, a, b):
3651 """Compares values numerically.
3652
3653 If the signs of the operands differ, a value representing each operand
3654 ('-1' if the operand is less than zero, '0' if the operand is zero or
3655 negative zero, or '1' if the operand is greater than zero) is used in
3656 place of that operand for the comparison instead of the actual
3657 operand.
3658
3659 The comparison is then effected by subtracting the second operand from
3660 the first and then returning a value according to the result of the
3661 subtraction: '-1' if the result is less than zero, '0' if the result is
3662 zero or negative zero, or '1' if the result is greater than zero.
3663
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003664 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003665 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003666 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003667 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003668 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003669 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003670 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003671 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003672 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003673 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003674 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003675 Decimal("-1")
3676 """
3677 return a.compare(b, context=self)
3678
Facundo Batista353750c2007-09-13 18:13:15 +00003679 def compare_signal(self, a, b):
3680 """Compares the values of the two operands numerically.
3681
3682 It's pretty much like compare(), but all NaNs signal, with signaling
3683 NaNs taking precedence over quiet NaNs.
3684
3685 >>> c = ExtendedContext
3686 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3687 Decimal("-1")
3688 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3689 Decimal("0")
3690 >>> c.flags[InvalidOperation] = 0
3691 >>> print c.flags[InvalidOperation]
3692 0
3693 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3694 Decimal("NaN")
3695 >>> print c.flags[InvalidOperation]
3696 1
3697 >>> c.flags[InvalidOperation] = 0
3698 >>> print c.flags[InvalidOperation]
3699 0
3700 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3701 Decimal("NaN")
3702 >>> print c.flags[InvalidOperation]
3703 1
3704 """
3705 return a.compare_signal(b, context=self)
3706
3707 def compare_total(self, a, b):
3708 """Compares two operands using their abstract representation.
3709
3710 This is not like the standard compare, which use their numerical
3711 value. Note that a total ordering is defined for all possible abstract
3712 representations.
3713
3714 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3715 Decimal("-1")
3716 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3717 Decimal("-1")
3718 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3719 Decimal("-1")
3720 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3721 Decimal("0")
3722 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3723 Decimal("1")
3724 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3725 Decimal("-1")
3726 """
3727 return a.compare_total(b)
3728
3729 def compare_total_mag(self, a, b):
3730 """Compares two operands using their abstract representation ignoring sign.
3731
3732 Like compare_total, but with operand's sign ignored and assumed to be 0.
3733 """
3734 return a.compare_total_mag(b)
3735
3736 def copy_abs(self, a):
3737 """Returns a copy of the operand with the sign set to 0.
3738
3739 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3740 Decimal("2.1")
3741 >>> ExtendedContext.copy_abs(Decimal('-100'))
3742 Decimal("100")
3743 """
3744 return a.copy_abs()
3745
3746 def copy_decimal(self, a):
3747 """Returns a copy of the decimal objet.
3748
3749 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3750 Decimal("2.1")
3751 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3752 Decimal("-1.00")
3753 """
3754 return a
3755
3756 def copy_negate(self, a):
3757 """Returns a copy of the operand with the sign inverted.
3758
3759 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3760 Decimal("-101.5")
3761 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3762 Decimal("101.5")
3763 """
3764 return a.copy_negate()
3765
3766 def copy_sign(self, a, b):
3767 """Copies the second operand's sign to the first one.
3768
3769 In detail, it returns a copy of the first operand with the sign
3770 equal to the sign of the second operand.
3771
3772 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3773 Decimal("1.50")
3774 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3775 Decimal("1.50")
3776 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3777 Decimal("-1.50")
3778 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3779 Decimal("-1.50")
3780 """
3781 return a.copy_sign(b)
3782
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003783 def divide(self, a, b):
3784 """Decimal division in a specified context.
3785
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003786 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003787 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003788 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003789 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003790 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003791 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003792 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003793 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003794 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003795 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003796 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003797 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003798 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003799 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003800 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003801 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003802 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003803 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003804 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003805 Decimal("1.20E+6")
3806 """
3807 return a.__div__(b, context=self)
3808
3809 def divide_int(self, a, b):
3810 """Divides two numbers and returns the integer part of the result.
3811
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003812 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003813 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003814 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003815 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003816 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003817 Decimal("3")
3818 """
3819 return a.__floordiv__(b, context=self)
3820
3821 def divmod(self, a, b):
3822 return a.__divmod__(b, context=self)
3823
Facundo Batista353750c2007-09-13 18:13:15 +00003824 def exp(self, a):
3825 """Returns e ** a.
3826
3827 >>> c = ExtendedContext.copy()
3828 >>> c.Emin = -999
3829 >>> c.Emax = 999
3830 >>> c.exp(Decimal('-Infinity'))
3831 Decimal("0")
3832 >>> c.exp(Decimal('-1'))
3833 Decimal("0.367879441")
3834 >>> c.exp(Decimal('0'))
3835 Decimal("1")
3836 >>> c.exp(Decimal('1'))
3837 Decimal("2.71828183")
3838 >>> c.exp(Decimal('0.693147181'))
3839 Decimal("2.00000000")
3840 >>> c.exp(Decimal('+Infinity'))
3841 Decimal("Infinity")
3842 """
3843 return a.exp(context=self)
3844
3845 def fma(self, a, b, c):
3846 """Returns a multiplied by b, plus c.
3847
3848 The first two operands are multiplied together, using multiply,
3849 the third operand is then added to the result of that
3850 multiplication, using add, all with only one final rounding.
3851
3852 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3853 Decimal("22")
3854 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3855 Decimal("-8")
3856 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3857 Decimal("1.38435736E+12")
3858 """
3859 return a.fma(b, c, context=self)
3860
3861 def is_canonical(self, a):
3862 """Returns 1 if the operand is canonical; otherwise returns 0.
3863
3864 >>> ExtendedContext.is_canonical(Decimal('2.50'))
3865 Decimal("1")
3866 """
3867 return Dec_p1
3868
3869 def is_finite(self, a):
3870 """Returns 1 if the operand is finite, otherwise returns 0.
3871
3872 For it to be finite, it must be neither infinite nor a NaN.
3873
3874 >>> ExtendedContext.is_finite(Decimal('2.50'))
3875 Decimal("1")
3876 >>> ExtendedContext.is_finite(Decimal('-0.3'))
3877 Decimal("1")
3878 >>> ExtendedContext.is_finite(Decimal('0'))
3879 Decimal("1")
3880 >>> ExtendedContext.is_finite(Decimal('Inf'))
3881 Decimal("0")
3882 >>> ExtendedContext.is_finite(Decimal('NaN'))
3883 Decimal("0")
3884 """
3885 return a.is_finite()
3886
3887 def is_infinite(self, a):
3888 """Returns 1 if the operand is an Infinite, otherwise returns 0.
3889
3890 >>> ExtendedContext.is_infinite(Decimal('2.50'))
3891 Decimal("0")
3892 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
3893 Decimal("1")
3894 >>> ExtendedContext.is_infinite(Decimal('NaN'))
3895 Decimal("0")
3896 """
3897 return a.is_infinite()
3898
3899 def is_nan(self, a):
3900 """Returns 1 if the operand is qNaN or sNaN, otherwise returns 0.
3901
3902 >>> ExtendedContext.is_nan(Decimal('2.50'))
3903 Decimal("0")
3904 >>> ExtendedContext.is_nan(Decimal('NaN'))
3905 Decimal("1")
3906 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
3907 Decimal("1")
3908 """
3909 return a.is_nan()
3910
3911 def is_normal(self, a):
3912 """Returns 1 if the operand is a normal number, otherwise returns 0.
3913
3914 >>> c = ExtendedContext.copy()
3915 >>> c.Emin = -999
3916 >>> c.Emax = 999
3917 >>> c.is_normal(Decimal('2.50'))
3918 Decimal("1")
3919 >>> c.is_normal(Decimal('0.1E-999'))
3920 Decimal("0")
3921 >>> c.is_normal(Decimal('0.00'))
3922 Decimal("0")
3923 >>> c.is_normal(Decimal('-Inf'))
3924 Decimal("0")
3925 >>> c.is_normal(Decimal('NaN'))
3926 Decimal("0")
3927 """
3928 return a.is_normal(context=self)
3929
3930 def is_qnan(self, a):
3931 """Returns 1 if the operand is a quiet NaN, otherwise returns 0.
3932
3933 >>> ExtendedContext.is_qnan(Decimal('2.50'))
3934 Decimal("0")
3935 >>> ExtendedContext.is_qnan(Decimal('NaN'))
3936 Decimal("1")
3937 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
3938 Decimal("0")
3939 """
3940 return a.is_qnan()
3941
3942 def is_signed(self, a):
3943 """Returns 1 if the operand is negative, otherwise returns 0.
3944
3945 >>> ExtendedContext.is_signed(Decimal('2.50'))
3946 Decimal("0")
3947 >>> ExtendedContext.is_signed(Decimal('-12'))
3948 Decimal("1")
3949 >>> ExtendedContext.is_signed(Decimal('-0'))
3950 Decimal("1")
3951 """
3952 return a.is_signed()
3953
3954 def is_snan(self, a):
3955 """Returns 1 if the operand is a signaling NaN, otherwise returns 0.
3956
3957 >>> ExtendedContext.is_snan(Decimal('2.50'))
3958 Decimal("0")
3959 >>> ExtendedContext.is_snan(Decimal('NaN'))
3960 Decimal("0")
3961 >>> ExtendedContext.is_snan(Decimal('sNaN'))
3962 Decimal("1")
3963 """
3964 return a.is_snan()
3965
3966 def is_subnormal(self, a):
3967 """Returns 1 if the operand is subnormal, otherwise returns 0.
3968
3969 >>> c = ExtendedContext.copy()
3970 >>> c.Emin = -999
3971 >>> c.Emax = 999
3972 >>> c.is_subnormal(Decimal('2.50'))
3973 Decimal("0")
3974 >>> c.is_subnormal(Decimal('0.1E-999'))
3975 Decimal("1")
3976 >>> c.is_subnormal(Decimal('0.00'))
3977 Decimal("0")
3978 >>> c.is_subnormal(Decimal('-Inf'))
3979 Decimal("0")
3980 >>> c.is_subnormal(Decimal('NaN'))
3981 Decimal("0")
3982 """
3983 return a.is_subnormal(context=self)
3984
3985 def is_zero(self, a):
3986 """Returns 1 if the operand is a zero, otherwise returns 0.
3987
3988 >>> ExtendedContext.is_zero(Decimal('0'))
3989 Decimal("1")
3990 >>> ExtendedContext.is_zero(Decimal('2.50'))
3991 Decimal("0")
3992 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
3993 Decimal("1")
3994 """
3995 return a.is_zero()
3996
3997 def ln(self, a):
3998 """Returns the natural (base e) logarithm of the operand.
3999
4000 >>> c = ExtendedContext.copy()
4001 >>> c.Emin = -999
4002 >>> c.Emax = 999
4003 >>> c.ln(Decimal('0'))
4004 Decimal("-Infinity")
4005 >>> c.ln(Decimal('1.000'))
4006 Decimal("0")
4007 >>> c.ln(Decimal('2.71828183'))
4008 Decimal("1.00000000")
4009 >>> c.ln(Decimal('10'))
4010 Decimal("2.30258509")
4011 >>> c.ln(Decimal('+Infinity'))
4012 Decimal("Infinity")
4013 """
4014 return a.ln(context=self)
4015
4016 def log10(self, a):
4017 """Returns the base 10 logarithm of the operand.
4018
4019 >>> c = ExtendedContext.copy()
4020 >>> c.Emin = -999
4021 >>> c.Emax = 999
4022 >>> c.log10(Decimal('0'))
4023 Decimal("-Infinity")
4024 >>> c.log10(Decimal('0.001'))
4025 Decimal("-3")
4026 >>> c.log10(Decimal('1.000'))
4027 Decimal("0")
4028 >>> c.log10(Decimal('2'))
4029 Decimal("0.301029996")
4030 >>> c.log10(Decimal('10'))
4031 Decimal("1")
4032 >>> c.log10(Decimal('70'))
4033 Decimal("1.84509804")
4034 >>> c.log10(Decimal('+Infinity'))
4035 Decimal("Infinity")
4036 """
4037 return a.log10(context=self)
4038
4039 def logb(self, a):
4040 """ Returns the exponent of the magnitude of the operand's MSD.
4041
4042 The result is the integer which is the exponent of the magnitude
4043 of the most significant digit of the operand (as though the
4044 operand were truncated to a single digit while maintaining the
4045 value of that digit and without limiting the resulting exponent).
4046
4047 >>> ExtendedContext.logb(Decimal('250'))
4048 Decimal("2")
4049 >>> ExtendedContext.logb(Decimal('2.50'))
4050 Decimal("0")
4051 >>> ExtendedContext.logb(Decimal('0.03'))
4052 Decimal("-2")
4053 >>> ExtendedContext.logb(Decimal('0'))
4054 Decimal("-Infinity")
4055 """
4056 return a.logb(context=self)
4057
4058 def logical_and(self, a, b):
4059 """Applies the logical operation 'and' between each operand's digits.
4060
4061 The operands must be both logical numbers.
4062
4063 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4064 Decimal("0")
4065 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4066 Decimal("0")
4067 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4068 Decimal("0")
4069 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4070 Decimal("1")
4071 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4072 Decimal("1000")
4073 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4074 Decimal("10")
4075 """
4076 return a.logical_and(b, context=self)
4077
4078 def logical_invert(self, a):
4079 """Invert all the digits in the operand.
4080
4081 The operand must be a logical number.
4082
4083 >>> ExtendedContext.logical_invert(Decimal('0'))
4084 Decimal("111111111")
4085 >>> ExtendedContext.logical_invert(Decimal('1'))
4086 Decimal("111111110")
4087 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4088 Decimal("0")
4089 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4090 Decimal("10101010")
4091 """
4092 return a.logical_invert(context=self)
4093
4094 def logical_or(self, a, b):
4095 """Applies the logical operation 'or' between each operand's digits.
4096
4097 The operands must be both logical numbers.
4098
4099 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4100 Decimal("0")
4101 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4102 Decimal("1")
4103 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4104 Decimal("1")
4105 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4106 Decimal("1")
4107 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4108 Decimal("1110")
4109 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4110 Decimal("1110")
4111 """
4112 return a.logical_or(b, context=self)
4113
4114 def logical_xor(self, a, b):
4115 """Applies the logical operation 'xor' between each operand's digits.
4116
4117 The operands must be both logical numbers.
4118
4119 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4120 Decimal("0")
4121 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4122 Decimal("1")
4123 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4124 Decimal("1")
4125 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4126 Decimal("0")
4127 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4128 Decimal("110")
4129 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4130 Decimal("1101")
4131 """
4132 return a.logical_xor(b, context=self)
4133
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004134 def max(self, a,b):
4135 """max compares two values numerically and returns the maximum.
4136
4137 If either operand is a NaN then the general rules apply.
4138 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004139 operation. If they are numerically equal then the left-hand operand
4140 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004141 infinity) of the two operands is chosen as the result.
4142
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004143 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004144 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004145 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004146 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004147 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004148 Decimal("1")
4149 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4150 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004151 """
4152 return a.max(b, context=self)
4153
Facundo Batista353750c2007-09-13 18:13:15 +00004154 def max_mag(self, a, b):
4155 """Compares the values numerically with their sign ignored."""
4156 return a.max_mag(b, context=self)
4157
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004158 def min(self, a,b):
4159 """min compares two values numerically and returns the minimum.
4160
4161 If either operand is a NaN then the general rules apply.
4162 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004163 operation. If they are numerically equal then the left-hand operand
4164 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004165 infinity) of the two operands is chosen as the result.
4166
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004167 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004168 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004169 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004170 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004171 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004172 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004173 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4174 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004175 """
4176 return a.min(b, context=self)
4177
Facundo Batista353750c2007-09-13 18:13:15 +00004178 def min_mag(self, a, b):
4179 """Compares the values numerically with their sign ignored."""
4180 return a.min_mag(b, context=self)
4181
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004182 def minus(self, a):
4183 """Minus corresponds to unary prefix minus in Python.
4184
4185 The operation is evaluated using the same rules as subtract; the
4186 operation minus(a) is calculated as subtract('0', a) where the '0'
4187 has the same exponent as the operand.
4188
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004189 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004190 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004191 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004192 Decimal("1.3")
4193 """
4194 return a.__neg__(context=self)
4195
4196 def multiply(self, a, b):
4197 """multiply multiplies two operands.
4198
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004199 If either operand is a special value then the general rules apply.
4200 Otherwise, the operands are multiplied together ('long multiplication'),
4201 resulting in a number which may be as long as the sum of the lengths
4202 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004203
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004204 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004205 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004206 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004207 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004208 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004209 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004210 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004211 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004212 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004213 Decimal("4.28135971E+11")
4214 """
4215 return a.__mul__(b, context=self)
4216
Facundo Batista353750c2007-09-13 18:13:15 +00004217 def next_minus(self, a):
4218 """Returns the largest representable number smaller than a.
4219
4220 >>> c = ExtendedContext.copy()
4221 >>> c.Emin = -999
4222 >>> c.Emax = 999
4223 >>> ExtendedContext.next_minus(Decimal('1'))
4224 Decimal("0.999999999")
4225 >>> c.next_minus(Decimal('1E-1007'))
4226 Decimal("0E-1007")
4227 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4228 Decimal("-1.00000004")
4229 >>> c.next_minus(Decimal('Infinity'))
4230 Decimal("9.99999999E+999")
4231 """
4232 return a.next_minus(context=self)
4233
4234 def next_plus(self, a):
4235 """Returns the smallest representable number larger than a.
4236
4237 >>> c = ExtendedContext.copy()
4238 >>> c.Emin = -999
4239 >>> c.Emax = 999
4240 >>> ExtendedContext.next_plus(Decimal('1'))
4241 Decimal("1.00000001")
4242 >>> c.next_plus(Decimal('-1E-1007'))
4243 Decimal("-0E-1007")
4244 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4245 Decimal("-1.00000002")
4246 >>> c.next_plus(Decimal('-Infinity'))
4247 Decimal("-9.99999999E+999")
4248 """
4249 return a.next_plus(context=self)
4250
4251 def next_toward(self, a, b):
4252 """Returns the number closest to a, in direction towards b.
4253
4254 The result is the closest representable number from the first
4255 operand (but not the first operand) that is in the direction
4256 towards the second operand, unless the operands have the same
4257 value.
4258
4259 >>> c = ExtendedContext.copy()
4260 >>> c.Emin = -999
4261 >>> c.Emax = 999
4262 >>> c.next_toward(Decimal('1'), Decimal('2'))
4263 Decimal("1.00000001")
4264 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4265 Decimal("-0E-1007")
4266 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4267 Decimal("-1.00000002")
4268 >>> c.next_toward(Decimal('1'), Decimal('0'))
4269 Decimal("0.999999999")
4270 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4271 Decimal("0E-1007")
4272 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4273 Decimal("-1.00000004")
4274 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4275 Decimal("-0.00")
4276 """
4277 return a.next_toward(b, context=self)
4278
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004279 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004280 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004281
4282 Essentially a plus operation with all trailing zeros removed from the
4283 result.
4284
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004285 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004286 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004287 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004288 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004289 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004290 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004291 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004292 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004293 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004294 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004295 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004296 Decimal("0")
4297 """
4298 return a.normalize(context=self)
4299
Facundo Batista353750c2007-09-13 18:13:15 +00004300 def number_class(self, a):
4301 """Returns an indication of the class of the operand.
4302
4303 The class is one of the following strings:
4304 -sNaN
4305 -NaN
4306 -Infinity
4307 -Normal
4308 -Subnormal
4309 -Zero
4310 +Zero
4311 +Subnormal
4312 +Normal
4313 +Infinity
4314
4315 >>> c = Context(ExtendedContext)
4316 >>> c.Emin = -999
4317 >>> c.Emax = 999
4318 >>> c.number_class(Decimal('Infinity'))
4319 '+Infinity'
4320 >>> c.number_class(Decimal('1E-10'))
4321 '+Normal'
4322 >>> c.number_class(Decimal('2.50'))
4323 '+Normal'
4324 >>> c.number_class(Decimal('0.1E-999'))
4325 '+Subnormal'
4326 >>> c.number_class(Decimal('0'))
4327 '+Zero'
4328 >>> c.number_class(Decimal('-0'))
4329 '-Zero'
4330 >>> c.number_class(Decimal('-0.1E-999'))
4331 '-Subnormal'
4332 >>> c.number_class(Decimal('-1E-10'))
4333 '-Normal'
4334 >>> c.number_class(Decimal('-2.50'))
4335 '-Normal'
4336 >>> c.number_class(Decimal('-Infinity'))
4337 '-Infinity'
4338 >>> c.number_class(Decimal('NaN'))
4339 'NaN'
4340 >>> c.number_class(Decimal('-NaN'))
4341 'NaN'
4342 >>> c.number_class(Decimal('sNaN'))
4343 'sNaN'
4344 """
4345 return a.number_class(context=self)
4346
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004347 def plus(self, a):
4348 """Plus corresponds to unary prefix plus in Python.
4349
4350 The operation is evaluated using the same rules as add; the
4351 operation plus(a) is calculated as add('0', a) where the '0'
4352 has the same exponent as the operand.
4353
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004354 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004355 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004356 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004357 Decimal("-1.3")
4358 """
4359 return a.__pos__(context=self)
4360
4361 def power(self, a, b, modulo=None):
4362 """Raises a to the power of b, to modulo if given.
4363
Facundo Batista353750c2007-09-13 18:13:15 +00004364 With two arguments, compute a**b. If a is negative then b
4365 must be integral. The result will be inexact unless b is
4366 integral and the result is finite and can be expressed exactly
4367 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004368
Facundo Batista353750c2007-09-13 18:13:15 +00004369 With three arguments, compute (a**b) % modulo. For the
4370 three argument form, the following restrictions on the
4371 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004372
Facundo Batista353750c2007-09-13 18:13:15 +00004373 - all three arguments must be integral
4374 - b must be nonnegative
4375 - at least one of a or b must be nonzero
4376 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004377
Facundo Batista353750c2007-09-13 18:13:15 +00004378 The result of pow(a, b, modulo) is identical to the result
4379 that would be obtained by computing (a**b) % modulo with
4380 unbounded precision, but is computed more efficiently. It is
4381 always exact.
4382
4383 >>> c = ExtendedContext.copy()
4384 >>> c.Emin = -999
4385 >>> c.Emax = 999
4386 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004387 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004388 >>> c.power(Decimal('-2'), Decimal('3'))
4389 Decimal("-8")
4390 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004391 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004392 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004393 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004394 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4395 Decimal("2.00000000")
4396 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004397 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004398 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004399 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004400 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004401 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004402 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004403 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004404 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004405 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004406 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004407 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004408 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004409 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004410 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004411 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004412
4413 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4414 Decimal("11")
4415 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4416 Decimal("-11")
4417 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4418 Decimal("1")
4419 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4420 Decimal("11")
4421 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4422 Decimal("11729830")
4423 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4424 Decimal("-0")
4425 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4426 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004427 """
4428 return a.__pow__(b, modulo, context=self)
4429
4430 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004431 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004432
4433 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004434 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004435 exponent is being increased), multiplied by a positive power of ten (if
4436 the exponent is being decreased), or is unchanged (if the exponent is
4437 already equal to that of the right-hand operand).
4438
4439 Unlike other operations, if the length of the coefficient after the
4440 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004441 operation condition is raised. This guarantees that, unless there is
4442 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004443 equal to that of the right-hand operand.
4444
4445 Also unlike other operations, quantize will never raise Underflow, even
4446 if the result is subnormal and inexact.
4447
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004448 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004449 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004450 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004451 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004452 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004453 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004454 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004455 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004456 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004457 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004458 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004459 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004460 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004461 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004462 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004463 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004464 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004465 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004466 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004467 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004468 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004469 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004470 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004471 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004472 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004473 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004474 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004475 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004476 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004477 Decimal("2E+2")
4478 """
4479 return a.quantize(b, context=self)
4480
Facundo Batista353750c2007-09-13 18:13:15 +00004481 def radix(self):
4482 """Just returns 10, as this is Decimal, :)
4483
4484 >>> ExtendedContext.radix()
4485 Decimal("10")
4486 """
4487 return Decimal(10)
4488
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004489 def remainder(self, a, b):
4490 """Returns the remainder from integer division.
4491
4492 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004493 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004494 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004495 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004496
4497 This operation will fail under the same conditions as integer division
4498 (that is, if integer division on the same two operands would fail, the
4499 remainder cannot be calculated).
4500
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004501 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004502 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004503 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004504 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004505 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004506 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004507 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004508 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004509 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004510 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004511 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004512 Decimal("1.0")
4513 """
4514 return a.__mod__(b, context=self)
4515
4516 def remainder_near(self, a, b):
4517 """Returns to be "a - b * n", where n is the integer nearest the exact
4518 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004519 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004520 sign of a.
4521
4522 This operation will fail under the same conditions as integer division
4523 (that is, if integer division on the same two operands would fail, the
4524 remainder cannot be calculated).
4525
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004526 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004527 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004528 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004529 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004530 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004531 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004532 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004533 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004534 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004535 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004536 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004537 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004538 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004539 Decimal("-0.3")
4540 """
4541 return a.remainder_near(b, context=self)
4542
Facundo Batista353750c2007-09-13 18:13:15 +00004543 def rotate(self, a, b):
4544 """Returns a rotated copy of a, b times.
4545
4546 The coefficient of the result is a rotated copy of the digits in
4547 the coefficient of the first operand. The number of places of
4548 rotation is taken from the absolute value of the second operand,
4549 with the rotation being to the left if the second operand is
4550 positive or to the right otherwise.
4551
4552 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4553 Decimal("400000003")
4554 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4555 Decimal("12")
4556 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4557 Decimal("891234567")
4558 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4559 Decimal("123456789")
4560 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4561 Decimal("345678912")
4562 """
4563 return a.rotate(b, context=self)
4564
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004565 def same_quantum(self, a, b):
4566 """Returns True if the two operands have the same exponent.
4567
4568 The result is never affected by either the sign or the coefficient of
4569 either operand.
4570
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004571 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004572 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004573 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004574 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004575 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004576 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004577 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004578 True
4579 """
4580 return a.same_quantum(b)
4581
Facundo Batista353750c2007-09-13 18:13:15 +00004582 def scaleb (self, a, b):
4583 """Returns the first operand after adding the second value its exp.
4584
4585 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4586 Decimal("0.0750")
4587 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4588 Decimal("7.50")
4589 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4590 Decimal("7.50E+3")
4591 """
4592 return a.scaleb (b, context=self)
4593
4594 def shift(self, a, b):
4595 """Returns a shifted copy of a, b times.
4596
4597 The coefficient of the result is a shifted copy of the digits
4598 in the coefficient of the first operand. The number of places
4599 to shift is taken from the absolute value of the second operand,
4600 with the shift being to the left if the second operand is
4601 positive or to the right otherwise. Digits shifted into the
4602 coefficient are zeros.
4603
4604 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4605 Decimal("400000000")
4606 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4607 Decimal("0")
4608 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4609 Decimal("1234567")
4610 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4611 Decimal("123456789")
4612 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4613 Decimal("345678900")
4614 """
4615 return a.shift(b, context=self)
4616
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004617 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004618 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004619
4620 If the result must be inexact, it is rounded using the round-half-even
4621 algorithm.
4622
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004623 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004624 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004625 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004626 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004627 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004628 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004629 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004630 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004631 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004632 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004633 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004634 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004635 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004636 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004637 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004638 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004639 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004640 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004641 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004642 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004643 """
4644 return a.sqrt(context=self)
4645
4646 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004647 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004648
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004649 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004650 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004651 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004652 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004653 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004654 Decimal("-0.77")
4655 """
4656 return a.__sub__(b, context=self)
4657
4658 def to_eng_string(self, a):
4659 """Converts a number to a string, using scientific notation.
4660
4661 The operation is not affected by the context.
4662 """
4663 return a.to_eng_string(context=self)
4664
4665 def to_sci_string(self, a):
4666 """Converts a number to a string, using scientific notation.
4667
4668 The operation is not affected by the context.
4669 """
4670 return a.__str__(context=self)
4671
Facundo Batista353750c2007-09-13 18:13:15 +00004672 def to_integral_exact(self, a):
4673 """Rounds to an integer.
4674
4675 When the operand has a negative exponent, the result is the same
4676 as using the quantize() operation using the given operand as the
4677 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4678 of the operand as the precision setting; Inexact and Rounded flags
4679 are allowed in this operation. The rounding mode is taken from the
4680 context.
4681
4682 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4683 Decimal("2")
4684 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4685 Decimal("100")
4686 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4687 Decimal("100")
4688 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4689 Decimal("102")
4690 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4691 Decimal("-102")
4692 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4693 Decimal("1.0E+6")
4694 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4695 Decimal("7.89E+77")
4696 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4697 Decimal("-Infinity")
4698 """
4699 return a.to_integral_exact(context=self)
4700
4701 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004702 """Rounds to an integer.
4703
4704 When the operand has a negative exponent, the result is the same
4705 as using the quantize() operation using the given operand as the
4706 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4707 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004708 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004709
Facundo Batista353750c2007-09-13 18:13:15 +00004710 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004711 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004712 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004713 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004714 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004715 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004716 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004717 Decimal("102")
Facundo Batista353750c2007-09-13 18:13:15 +00004718 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004719 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004720 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004721 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004722 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004723 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004724 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004725 Decimal("-Infinity")
4726 """
Facundo Batista353750c2007-09-13 18:13:15 +00004727 return a.to_integral_value(context=self)
4728
4729 # the method name changed, but we provide also the old one, for compatibility
4730 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004731
4732class _WorkRep(object):
4733 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004734 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004735 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004736 # exp: None, int, or string
4737
4738 def __init__(self, value=None):
4739 if value is None:
4740 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004741 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004742 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004743 elif isinstance(value, Decimal):
4744 self.sign = value._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004745 cum = 0
Raymond Hettinger17931de2004-10-27 06:21:46 +00004746 for digit in value._int:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004747 cum = cum * 10 + digit
4748 self.int = cum
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004749 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004750 else:
4751 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004752 self.sign = value[0]
4753 self.int = value[1]
4754 self.exp = value[2]
4755
4756 def __repr__(self):
4757 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4758
4759 __str__ = __repr__
4760
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004761
4762
4763def _normalize(op1, op2, shouldround = 0, prec = 0):
4764 """Normalizes op1, op2 to have the same exp and length of coefficient.
4765
4766 Done during addition.
4767 """
Facundo Batista353750c2007-09-13 18:13:15 +00004768 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004769 tmp = op2
4770 other = op1
4771 else:
4772 tmp = op1
4773 other = op2
4774
Facundo Batista353750c2007-09-13 18:13:15 +00004775 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4776 # Then adding 10**exp to tmp has the same effect (after rounding)
4777 # as adding any positive quantity smaller than 10**exp; similarly
4778 # for subtraction. So if other is smaller than 10**exp we replace
4779 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4780 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004781 tmp_len = len(str(tmp.int))
4782 other_len = len(str(other.int))
Facundo Batista353750c2007-09-13 18:13:15 +00004783 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4784 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004785 other.int = 1
Facundo Batista353750c2007-09-13 18:13:15 +00004786 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004787
Facundo Batista353750c2007-09-13 18:13:15 +00004788 tmp.int *= 10 ** (tmp.exp - other.exp)
4789 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004790 return op1, op2
4791
4792def _adjust_coefficients(op1, op2):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004793 """Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004794
4795 Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp.
4796
4797 Used on _WorkRep instances during division.
4798 """
4799 adjust = 0
Facundo Batista59c58842007-04-10 12:58:45 +00004800 # If op1 is smaller, make it larger
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004801 while op2.int > op1.int:
4802 op1.int *= 10
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004803 op1.exp -= 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004804 adjust += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004805
Facundo Batista59c58842007-04-10 12:58:45 +00004806 # If op2 is too small, make it larger
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004807 while op1.int >= (10 * op2.int):
4808 op2.int *= 10
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004809 op2.exp -= 1
4810 adjust -= 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004811
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004812 return op1, op2, adjust
4813
Facundo Batista353750c2007-09-13 18:13:15 +00004814
4815##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4816
4817# This function from Tim Peters was taken from here:
4818# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4819# The correction being in the function definition is for speed, and
4820# the whole function is not resolved with math.log because of avoiding
4821# the use of floats.
4822def _nbits(n, correction = {
4823 '0': 4, '1': 3, '2': 2, '3': 2,
4824 '4': 1, '5': 1, '6': 1, '7': 1,
4825 '8': 0, '9': 0, 'a': 0, 'b': 0,
4826 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4827 """Number of bits in binary representation of the positive integer n,
4828 or 0 if n == 0.
4829 """
4830 if n < 0:
4831 raise ValueError("The argument to _nbits should be nonnegative.")
4832 hex_n = "%x" % n
4833 return 4*len(hex_n) - correction[hex_n[0]]
4834
4835def _sqrt_nearest(n, a):
4836 """Closest integer to the square root of the positive integer n. a is
4837 an initial approximation to the square root. Any positive integer
4838 will do for a, but the closer a is to the square root of n the
4839 faster convergence will be.
4840
4841 """
4842 if n <= 0 or a <= 0:
4843 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4844
4845 b=0
4846 while a != b:
4847 b, a = a, a--n//a>>1
4848 return a
4849
4850def _rshift_nearest(x, shift):
4851 """Given an integer x and a nonnegative integer shift, return closest
4852 integer to x / 2**shift; use round-to-even in case of a tie.
4853
4854 """
4855 b, q = 1L << shift, x >> shift
4856 return q + (2*(x & (b-1)) + (q&1) > b)
4857
4858def _div_nearest(a, b):
4859 """Closest integer to a/b, a and b positive integers; rounds to even
4860 in the case of a tie.
4861
4862 """
4863 q, r = divmod(a, b)
4864 return q + (2*r + (q&1) > b)
4865
4866def _ilog(x, M, L = 8):
4867 """Integer approximation to M*log(x/M), with absolute error boundable
4868 in terms only of x/M.
4869
4870 Given positive integers x and M, return an integer approximation to
4871 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4872 between the approximation and the exact result is at most 22. For
4873 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4874 both cases these are upper bounds on the error; it will usually be
4875 much smaller."""
4876
4877 # The basic algorithm is the following: let log1p be the function
4878 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4879 # the reduction
4880 #
4881 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4882 #
4883 # repeatedly until the argument to log1p is small (< 2**-L in
4884 # absolute value). For small y we can use the Taylor series
4885 # expansion
4886 #
4887 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4888 #
4889 # truncating at T such that y**T is small enough. The whole
4890 # computation is carried out in a form of fixed-point arithmetic,
4891 # with a real number z being represented by an integer
4892 # approximation to z*M. To avoid loss of precision, the y below
4893 # is actually an integer approximation to 2**R*y*M, where R is the
4894 # number of reductions performed so far.
4895
4896 y = x-M
4897 # argument reduction; R = number of reductions performed
4898 R = 0
4899 while (R <= L and long(abs(y)) << L-R >= M or
4900 R > L and abs(y) >> R-L >= M):
4901 y = _div_nearest(long(M*y) << 1,
4902 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4903 R += 1
4904
4905 # Taylor series with T terms
4906 T = -int(-10*len(str(M))//(3*L))
4907 yshift = _rshift_nearest(y, R)
4908 w = _div_nearest(M, T)
4909 for k in xrange(T-1, 0, -1):
4910 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4911
4912 return _div_nearest(w*y, M)
4913
4914def _dlog10(c, e, p):
4915 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4916 approximation to 10**p * log10(c*10**e), with an absolute error of
4917 at most 1. Assumes that c*10**e is not exactly 1."""
4918
4919 # increase precision by 2; compensate for this by dividing
4920 # final result by 100
4921 p += 2
4922
4923 # write c*10**e as d*10**f with either:
4924 # f >= 0 and 1 <= d <= 10, or
4925 # f <= 0 and 0.1 <= d <= 1.
4926 # Thus for c*10**e close to 1, f = 0
4927 l = len(str(c))
4928 f = e+l - (e+l >= 1)
4929
4930 if p > 0:
4931 M = 10**p
4932 k = e+p-f
4933 if k >= 0:
4934 c *= 10**k
4935 else:
4936 c = _div_nearest(c, 10**-k)
4937
4938 log_d = _ilog(c, M) # error < 5 + 22 = 27
4939 log_10 = _ilog(10*M, M) # error < 15
4940 log_d = _div_nearest(log_d*M, log_10)
4941 log_tenpower = f*M # exact
4942 else:
4943 log_d = 0 # error < 2.31
4944 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4945
4946 return _div_nearest(log_tenpower+log_d, 100)
4947
4948def _dlog(c, e, p):
4949 """Given integers c, e and p with c > 0, compute an integer
4950 approximation to 10**p * log(c*10**e), with an absolute error of
4951 at most 1. Assumes that c*10**e is not exactly 1."""
4952
4953 # Increase precision by 2. The precision increase is compensated
4954 # for at the end with a division by 100.
4955 p += 2
4956
4957 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4958 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4959 # as 10**p * log(d) + 10**p*f * log(10).
4960 l = len(str(c))
4961 f = e+l - (e+l >= 1)
4962
4963 # compute approximation to 10**p*log(d), with error < 27
4964 if p > 0:
4965 k = e+p-f
4966 if k >= 0:
4967 c *= 10**k
4968 else:
4969 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4970
4971 # _ilog magnifies existing error in c by a factor of at most 10
4972 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4973 else:
4974 # p <= 0: just approximate the whole thing by 0; error < 2.31
4975 log_d = 0
4976
4977 # compute approximation to 10**p*f*log(10), with error < 17
4978 if f:
4979 sign_f = [-1, 1][f > 0]
4980 if p >= 0:
4981 M = 10**p * abs(f)
4982 else:
4983 M = _div_nearest(abs(f), 10**-p) # M = 10**p*|f|, error <= 0.5
4984
4985 if M:
4986 f_log_ten = sign_f*_ilog(10*M, M) # M*log(10), error <= 1.2 + 15 < 17
4987 else:
4988 f_log_ten = 0
4989 else:
4990 f_log_ten = 0
4991
4992 # error in sum < 17+27 = 44; error after division < 0.44 + 0.5 < 1
4993 return _div_nearest(f_log_ten + log_d, 100)
4994
4995def _iexp(x, M, L=8):
4996 """Given integers x and M, M > 0, such that x/M is small in absolute
4997 value, compute an integer approximation to M*exp(x/M). For 0 <=
4998 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4999 is usually much smaller)."""
5000
5001 # Algorithm: to compute exp(z) for a real number z, first divide z
5002 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5003 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5004 # series
5005 #
5006 # expm1(x) = x + x**2/2! + x**3/3! + ...
5007 #
5008 # Now use the identity
5009 #
5010 # expm1(2x) = expm1(x)*(expm1(x)+2)
5011 #
5012 # R times to compute the sequence expm1(z/2**R),
5013 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5014
5015 # Find R such that x/2**R/M <= 2**-L
5016 R = _nbits((long(x)<<L)//M)
5017
5018 # Taylor series. (2**L)**T > M
5019 T = -int(-10*len(str(M))//(3*L))
5020 y = _div_nearest(x, T)
5021 Mshift = long(M)<<R
5022 for i in xrange(T-1, 0, -1):
5023 y = _div_nearest(x*(Mshift + y), Mshift * i)
5024
5025 # Expansion
5026 for k in xrange(R-1, -1, -1):
5027 Mshift = long(M)<<(k+2)
5028 y = _div_nearest(y*(y+Mshift), Mshift)
5029
5030 return M+y
5031
5032def _dexp(c, e, p):
5033 """Compute an approximation to exp(c*10**e), with p decimal places of
5034 precision.
5035
5036 Returns d, f such that:
5037
5038 10**(p-1) <= d <= 10**p, and
5039 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5040
5041 In other words, d*10**f is an approximation to exp(c*10**e) with p
5042 digits of precision, and with an error in d of at most 1. This is
5043 almost, but not quite, the same as the error being < 1ulp: when d
5044 = 10**(p-1) the error could be up to 10 ulp."""
5045
5046 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5047 p += 2
5048
5049 # compute log10 with extra precision = adjusted exponent of c*10**e
5050 extra = max(0, e + len(str(c)) - 1)
5051 q = p + extra
5052 log10 = _dlog(10, 0, q) # error <= 1
5053
5054 # compute quotient c*10**e/(log10/10**q) = c*10**(e+q)/log10,
5055 # rounding down
5056 shift = e+q
5057 if shift >= 0:
5058 cshift = c*10**shift
5059 else:
5060 cshift = c//10**-shift
5061 quot, rem = divmod(cshift, log10)
5062
5063 # reduce remainder back to original precision
5064 rem = _div_nearest(rem, 10**extra)
5065
5066 # error in result of _iexp < 120; error after division < 0.62
5067 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5068
5069def _dpower(xc, xe, yc, ye, p):
5070 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5071 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5072
5073 10**(p-1) <= c <= 10**p, and
5074 (c-1)*10**e < x**y < (c+1)*10**e
5075
5076 in other words, c*10**e is an approximation to x**y with p digits
5077 of precision, and with an error in c of at most 1. (This is
5078 almost, but not quite, the same as the error being < 1ulp: when c
5079 == 10**(p-1) we can only guarantee error < 10ulp.)
5080
5081 We assume that: x is positive and not equal to 1, and y is nonzero.
5082 """
5083
5084 # Find b such that 10**(b-1) <= |y| <= 10**b
5085 b = len(str(abs(yc))) + ye
5086
5087 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5088 lxc = _dlog(xc, xe, p+b+1)
5089
5090 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5091 shift = ye-b
5092 if shift >= 0:
5093 pc = lxc*yc*10**shift
5094 else:
5095 pc = _div_nearest(lxc*yc, 10**-shift)
5096
5097 if pc == 0:
5098 # we prefer a result that isn't exactly 1; this makes it
5099 # easier to compute a correctly rounded result in __pow__
5100 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5101 coeff, exp = 10**(p-1)+1, 1-p
5102 else:
5103 coeff, exp = 10**p-1, -p
5104 else:
5105 coeff, exp = _dexp(pc, -(p+1), p+1)
5106 coeff = _div_nearest(coeff, 10)
5107 exp += 1
5108
5109 return coeff, exp
5110
5111def _log10_lb(c, correction = {
5112 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5113 '6': 23, '7': 16, '8': 10, '9': 5}):
5114 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5115 if c <= 0:
5116 raise ValueError("The argument to _log10_lb should be nonnegative.")
5117 str_c = str(c)
5118 return 100*len(str_c) - correction[str_c[0]]
5119
Facundo Batista59c58842007-04-10 12:58:45 +00005120##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005121
Facundo Batista353750c2007-09-13 18:13:15 +00005122def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005123 """Convert other to Decimal.
5124
5125 Verifies that it's ok to use in an implicit construction.
5126 """
5127 if isinstance(other, Decimal):
5128 return other
5129 if isinstance(other, (int, long)):
5130 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005131 if raiseit:
5132 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005133 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005134
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005135_infinity_map = {
5136 'inf' : 1,
5137 'infinity' : 1,
5138 '+inf' : 1,
5139 '+infinity' : 1,
5140 '-inf' : -1,
5141 '-infinity' : -1
5142}
5143
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005144def _isinfinity(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005145 """Determines whether a string or float is infinity.
5146
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005147 +1 for negative infinity; 0 for finite ; +1 for positive infinity
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005148 """
5149 num = str(num).lower()
5150 return _infinity_map.get(num, 0)
5151
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005152def _isnan(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005153 """Determines whether a string or float is NaN
5154
5155 (1, sign, diagnostic info as string) => NaN
5156 (2, sign, diagnostic info as string) => sNaN
5157 0 => not a NaN
5158 """
5159 num = str(num).lower()
5160 if not num:
5161 return 0
5162
Facundo Batista59c58842007-04-10 12:58:45 +00005163 # Get the sign, get rid of trailing [+-]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005164 sign = 0
5165 if num[0] == '+':
5166 num = num[1:]
Facundo Batista59c58842007-04-10 12:58:45 +00005167 elif num[0] == '-': # elif avoids '+-nan'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005168 num = num[1:]
5169 sign = 1
5170
5171 if num.startswith('nan'):
Facundo Batista59c58842007-04-10 12:58:45 +00005172 if len(num) > 3 and not num[3:].isdigit(): # diagnostic info
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005173 return 0
5174 return (1, sign, num[3:].lstrip('0'))
5175 if num.startswith('snan'):
5176 if len(num) > 4 and not num[4:].isdigit():
5177 return 0
5178 return (2, sign, num[4:].lstrip('0'))
5179 return 0
5180
5181
Facundo Batista59c58842007-04-10 12:58:45 +00005182##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005183
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005184# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005185# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005186
5187DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005188 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005189 traps=[DivisionByZero, Overflow, InvalidOperation],
5190 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005191 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005192 Emax=999999999,
5193 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005194 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005195)
5196
5197# Pre-made alternate contexts offered by the specification
5198# Don't change these; the user should be able to select these
5199# contexts and be able to reproduce results from other implementations
5200# of the spec.
5201
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005202BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005203 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005204 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5205 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005206)
5207
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005208ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005209 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005210 traps=[],
5211 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005212)
5213
5214
Facundo Batista59c58842007-04-10 12:58:45 +00005215##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005216
Facundo Batista59c58842007-04-10 12:58:45 +00005217# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005218Inf = Decimal('Inf')
5219negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005220NaN = Decimal('NaN')
5221Dec_0 = Decimal(0)
5222Dec_p1 = Decimal(1)
5223Dec_n1 = Decimal(-1)
5224Dec_p2 = Decimal(2)
5225Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005226
Facundo Batista59c58842007-04-10 12:58:45 +00005227# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005228Infsign = (Inf, negInf)
5229
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005230
Facundo Batista59c58842007-04-10 12:58:45 +00005231##### crud for parsing strings #############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005232import re
5233
5234# There's an optional sign at the start, and an optional exponent
5235# at the end. The exponent has an optional sign and at least one
5236# digit. In between, must have either at least one digit followed
5237# by an optional fraction, or a decimal point followed by at least
5238# one digit. Yuck.
5239
5240_parser = re.compile(r"""
5241# \s*
5242 (?P<sign>[-+])?
5243 (
5244 (?P<int>\d+) (\. (?P<frac>\d*))?
5245 |
5246 \. (?P<onlyfrac>\d+)
5247 )
5248 ([eE](?P<exp>[-+]? \d+))?
5249# \s*
5250 $
Facundo Batista59c58842007-04-10 12:58:45 +00005251""", re.VERBOSE).match # Uncomment the \s* to allow leading or trailing spaces.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005252
5253del re
5254
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005255def _string2exact(s):
Facundo Batista59c58842007-04-10 12:58:45 +00005256 """Return sign, n, p s.t.
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00005257
Facundo Batista59c58842007-04-10 12:58:45 +00005258 Float string value == -1**sign * n * 10**p exactly
5259 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005260 m = _parser(s)
5261 if m is None:
5262 raise ValueError("invalid literal for Decimal: %r" % s)
5263
5264 if m.group('sign') == "-":
5265 sign = 1
5266 else:
5267 sign = 0
5268
5269 exp = m.group('exp')
5270 if exp is None:
5271 exp = 0
5272 else:
5273 exp = int(exp)
5274
5275 intpart = m.group('int')
5276 if intpart is None:
5277 intpart = ""
5278 fracpart = m.group('onlyfrac')
5279 else:
5280 fracpart = m.group('frac')
5281 if fracpart is None:
5282 fracpart = ""
5283
5284 exp -= len(fracpart)
5285
5286 mantissa = intpart + fracpart
5287 tmp = map(int, mantissa)
5288 backup = tmp
5289 while tmp and tmp[0] == 0:
5290 del tmp[0]
5291
5292 # It's a zero
5293 if not tmp:
5294 if backup:
5295 return (sign, tuple(backup), exp)
5296 return (sign, (0,), exp)
5297 mantissa = tuple(tmp)
5298
5299 return (sign, mantissa, exp)
5300
5301
5302if __name__ == '__main__':
5303 import doctest, sys
5304 doctest.testmod(sys.modules[__name__])