blob: 6ca8bab3fe2bcabdca916ab455359fc64042f88e [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
Facundo Batistacce8df22007-09-18 16:53:18 +0000247 def handle(self, context, sign, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000248 return Infsign[sign]
249
250class DivisionImpossible(InvalidOperation):
251 """Cannot perform the division adequately.
252
253 This occurs and signals invalid-operation if the integer result of a
254 divide-integer or remainder operation had too many digits (would be
Facundo Batista59c58842007-04-10 12:58:45 +0000255 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000256 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000257
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000258 def handle(self, context, *args):
Facundo Batistacce8df22007-09-18 16:53:18 +0000259 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000260
261class DivisionUndefined(InvalidOperation, ZeroDivisionError):
262 """Undefined result of division.
263
264 This occurs and signals invalid-operation if division by zero was
265 attempted (during a divide-integer, divide, or remainder operation), and
Facundo Batista59c58842007-04-10 12:58:45 +0000266 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000267 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000268
Facundo Batistacce8df22007-09-18 16:53:18 +0000269 def handle(self, context, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000270 return NaN
271
272class Inexact(DecimalException):
273 """Had to round, losing information.
274
275 This occurs and signals inexact whenever the result of an operation is
276 not exact (that is, it needed to be rounded and any discarded digits
Facundo Batista59c58842007-04-10 12:58:45 +0000277 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000278 result in all cases is unchanged.
279
280 The inexact signal may be tested (or trapped) to determine if a given
281 operation (or sequence of operations) was inexact.
282 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000283 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000284
285class InvalidContext(InvalidOperation):
286 """Invalid context. Unknown rounding, for example.
287
288 This occurs and signals invalid-operation if an invalid context was
Facundo Batista59c58842007-04-10 12:58:45 +0000289 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000290 on creation and either the precision exceeds the capability of the
291 underlying concrete representation or an unknown or unsupported rounding
Facundo Batista59c58842007-04-10 12:58:45 +0000292 was specified. These aspects of the context need only be checked when
293 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000294 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000295
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000296 def handle(self, context, *args):
297 return NaN
298
299class Rounded(DecimalException):
300 """Number got rounded (not necessarily changed during rounding).
301
302 This occurs and signals rounded whenever the result of an operation is
303 rounded (that is, some zero or non-zero digits were discarded from the
Facundo Batista59c58842007-04-10 12:58:45 +0000304 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000305 result in all cases is unchanged.
306
307 The rounded signal may be tested (or trapped) to determine if a given
308 operation (or sequence of operations) caused a loss of precision.
309 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000310 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000311
312class Subnormal(DecimalException):
313 """Exponent < Emin before rounding.
314
315 This occurs and signals subnormal whenever the result of a conversion or
316 operation is subnormal (that is, its adjusted exponent is less than
Facundo Batista59c58842007-04-10 12:58:45 +0000317 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000318
319 The subnormal signal may be tested (or trapped) to determine if a given
320 or operation (or sequence of operations) yielded a subnormal result.
321 """
322 pass
323
324class Overflow(Inexact, Rounded):
325 """Numerical overflow.
326
327 This occurs and signals overflow if the adjusted exponent of a result
328 (from a conversion or from an operation that is not an attempt to divide
329 by zero), after rounding, would be greater than the largest value that
330 can be handled by the implementation (the value Emax).
331
332 The result depends on the rounding mode:
333
334 For round-half-up and round-half-even (and for round-half-down and
335 round-up, if implemented), the result of the operation is [sign,inf],
Facundo Batista59c58842007-04-10 12:58:45 +0000336 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 result is the largest finite number that can be represented in the
Facundo Batista59c58842007-04-10 12:58:45 +0000338 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000339 round-ceiling, the result is the same as for round-down if the sign of
Facundo Batista59c58842007-04-10 12:58:45 +0000340 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000341 the result is the same as for round-down if the sign of the intermediate
Facundo Batista59c58842007-04-10 12:58:45 +0000342 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000343 will also be raised.
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000344 """
345
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000346 def handle(self, context, sign, *args):
347 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Facundo Batista353750c2007-09-13 18:13:15 +0000348 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000349 return Infsign[sign]
350 if sign == 0:
351 if context.rounding == ROUND_CEILING:
352 return Infsign[sign]
353 return Decimal((sign, (9,)*context.prec,
354 context.Emax-context.prec+1))
355 if sign == 1:
356 if context.rounding == ROUND_FLOOR:
357 return Infsign[sign]
358 return Decimal( (sign, (9,)*context.prec,
359 context.Emax-context.prec+1))
360
361
362class Underflow(Inexact, Rounded, Subnormal):
363 """Numerical underflow with result rounded to 0.
364
365 This occurs and signals underflow if a result is inexact and the
366 adjusted exponent of the result would be smaller (more negative) than
367 the smallest value that can be handled by the implementation (the value
Facundo Batista59c58842007-04-10 12:58:45 +0000368 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000369
370 The result after an underflow will be a subnormal number rounded, if
Facundo Batista59c58842007-04-10 12:58:45 +0000371 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000372 in 0 with the sign of the intermediate result and an exponent of Etiny.
373
374 In all cases, Inexact, Rounded, and Subnormal will also be raised.
375 """
376
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000377# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000378_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000379 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000380
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000381# Map conditions (per the spec) to signals
382_condition_map = {ConversionSyntax:InvalidOperation,
383 DivisionImpossible:InvalidOperation,
384 DivisionUndefined:InvalidOperation,
385 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000386
Facundo Batista59c58842007-04-10 12:58:45 +0000387##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000388
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000389# The getcontext() and setcontext() function manage access to a thread-local
390# current context. Py2.4 offers direct support for thread locals. If that
391# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000392# work for older Pythons. If threads are not part of the build, create a
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000393# mock threading object with threading.local() returning the module namespace.
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000394
395try:
396 import threading
397except ImportError:
398 # Python was compiled without threads; create a mock object instead
399 import sys
Facundo Batista59c58842007-04-10 12:58:45 +0000400 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000401 def local(self, sys=sys):
402 return sys.modules[__name__]
403 threading = MockThreading()
404 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000405
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000406try:
407 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000408
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000409except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000410
Facundo Batista59c58842007-04-10 12:58:45 +0000411 # To fix reloading, force it to create a new context
412 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000413 if hasattr(threading.currentThread(), '__decimal_context__'):
414 del threading.currentThread().__decimal_context__
415
416 def setcontext(context):
417 """Set this thread's context to context."""
418 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000419 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000420 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000421 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000422
423 def getcontext():
424 """Returns this thread's context.
425
426 If this thread does not yet have a context, returns
427 a new context and sets this thread's context.
428 New contexts are copies of DefaultContext.
429 """
430 try:
431 return threading.currentThread().__decimal_context__
432 except AttributeError:
433 context = Context()
434 threading.currentThread().__decimal_context__ = context
435 return context
436
437else:
438
439 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000440 if hasattr(local, '__decimal_context__'):
441 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000442
443 def getcontext(_local=local):
444 """Returns this thread's context.
445
446 If this thread does not yet have a context, returns
447 a new context and sets this thread's context.
448 New contexts are copies of DefaultContext.
449 """
450 try:
451 return _local.__decimal_context__
452 except AttributeError:
453 context = Context()
454 _local.__decimal_context__ = context
455 return context
456
457 def setcontext(context, _local=local):
458 """Set this thread's context to context."""
459 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000460 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000461 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000462 _local.__decimal_context__ = context
463
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000464 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000465
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000466def localcontext(ctx=None):
467 """Return a context manager for a copy of the supplied context
468
469 Uses a copy of the current context if no context is specified
470 The returned context manager creates a local decimal context
471 in a with statement:
472 def sin(x):
473 with localcontext() as ctx:
474 ctx.prec += 2
475 # Rest of sin calculation algorithm
476 # uses a precision 2 greater than normal
Facundo Batista59c58842007-04-10 12:58:45 +0000477 return +s # Convert result to normal precision
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000478
479 def sin(x):
480 with localcontext(ExtendedContext):
481 # Rest of sin calculation algorithm
482 # uses the Extended Context from the
483 # General Decimal Arithmetic Specification
Facundo Batista59c58842007-04-10 12:58:45 +0000484 return +s # Convert result to normal context
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000485
486 """
Neal Norwitz681d8672006-09-02 18:51:34 +0000487 # The string below can't be included in the docstring until Python 2.6
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000488 # as the doctest module doesn't understand __future__ statements
489 """
490 >>> from __future__ import with_statement
491 >>> print getcontext().prec
492 28
493 >>> with localcontext():
494 ... ctx = getcontext()
Raymond Hettinger495df472007-02-08 01:42:35 +0000495 ... ctx.prec += 2
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000496 ... print ctx.prec
497 ...
498 30
499 >>> with localcontext(ExtendedContext):
500 ... print getcontext().prec
501 ...
502 9
503 >>> print getcontext().prec
504 28
505 """
Nick Coghlanced12182006-09-02 03:54:17 +0000506 if ctx is None: ctx = getcontext()
507 return _ContextManager(ctx)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000508
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000509
Facundo Batista59c58842007-04-10 12:58:45 +0000510##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000511
512class Decimal(object):
513 """Floating point class for decimal arithmetic."""
514
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000515 __slots__ = ('_exp','_int','_sign', '_is_special')
516 # Generally, the value of the Decimal instance is given by
517 # (-1)**_sign * _int * 10**_exp
518 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000519
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000520 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000521 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000522 """Create a decimal point instance.
523
524 >>> Decimal('3.14') # string input
525 Decimal("3.14")
Facundo Batista59c58842007-04-10 12:58:45 +0000526 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000527 Decimal("3.14")
528 >>> Decimal(314) # int or long
529 Decimal("314")
530 >>> Decimal(Decimal(314)) # another decimal instance
531 Decimal("314")
532 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000533
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000534 self = object.__new__(cls)
535 self._is_special = False
536
537 # From an internal working value
538 if isinstance(value, _WorkRep):
Raymond Hettinger17931de2004-10-27 06:21:46 +0000539 self._sign = value.sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000540 self._int = tuple(map(int, str(value.int)))
541 self._exp = int(value.exp)
542 return self
543
544 # From another decimal
545 if isinstance(value, Decimal):
546 self._exp = value._exp
547 self._sign = value._sign
548 self._int = value._int
549 self._is_special = value._is_special
550 return self
551
552 # From an integer
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000553 if isinstance(value, (int,long)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000554 if value >= 0:
555 self._sign = 0
556 else:
557 self._sign = 1
558 self._exp = 0
559 self._int = tuple(map(int, str(abs(value))))
560 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000561
562 # tuple/list conversion (possibly from as_tuple())
563 if isinstance(value, (list,tuple)):
564 if len(value) != 3:
Facundo Batista59c58842007-04-10 12:58:45 +0000565 raise ValueError('Invalid arguments')
Raymond Hettingerdbecd932005-02-06 06:57:08 +0000566 if value[0] not in (0,1):
Facundo Batista59c58842007-04-10 12:58:45 +0000567 raise ValueError('Invalid sign')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000568 for digit in value[1]:
569 if not isinstance(digit, (int,long)) or digit < 0:
Facundo Batista353750c2007-09-13 18:13:15 +0000570 raise ValueError("The second value in the tuple must be "
Facundo Batista59c58842007-04-10 12:58:45 +0000571 "composed of non negative integer elements.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000572 self._sign = value[0]
573 self._int = tuple(value[1])
574 if value[2] in ('F','n','N'):
575 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000576 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000577 else:
578 self._exp = int(value[2])
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000579 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000580
Raymond Hettingerbf440692004-07-10 14:14:37 +0000581 if isinstance(value, float):
582 raise TypeError("Cannot convert float to Decimal. " +
583 "First convert the float to a string")
584
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000585 # Other argument types may require the context during interpretation
586 if context is None:
587 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000588
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000589 # From a string
590 # REs insist on real strings, so we can too.
591 if isinstance(value, basestring):
592 if _isinfinity(value):
593 self._exp = 'F'
594 self._int = (0,)
595 self._is_special = True
596 if _isinfinity(value) == 1:
597 self._sign = 0
598 else:
599 self._sign = 1
600 return self
601 if _isnan(value):
602 sig, sign, diag = _isnan(value)
603 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000604 if sig == 1:
Facundo Batista59c58842007-04-10 12:58:45 +0000605 self._exp = 'n' # qNaN
606 else: # sig == 2
607 self._exp = 'N' # sNaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000608 self._sign = sign
Facundo Batista59c58842007-04-10 12:58:45 +0000609 self._int = tuple(map(int, diag)) # Diagnostic info
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000610 return self
611 try:
612 self._sign, self._int, self._exp = _string2exact(value)
613 except ValueError:
614 self._is_special = True
Facundo Batista353750c2007-09-13 18:13:15 +0000615 return context._raise_error(ConversionSyntax,
616 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000617 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000618
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000619 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000620
621 def _isnan(self):
622 """Returns whether the number is not actually one.
623
624 0 if a number
Facundo Batista353750c2007-09-13 18:13:15 +0000625 1 if NaN (it could be a normal quiet NaN or a phantom one)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000626 2 if sNaN
627 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000628 if self._is_special:
629 exp = self._exp
630 if exp == 'n':
631 return 1
632 elif exp == 'N':
633 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000634 return 0
635
636 def _isinfinity(self):
637 """Returns whether the number is infinite
638
639 0 if finite or not a number
640 1 if +INF
641 -1 if -INF
642 """
643 if self._exp == 'F':
644 if self._sign:
645 return -1
646 return 1
647 return 0
648
Facundo Batista353750c2007-09-13 18:13:15 +0000649 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000650 """Returns whether the number is not actually one.
651
652 if self, other are sNaN, signal
653 if self, other are NaN return nan
654 return 0
655
656 Done before operations.
657 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000658
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000659 self_is_nan = self._isnan()
660 if other is None:
661 other_is_nan = False
662 else:
663 other_is_nan = other._isnan()
664
665 if self_is_nan or other_is_nan:
666 if context is None:
667 context = getcontext()
668
669 if self_is_nan == 2:
670 return context._raise_error(InvalidOperation, 'sNaN',
671 1, self)
672 if other_is_nan == 2:
673 return context._raise_error(InvalidOperation, 'sNaN',
674 1, other)
675 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000676 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000677
Facundo Batista353750c2007-09-13 18:13:15 +0000678 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000679 return 0
680
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000681 def __nonzero__(self):
682 """Is the number non-zero?
683
684 0 if self == 0
685 1 if self != 0
686 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000687 if self._is_special:
Facundo Batista353750c2007-09-13 18:13:15 +0000688 return True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000689 return sum(self._int) != 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000690
Facundo Batista353750c2007-09-13 18:13:15 +0000691 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000692 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000693 if other is NotImplemented:
Facundo Batista353750c2007-09-13 18:13:15 +0000694 # Never return NotImplemented
695 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000696
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000697 if self._is_special or other._is_special:
Facundo Batista353750c2007-09-13 18:13:15 +0000698 # check for nans, without raising on a signaling nan
699 if self._isnan() or other._isnan():
Facundo Batista59c58842007-04-10 12:58:45 +0000700 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000701
702 # INF = INF
703 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000704
Facundo Batista353750c2007-09-13 18:13:15 +0000705 # check for zeros; note that cmp(0, -0) should return 0
706 if not self:
707 if not other:
708 return 0
709 else:
710 return -((-1)**other._sign)
711 if not other:
712 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000713
Facundo Batista59c58842007-04-10 12:58:45 +0000714 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000715 if other._sign < self._sign:
716 return -1
717 if self._sign < other._sign:
718 return 1
719
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000720 self_adjusted = self.adjusted()
721 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000722 if self_adjusted == other_adjusted:
723 self_padded = self._int + (0,)*(self._exp - other._exp)
724 other_padded = other._int + (0,)*(other._exp - self._exp)
725 return cmp(self_padded, other_padded) * (-1)**self._sign
726 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000727 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000728 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000729 return -((-1)**self._sign)
730
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000731 def __eq__(self, other):
732 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000733 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000734 return self.__cmp__(other) == 0
735
736 def __ne__(self, other):
737 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000738 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000739 return self.__cmp__(other) != 0
740
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000741 def compare(self, other, context=None):
742 """Compares one to another.
743
744 -1 => a < b
745 0 => a = b
746 1 => a > b
747 NaN => one is NaN
748 Like __cmp__, but returns Decimal instances.
749 """
Facundo Batista353750c2007-09-13 18:13:15 +0000750 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000751
Facundo Batista59c58842007-04-10 12:58:45 +0000752 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000753 if (self._is_special or other and other._is_special):
754 ans = self._check_nans(other, context)
755 if ans:
756 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000757
Facundo Batista353750c2007-09-13 18:13:15 +0000758 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000759
760 def __hash__(self):
761 """x.__hash__() <==> hash(x)"""
762 # Decimal integers must hash the same as the ints
763 # Non-integer decimals are normalized and hashed as strings
Georg Brandl1fb9f522006-05-11 19:57:09 +0000764 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000765 if self._is_special:
766 if self._isnan():
767 raise TypeError('Cannot hash a NaN value.')
768 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000769 if not self:
770 return 0
771 if self._isinteger():
772 op = _WorkRep(self.to_integral_value())
773 # to make computation feasible for Decimals with large
774 # exponent, we use the fact that hash(n) == hash(m) for
775 # any two nonzero integers n and m such that (i) n and m
776 # have the same sign, and (ii) n is congruent to m modulo
777 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
778 # hash((-1)**s*c*pow(10, e, 2**64-1).
779 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000780 return hash(str(self.normalize()))
781
782 def as_tuple(self):
783 """Represents the number as a triple tuple.
784
785 To show the internals exactly as they are.
786 """
787 return (self._sign, self._int, self._exp)
788
789 def __repr__(self):
790 """Represents the number as an instance of Decimal."""
791 # Invariant: eval(repr(d)) == d
792 return 'Decimal("%s")' % str(self)
793
Facundo Batista353750c2007-09-13 18:13:15 +0000794 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000795 """Return string representation of the number in scientific notation.
796
797 Captures all of the information in the underlying representation.
798 """
799
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000800 if self._is_special:
801 if self._isnan():
802 minus = '-'*self._sign
803 if self._int == (0,):
804 info = ''
805 else:
806 info = ''.join(map(str, self._int))
807 if self._isnan() == 2:
808 return minus + 'sNaN' + info
809 return minus + 'NaN' + info
810 if self._isinfinity():
811 minus = '-'*self._sign
812 return minus + 'Infinity'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000813
814 if context is None:
815 context = getcontext()
816
817 tmp = map(str, self._int)
818 numdigits = len(self._int)
819 leftdigits = self._exp + numdigits
Facundo Batista59c58842007-04-10 12:58:45 +0000820 if eng and not self: # self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
821 if self._exp < 0 and self._exp >= -6: # short, no need for e/E
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000822 s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
823 return s
Facundo Batista59c58842007-04-10 12:58:45 +0000824 # exp is closest mult. of 3 >= self._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000825 exp = ((self._exp - 1)// 3 + 1) * 3
826 if exp != self._exp:
827 s = '0.'+'0'*(exp - self._exp)
828 else:
829 s = '0'
830 if exp != 0:
831 if context.capitals:
832 s += 'E'
833 else:
834 s += 'e'
835 if exp > 0:
Facundo Batista59c58842007-04-10 12:58:45 +0000836 s += '+' # 0.0e+3, not 0.0e3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000837 s += str(exp)
838 s = '-'*self._sign + s
839 return s
840 if eng:
841 dotplace = (leftdigits-1)%3+1
842 adjexp = leftdigits -1 - (leftdigits-1)%3
843 else:
844 adjexp = leftdigits-1
845 dotplace = 1
846 if self._exp == 0:
847 pass
848 elif self._exp < 0 and adjexp >= 0:
849 tmp.insert(leftdigits, '.')
850 elif self._exp < 0 and adjexp >= -6:
851 tmp[0:0] = ['0'] * int(-leftdigits)
852 tmp.insert(0, '0.')
853 else:
854 if numdigits > dotplace:
855 tmp.insert(dotplace, '.')
856 elif numdigits < dotplace:
857 tmp.extend(['0']*(dotplace-numdigits))
858 if adjexp:
859 if not context.capitals:
860 tmp.append('e')
861 else:
862 tmp.append('E')
863 if adjexp > 0:
864 tmp.append('+')
865 tmp.append(str(adjexp))
866 if eng:
867 while tmp[0:1] == ['0']:
868 tmp[0:1] = []
869 if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
870 tmp[0:0] = ['0']
871 if self._sign:
872 tmp.insert(0, '-')
873
874 return ''.join(tmp)
875
876 def to_eng_string(self, context=None):
877 """Convert to engineering-type string.
878
879 Engineering notation has an exponent which is a multiple of 3, so there
880 are up to 3 digits left of the decimal place.
881
882 Same rules for when in exponential and when as a value as in __str__.
883 """
Facundo Batista353750c2007-09-13 18:13:15 +0000884 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000885
886 def __neg__(self, context=None):
887 """Returns a copy with the sign switched.
888
889 Rounds, if it has reason.
890 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000891 if self._is_special:
892 ans = self._check_nans(context=context)
893 if ans:
894 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000895
896 if not self:
897 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +0000898 ans = self.copy_sign(Dec_0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000899 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000900 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000901
902 if context is None:
903 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000904 if context._rounding_decision == ALWAYS_ROUND:
Facundo Batista353750c2007-09-13 18:13:15 +0000905 return ans._fix(context)
906 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000907
908 def __pos__(self, context=None):
909 """Returns a copy, unless it is a sNaN.
910
911 Rounds the number (if more then precision digits)
912 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000913 if self._is_special:
914 ans = self._check_nans(context=context)
915 if ans:
916 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000917
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000918 if not self:
919 # + (-0) = 0
Facundo Batista353750c2007-09-13 18:13:15 +0000920 ans = self.copy_sign(Dec_0)
921 else:
922 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000923
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000924 if context is None:
925 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000926 if context._rounding_decision == ALWAYS_ROUND:
Facundo Batista353750c2007-09-13 18:13:15 +0000927 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000928 return ans
929
930 def __abs__(self, round=1, context=None):
931 """Returns the absolute value of self.
932
933 If the second argument is 0, do not round.
934 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000935 if self._is_special:
936 ans = self._check_nans(context=context)
937 if ans:
938 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000939
940 if not round:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000941 if context is None:
942 context = getcontext()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000943 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000944 context._set_rounding_decision(NEVER_ROUND)
945
946 if self._sign:
947 ans = self.__neg__(context=context)
948 else:
949 ans = self.__pos__(context=context)
950
951 return ans
952
953 def __add__(self, other, context=None):
954 """Returns self + other.
955
956 -INF + INF (or the reverse) cause InvalidOperation errors.
957 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000958 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000959 if other is NotImplemented:
960 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000961
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000962 if context is None:
963 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000964
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000965 if self._is_special or other._is_special:
966 ans = self._check_nans(other, context)
967 if ans:
968 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000969
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000970 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000971 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000972 if self._sign != other._sign and other._isinfinity():
973 return context._raise_error(InvalidOperation, '-INF + INF')
974 return Decimal(self)
975 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000976 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000977
978 shouldround = context._rounding_decision == ALWAYS_ROUND
979
980 exp = min(self._exp, other._exp)
981 negativezero = 0
982 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +0000983 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000984 negativezero = 1
985
986 if not self and not other:
987 sign = min(self._sign, other._sign)
988 if negativezero:
989 sign = 1
Facundo Batista353750c2007-09-13 18:13:15 +0000990 ans = Decimal( (sign, (0,), exp))
991 if shouldround:
992 ans = ans._fix(context)
993 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000994 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +0000995 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +0000996 ans = other._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000997 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000998 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000999 return ans
1000 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001001 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001002 ans = self._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001003 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001004 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001005 return ans
1006
1007 op1 = _WorkRep(self)
1008 op2 = _WorkRep(other)
1009 op1, op2 = _normalize(op1, op2, shouldround, context.prec)
1010
1011 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001012 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001013 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001014 if op1.int == op2.int:
Facundo Batista353750c2007-09-13 18:13:15 +00001015 ans = Decimal((negativezero, (0,), exp))
1016 if shouldround:
1017 ans = ans._fix(context)
1018 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001019 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001020 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001021 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001022 if op1.sign == 1:
1023 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001024 op1.sign, op2.sign = op2.sign, op1.sign
1025 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001026 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001027 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001028 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001029 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001030 op1.sign, op2.sign = (0, 0)
1031 else:
1032 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001033 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001034
Raymond Hettinger17931de2004-10-27 06:21:46 +00001035 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001036 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001037 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001038 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001039
1040 result.exp = op1.exp
1041 ans = Decimal(result)
1042 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001043 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001044 return ans
1045
1046 __radd__ = __add__
1047
1048 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001049 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001050 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001051 if other is NotImplemented:
1052 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001053
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001054 if self._is_special or other._is_special:
1055 ans = self._check_nans(other, context=context)
1056 if ans:
1057 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001058
Facundo Batista353750c2007-09-13 18:13:15 +00001059 # self - other is computed as self + other.copy_negate()
1060 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001061
1062 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001063 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001064 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001065 if other is NotImplemented:
1066 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001067
Facundo Batista353750c2007-09-13 18:13:15 +00001068 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001069
Facundo Batista353750c2007-09-13 18:13:15 +00001070 def _increment(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001071 """Special case of add, adding 1eExponent
1072
1073 Since it is common, (rounding, for example) this adds
1074 (sign)*one E self._exp to the number more efficiently than add.
1075
Facundo Batista353750c2007-09-13 18:13:15 +00001076 Assumes that self is nonspecial.
1077
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001078 For example:
1079 Decimal('5.624e10')._increment() == Decimal('5.625e10')
1080 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081 L = list(self._int)
1082 L[-1] += 1
1083 spot = len(L)-1
1084 while L[spot] == 10:
1085 L[spot] = 0
1086 if spot == 0:
1087 L[0:0] = [1]
1088 break
1089 L[spot-1] += 1
1090 spot -= 1
Facundo Batista353750c2007-09-13 18:13:15 +00001091 return Decimal((self._sign, L, self._exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001092
1093 def __mul__(self, other, context=None):
1094 """Return self * other.
1095
1096 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1097 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001098 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001099 if other is NotImplemented:
1100 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001101
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001102 if context is None:
1103 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001104
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001105 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001106
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001107 if self._is_special or other._is_special:
1108 ans = self._check_nans(other, context)
1109 if ans:
1110 return ans
1111
1112 if self._isinfinity():
1113 if not other:
1114 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1115 return Infsign[resultsign]
1116
1117 if other._isinfinity():
1118 if not self:
1119 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1120 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001121
1122 resultexp = self._exp + other._exp
1123 shouldround = context._rounding_decision == ALWAYS_ROUND
1124
1125 # Special case for multiplying by zero
1126 if not self or not other:
1127 ans = Decimal((resultsign, (0,), resultexp))
1128 if shouldround:
Facundo Batista59c58842007-04-10 12:58:45 +00001129 # Fixing in case the exponent is out of bounds
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001130 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001131 return ans
1132
1133 # Special case for multiplying by power of 10
1134 if self._int == (1,):
1135 ans = Decimal((resultsign, other._int, resultexp))
1136 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001137 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001138 return ans
1139 if other._int == (1,):
1140 ans = Decimal((resultsign, self._int, resultexp))
1141 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001142 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001143 return ans
1144
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001145 op1 = _WorkRep(self)
1146 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001147
Facundo Batista59c58842007-04-10 12:58:45 +00001148 ans = Decimal((resultsign, map(int, str(op1.int * op2.int)), resultexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001149 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001150 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001151
1152 return ans
1153 __rmul__ = __mul__
1154
1155 def __div__(self, other, context=None):
1156 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001157 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001158 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001159 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001160
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001161 if context is None:
1162 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001163
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001164 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001165
1166 if self._is_special or other._is_special:
1167 ans = self._check_nans(other, context)
1168 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001169 return ans
1170
1171 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001172 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001173
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001174 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001175 return Infsign[sign]
1176
1177 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001178 context._raise_error(Clamped, 'Division by infinity')
1179 return Decimal((sign, (0,), context.Etiny()))
1180
1181 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001182 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001183 if not self:
1184 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001185 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001186
Facundo Batistacce8df22007-09-18 16:53:18 +00001187 if not self:
1188 exp = self._exp - other._exp
1189 coeff = 0
1190 else:
1191 # OK, so neither = 0, INF or NaN
1192 shift = len(other._int) - len(self._int) + context.prec + 1
1193 exp = self._exp - other._exp - shift
1194 op1 = _WorkRep(self)
1195 op2 = _WorkRep(other)
1196 if shift >= 0:
1197 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1198 else:
1199 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1200 if remainder:
1201 # result is not exact; adjust to ensure correct rounding
1202 if coeff % 5 == 0:
1203 coeff += 1
1204 else:
1205 # result is exact; get as close to ideal exponent as possible
1206 ideal_exp = self._exp - other._exp
1207 while exp < ideal_exp and coeff % 10 == 0:
1208 coeff //= 10
1209 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001210
Facundo Batistacce8df22007-09-18 16:53:18 +00001211 ans = Decimal((sign, map(int, str(coeff)), exp))
1212 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001213
Facundo Batistacce8df22007-09-18 16:53:18 +00001214 __truediv__ = __div__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001215
Facundo Batistacce8df22007-09-18 16:53:18 +00001216 def _divide(self, other, context):
1217 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001218
Facundo Batistacce8df22007-09-18 16:53:18 +00001219 Assumes that neither self nor other is a NaN, that self is not
1220 infinite and that other is nonzero.
1221 """
1222 sign = self._sign ^ other._sign
1223 if other._isinfinity():
1224 ideal_exp = self._exp
1225 else:
1226 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001227
Facundo Batistacce8df22007-09-18 16:53:18 +00001228 expdiff = self.adjusted() - other.adjusted()
1229 if not self or other._isinfinity() or expdiff <= -2:
1230 return (Decimal((sign, (0,), 0)),
1231 self._rescale(ideal_exp, context.rounding))
1232 if expdiff <= context.prec:
1233 op1 = _WorkRep(self)
1234 op2 = _WorkRep(other)
1235 if op1.exp >= op2.exp:
1236 op1.int *= 10**(op1.exp - op2.exp)
1237 else:
1238 op2.int *= 10**(op2.exp - op1.exp)
1239 q, r = divmod(op1.int, op2.int)
1240 if q < 10**context.prec:
1241 return (Decimal((sign, map(int, str(q)), 0)),
1242 Decimal((self._sign, map(int, str(r)), ideal_exp)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001243
Facundo Batistacce8df22007-09-18 16:53:18 +00001244 # Here the quotient is too large to be representable
1245 ans = context._raise_error(DivisionImpossible,
1246 'quotient too large in //, % or divmod')
1247 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001248
1249 def __rdiv__(self, other, context=None):
1250 """Swaps self/other and returns __div__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001251 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001252 if other is NotImplemented:
1253 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001254 return other.__div__(self, context=context)
1255 __rtruediv__ = __rdiv__
1256
1257 def __divmod__(self, other, context=None):
1258 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001259 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001260 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001261 other = _convert_other(other)
1262 if other is NotImplemented:
1263 return other
1264
1265 if context is None:
1266 context = getcontext()
1267
1268 ans = self._check_nans(other, context)
1269 if ans:
1270 return (ans, ans)
1271
1272 sign = self._sign ^ other._sign
1273 if self._isinfinity():
1274 if other._isinfinity():
1275 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1276 return ans, ans
1277 else:
1278 return (Infsign[sign],
1279 context._raise_error(InvalidOperation, 'INF % x'))
1280
1281 if not other:
1282 if not self:
1283 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1284 return ans, ans
1285 else:
1286 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1287 context._raise_error(InvalidOperation, 'x % 0'))
1288
1289 quotient, remainder = self._divide(other, context)
1290 if context._rounding_decision == ALWAYS_ROUND:
1291 remainder = remainder._fix(context)
1292 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001293
1294 def __rdivmod__(self, other, context=None):
1295 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001296 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001297 if other is NotImplemented:
1298 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001299 return other.__divmod__(self, context=context)
1300
1301 def __mod__(self, other, context=None):
1302 """
1303 self % other
1304 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001305 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001306 if other is NotImplemented:
1307 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001308
Facundo Batistacce8df22007-09-18 16:53:18 +00001309 if context is None:
1310 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001311
Facundo Batistacce8df22007-09-18 16:53:18 +00001312 ans = self._check_nans(other, context)
1313 if ans:
1314 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001315
Facundo Batistacce8df22007-09-18 16:53:18 +00001316 if self._isinfinity():
1317 return context._raise_error(InvalidOperation, 'INF % x')
1318 elif not other:
1319 if self:
1320 return context._raise_error(InvalidOperation, 'x % 0')
1321 else:
1322 return context._raise_error(DivisionUndefined, '0 % 0')
1323
1324 remainder = self._divide(other, context)[1]
1325 if context._rounding_decision == ALWAYS_ROUND:
1326 remainder = remainder._fix(context)
1327 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001328
1329 def __rmod__(self, other, context=None):
1330 """Swaps self/other and returns __mod__."""
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 return other.__mod__(self, context=context)
1335
1336 def remainder_near(self, other, context=None):
1337 """
1338 Remainder nearest to 0- abs(remainder-near) <= other/2
1339 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001340 if context is None:
1341 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001342
Facundo Batista353750c2007-09-13 18:13:15 +00001343 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001344
Facundo Batista353750c2007-09-13 18:13:15 +00001345 ans = self._check_nans(other, context)
1346 if ans:
1347 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001348
Facundo Batista353750c2007-09-13 18:13:15 +00001349 # self == +/-infinity -> InvalidOperation
1350 if self._isinfinity():
1351 return context._raise_error(InvalidOperation,
1352 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001353
Facundo Batista353750c2007-09-13 18:13:15 +00001354 # other == 0 -> either InvalidOperation or DivisionUndefined
1355 if not other:
1356 if self:
1357 return context._raise_error(InvalidOperation,
1358 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001359 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001360 return context._raise_error(DivisionUndefined,
1361 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001362
Facundo Batista353750c2007-09-13 18:13:15 +00001363 # other = +/-infinity -> remainder = self
1364 if other._isinfinity():
1365 ans = Decimal(self)
1366 return ans._fix(context)
1367
1368 # self = 0 -> remainder = self, with ideal exponent
1369 ideal_exponent = min(self._exp, other._exp)
1370 if not self:
1371 ans = Decimal((self._sign, (0,), ideal_exponent))
1372 return ans._fix(context)
1373
1374 # catch most cases of large or small quotient
1375 expdiff = self.adjusted() - other.adjusted()
1376 if expdiff >= context.prec + 1:
1377 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001378 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001379 if expdiff <= -2:
1380 # expdiff <= -2 => abs(self/other) < 0.1
1381 ans = self._rescale(ideal_exponent, context.rounding)
1382 return ans._fix(context)
1383
1384 # adjust both arguments to have the same exponent, then divide
1385 op1 = _WorkRep(self)
1386 op2 = _WorkRep(other)
1387 if op1.exp >= op2.exp:
1388 op1.int *= 10**(op1.exp - op2.exp)
1389 else:
1390 op2.int *= 10**(op2.exp - op1.exp)
1391 q, r = divmod(op1.int, op2.int)
1392 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1393 # 10**ideal_exponent. Apply correction to ensure that
1394 # abs(remainder) <= abs(other)/2
1395 if 2*r + (q&1) > op2.int:
1396 r -= op2.int
1397 q += 1
1398
1399 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001400 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001401
1402 # result has same sign as self unless r is negative
1403 sign = self._sign
1404 if r < 0:
1405 sign = 1-sign
1406 r = -r
1407
1408 ans = Decimal((sign, map(int, str(r)), ideal_exponent))
1409 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001410
1411 def __floordiv__(self, other, context=None):
1412 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001413 other = _convert_other(other)
1414 if other is NotImplemented:
1415 return other
1416
1417 if context is None:
1418 context = getcontext()
1419
1420 ans = self._check_nans(other, context)
1421 if ans:
1422 return ans
1423
1424 if self._isinfinity():
1425 if other._isinfinity():
1426 return context._raise_error(InvalidOperation, 'INF // INF')
1427 else:
1428 return Infsign[self._sign ^ other._sign]
1429
1430 if not other:
1431 if self:
1432 return context._raise_error(DivisionByZero, 'x // 0',
1433 self._sign ^ other._sign)
1434 else:
1435 return context._raise_error(DivisionUndefined, '0 // 0')
1436
1437 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001438
1439 def __rfloordiv__(self, other, context=None):
1440 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001441 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001442 if other is NotImplemented:
1443 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001444 return other.__floordiv__(self, context=context)
1445
1446 def __float__(self):
1447 """Float representation."""
1448 return float(str(self))
1449
1450 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001451 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001452 if self._is_special:
1453 if self._isnan():
1454 context = getcontext()
1455 return context._raise_error(InvalidContext)
1456 elif self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001457 raise OverflowError("Cannot convert infinity to long")
Facundo Batista353750c2007-09-13 18:13:15 +00001458 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001459 if self._exp >= 0:
Facundo Batista353750c2007-09-13 18:13:15 +00001460 return s*int(''.join(map(str, self._int)))*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001461 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001462 return s*int(''.join(map(str, self._int))[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001463
1464 def __long__(self):
1465 """Converts to a long.
1466
1467 Equivalent to long(int(self))
1468 """
1469 return long(self.__int__())
1470
Facundo Batista353750c2007-09-13 18:13:15 +00001471 def _fix_nan(self, context):
1472 """Decapitate the payload of a NaN to fit the context"""
1473 payload = self._int
1474
1475 # maximum length of payload is precision if _clamp=0,
1476 # precision-1 if _clamp=1.
1477 max_payload_len = context.prec - context._clamp
1478 if len(payload) > max_payload_len:
1479 pos = len(payload)-max_payload_len
1480 while pos < len(payload) and payload[pos] == 0:
1481 pos += 1
1482 payload = payload[pos:]
1483 return Decimal((self._sign, payload, self._exp))
Facundo Batista6c398da2007-09-17 17:30:13 +00001484 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001485
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001486 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001487 """Round if it is necessary to keep self within prec precision.
1488
1489 Rounds and fixes the exponent. Does not raise on a sNaN.
1490
1491 Arguments:
1492 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001493 context - context used.
1494 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001495
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001496 if context is None:
1497 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001498
Facundo Batista353750c2007-09-13 18:13:15 +00001499 if self._is_special:
1500 if self._isnan():
1501 # decapitate payload if necessary
1502 return self._fix_nan(context)
1503 else:
1504 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001505 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001506
Facundo Batista353750c2007-09-13 18:13:15 +00001507 # if self is zero then exponent should be between Etiny and
1508 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1509 Etiny = context.Etiny()
1510 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001511 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001512 exp_max = [context.Emax, Etop][context._clamp]
1513 new_exp = min(max(self._exp, Etiny), exp_max)
1514 if new_exp != self._exp:
1515 context._raise_error(Clamped)
1516 return Decimal((self._sign, (0,), new_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001517 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001518 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001519
1520 # exp_min is the smallest allowable exponent of the result,
1521 # equal to max(self.adjusted()-context.prec+1, Etiny)
1522 exp_min = len(self._int) + self._exp - context.prec
1523 if exp_min > Etop:
1524 # overflow: exp_min > Etop iff self.adjusted() > Emax
1525 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001526 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001527 return context._raise_error(Overflow, 'above Emax', self._sign)
1528 self_is_subnormal = exp_min < Etiny
1529 if self_is_subnormal:
1530 context._raise_error(Subnormal)
1531 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001532
Facundo Batista353750c2007-09-13 18:13:15 +00001533 # round if self has too many digits
1534 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001535 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001536 ans = self._rescale(exp_min, context.rounding)
1537 if ans != self:
1538 context._raise_error(Inexact)
1539 if self_is_subnormal:
1540 context._raise_error(Underflow)
1541 if not ans:
1542 # raise Clamped on underflow to 0
1543 context._raise_error(Clamped)
1544 elif len(ans._int) == context.prec+1:
1545 # we get here only if rescaling rounds the
1546 # cofficient up to exactly 10**context.prec
1547 if ans._exp < Etop:
1548 ans = Decimal((ans._sign, ans._int[:-1], ans._exp+1))
1549 else:
1550 # Inexact and Rounded have already been raised
1551 ans = context._raise_error(Overflow, 'above Emax',
1552 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001553 return ans
1554
Facundo Batista353750c2007-09-13 18:13:15 +00001555 # fold down if _clamp == 1 and self has too few digits
1556 if context._clamp == 1 and self._exp > Etop:
1557 context._raise_error(Clamped)
1558 self_padded = self._int + (0,)*(self._exp - Etop)
1559 return Decimal((self._sign, self_padded, Etop))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001560
Facundo Batista353750c2007-09-13 18:13:15 +00001561 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001562 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001563
1564 _pick_rounding_function = {}
1565
Facundo Batista353750c2007-09-13 18:13:15 +00001566 # for each of the rounding functions below:
1567 # self is a finite, nonzero Decimal
1568 # prec is an integer satisfying 0 <= prec < len(self._int)
1569 # the rounded result will have exponent self._exp + len(self._int) - prec;
1570
1571 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001572 """Also known as round-towards-0, truncate."""
Facundo Batista353750c2007-09-13 18:13:15 +00001573 newexp = self._exp + len(self._int) - prec
1574 return Decimal((self._sign, self._int[:prec] or (0,), newexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001575
Facundo Batista353750c2007-09-13 18:13:15 +00001576 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001577 """Rounds away from 0."""
Facundo Batista353750c2007-09-13 18:13:15 +00001578 newexp = self._exp + len(self._int) - prec
1579 tmp = Decimal((self._sign, self._int[:prec] or (0,), newexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001580 for digit in self._int[prec:]:
1581 if digit != 0:
Facundo Batista353750c2007-09-13 18:13:15 +00001582 return tmp._increment()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001583 return tmp
1584
Facundo Batista353750c2007-09-13 18:13:15 +00001585 def _round_half_up(self, prec):
1586 """Rounds 5 up (away from 0)"""
1587 if self._int[prec] >= 5:
1588 return self._round_up(prec)
1589 else:
1590 return self._round_down(prec)
1591
1592 def _round_half_down(self, prec):
1593 """Round 5 down"""
1594 if self._int[prec] == 5:
1595 for digit in self._int[prec+1:]:
1596 if digit != 0:
1597 break
1598 else:
1599 return self._round_down(prec)
1600 return self._round_half_up(prec)
1601
1602 def _round_half_even(self, prec):
1603 """Round 5 to even, rest to nearest."""
1604 if prec and self._int[prec-1] & 1:
1605 return self._round_half_up(prec)
1606 else:
1607 return self._round_half_down(prec)
1608
1609 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001610 """Rounds up (not away from 0 if negative.)"""
1611 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001612 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001613 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001614 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001615
Facundo Batista353750c2007-09-13 18:13:15 +00001616 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001617 """Rounds down (not towards 0 if negative)"""
1618 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001619 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001620 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001621 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001622
Facundo Batista353750c2007-09-13 18:13:15 +00001623 def _round_05up(self, prec):
1624 """Round down unless digit prec-1 is 0 or 5."""
1625 if prec == 0 or self._int[prec-1] in (0, 5):
1626 return self._round_up(prec)
1627 else:
1628 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001629
Facundo Batista353750c2007-09-13 18:13:15 +00001630 def fma(self, other, third, context=None):
1631 """Fused multiply-add.
1632
1633 Returns self*other+third with no rounding of the intermediate
1634 product self*other.
1635
1636 self and other are multiplied together, with no rounding of
1637 the result. The third operand is then added to the result,
1638 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001639 """
Facundo Batista353750c2007-09-13 18:13:15 +00001640
1641 other = _convert_other(other, raiseit=True)
1642 third = _convert_other(third, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001643
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001644 if context is None:
1645 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001646
Facundo Batista353750c2007-09-13 18:13:15 +00001647 # do self*other in fresh context with no traps and no rounding
1648 mul_context = Context(traps=[], flags=[],
1649 _rounding_decision=NEVER_ROUND)
1650 product = self.__mul__(other, mul_context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001651
Facundo Batista353750c2007-09-13 18:13:15 +00001652 if mul_context.flags[InvalidOperation]:
1653 # reraise in current context
1654 return context._raise_error(InvalidOperation,
1655 'invalid multiplication in fma',
1656 1, product)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001657
Facundo Batista353750c2007-09-13 18:13:15 +00001658 ans = product.__add__(third, context)
1659 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001660
Facundo Batista353750c2007-09-13 18:13:15 +00001661 def _power_modulo(self, other, modulo, context=None):
1662 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001663
Facundo Batista353750c2007-09-13 18:13:15 +00001664 # if can't convert other and modulo to Decimal, raise
1665 # TypeError; there's no point returning NotImplemented (no
1666 # equivalent of __rpow__ for three argument pow)
1667 other = _convert_other(other, raiseit=True)
1668 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001669
Facundo Batista353750c2007-09-13 18:13:15 +00001670 if context is None:
1671 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001672
Facundo Batista353750c2007-09-13 18:13:15 +00001673 # deal with NaNs: if there are any sNaNs then first one wins,
1674 # (i.e. behaviour for NaNs is identical to that of fma)
1675 self_is_nan = self._isnan()
1676 other_is_nan = other._isnan()
1677 modulo_is_nan = modulo._isnan()
1678 if self_is_nan or other_is_nan or modulo_is_nan:
1679 if self_is_nan == 2:
1680 return context._raise_error(InvalidOperation, 'sNaN',
1681 1, self)
1682 if other_is_nan == 2:
1683 return context._raise_error(InvalidOperation, 'sNaN',
1684 1, other)
1685 if modulo_is_nan == 2:
1686 return context._raise_error(InvalidOperation, 'sNaN',
1687 1, modulo)
1688 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001689 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001690 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001691 return other._fix_nan(context)
1692 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001693
Facundo Batista353750c2007-09-13 18:13:15 +00001694 # check inputs: we apply same restrictions as Python's pow()
1695 if not (self._isinteger() and
1696 other._isinteger() and
1697 modulo._isinteger()):
1698 return context._raise_error(InvalidOperation,
1699 'pow() 3rd argument not allowed '
1700 'unless all arguments are integers')
1701 if other < 0:
1702 return context._raise_error(InvalidOperation,
1703 'pow() 2nd argument cannot be '
1704 'negative when 3rd argument specified')
1705 if not modulo:
1706 return context._raise_error(InvalidOperation,
1707 'pow() 3rd argument cannot be 0')
1708
1709 # additional restriction for decimal: the modulus must be less
1710 # than 10**prec in absolute value
1711 if modulo.adjusted() >= context.prec:
1712 return context._raise_error(InvalidOperation,
1713 'insufficient precision: pow() 3rd '
1714 'argument must not have more than '
1715 'precision digits')
1716
1717 # define 0**0 == NaN, for consistency with two-argument pow
1718 # (even though it hurts!)
1719 if not other and not self:
1720 return context._raise_error(InvalidOperation,
1721 'at least one of pow() 1st argument '
1722 'and 2nd argument must be nonzero ;'
1723 '0**0 is not defined')
1724
1725 # compute sign of result
1726 if other._iseven():
1727 sign = 0
1728 else:
1729 sign = self._sign
1730
1731 # convert modulo to a Python integer, and self and other to
1732 # Decimal integers (i.e. force their exponents to be >= 0)
1733 modulo = abs(int(modulo))
1734 base = _WorkRep(self.to_integral_value())
1735 exponent = _WorkRep(other.to_integral_value())
1736
1737 # compute result using integer pow()
1738 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1739 for i in xrange(exponent.exp):
1740 base = pow(base, 10, modulo)
1741 base = pow(base, exponent.int, modulo)
1742
1743 return Decimal((sign, map(int, str(base)), 0))
1744
1745 def _power_exact(self, other, p):
1746 """Attempt to compute self**other exactly.
1747
1748 Given Decimals self and other and an integer p, attempt to
1749 compute an exact result for the power self**other, with p
1750 digits of precision. Return None if self**other is not
1751 exactly representable in p digits.
1752
1753 Assumes that elimination of special cases has already been
1754 performed: self and other must both be nonspecial; self must
1755 be positive and not numerically equal to 1; other must be
1756 nonzero. For efficiency, other._exp should not be too large,
1757 so that 10**abs(other._exp) is a feasible calculation."""
1758
1759 # In the comments below, we write x for the value of self and
1760 # y for the value of other. Write x = xc*10**xe and y =
1761 # yc*10**ye.
1762
1763 # The main purpose of this method is to identify the *failure*
1764 # of x**y to be exactly representable with as little effort as
1765 # possible. So we look for cheap and easy tests that
1766 # eliminate the possibility of x**y being exact. Only if all
1767 # these tests are passed do we go on to actually compute x**y.
1768
1769 # Here's the main idea. First normalize both x and y. We
1770 # express y as a rational m/n, with m and n relatively prime
1771 # and n>0. Then for x**y to be exactly representable (at
1772 # *any* precision), xc must be the nth power of a positive
1773 # integer and xe must be divisible by n. If m is negative
1774 # then additionally xc must be a power of either 2 or 5, hence
1775 # a power of 2**n or 5**n.
1776 #
1777 # There's a limit to how small |y| can be: if y=m/n as above
1778 # then:
1779 #
1780 # (1) if xc != 1 then for the result to be representable we
1781 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1782 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1783 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1784 # representable.
1785 #
1786 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1787 # |y| < 1/|xe| then the result is not representable.
1788 #
1789 # Note that since x is not equal to 1, at least one of (1) and
1790 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1791 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1792 #
1793 # There's also a limit to how large y can be, at least if it's
1794 # positive: the normalized result will have coefficient xc**y,
1795 # so if it's representable then xc**y < 10**p, and y <
1796 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1797 # not exactly representable.
1798
1799 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1800 # so |y| < 1/xe and the result is not representable.
1801 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1802 # < 1/nbits(xc).
1803
1804 x = _WorkRep(self)
1805 xc, xe = x.int, x.exp
1806 while xc % 10 == 0:
1807 xc //= 10
1808 xe += 1
1809
1810 y = _WorkRep(other)
1811 yc, ye = y.int, y.exp
1812 while yc % 10 == 0:
1813 yc //= 10
1814 ye += 1
1815
1816 # case where xc == 1: result is 10**(xe*y), with xe*y
1817 # required to be an integer
1818 if xc == 1:
1819 if ye >= 0:
1820 exponent = xe*yc*10**ye
1821 else:
1822 exponent, remainder = divmod(xe*yc, 10**-ye)
1823 if remainder:
1824 return None
1825 if y.sign == 1:
1826 exponent = -exponent
1827 # if other is a nonnegative integer, use ideal exponent
1828 if other._isinteger() and other._sign == 0:
1829 ideal_exponent = self._exp*int(other)
1830 zeros = min(exponent-ideal_exponent, p-1)
1831 else:
1832 zeros = 0
1833 return Decimal((0, (1,) + (0,)*zeros, exponent-zeros))
1834
1835 # case where y is negative: xc must be either a power
1836 # of 2 or a power of 5.
1837 if y.sign == 1:
1838 last_digit = xc % 10
1839 if last_digit in (2,4,6,8):
1840 # quick test for power of 2
1841 if xc & -xc != xc:
1842 return None
1843 # now xc is a power of 2; e is its exponent
1844 e = _nbits(xc)-1
1845 # find e*y and xe*y; both must be integers
1846 if ye >= 0:
1847 y_as_int = yc*10**ye
1848 e = e*y_as_int
1849 xe = xe*y_as_int
1850 else:
1851 ten_pow = 10**-ye
1852 e, remainder = divmod(e*yc, ten_pow)
1853 if remainder:
1854 return None
1855 xe, remainder = divmod(xe*yc, ten_pow)
1856 if remainder:
1857 return None
1858
1859 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1860 return None
1861 xc = 5**e
1862
1863 elif last_digit == 5:
1864 # e >= log_5(xc) if xc is a power of 5; we have
1865 # equality all the way up to xc=5**2658
1866 e = _nbits(xc)*28//65
1867 xc, remainder = divmod(5**e, xc)
1868 if remainder:
1869 return None
1870 while xc % 5 == 0:
1871 xc //= 5
1872 e -= 1
1873 if ye >= 0:
1874 y_as_integer = yc*10**ye
1875 e = e*y_as_integer
1876 xe = xe*y_as_integer
1877 else:
1878 ten_pow = 10**-ye
1879 e, remainder = divmod(e*yc, ten_pow)
1880 if remainder:
1881 return None
1882 xe, remainder = divmod(xe*yc, ten_pow)
1883 if remainder:
1884 return None
1885 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1886 return None
1887 xc = 2**e
1888 else:
1889 return None
1890
1891 if xc >= 10**p:
1892 return None
1893 xe = -e-xe
1894 return Decimal((0, map(int, str(xc)), xe))
1895
1896 # now y is positive; find m and n such that y = m/n
1897 if ye >= 0:
1898 m, n = yc*10**ye, 1
1899 else:
1900 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1901 return None
1902 xc_bits = _nbits(xc)
1903 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1904 return None
1905 m, n = yc, 10**(-ye)
1906 while m % 2 == n % 2 == 0:
1907 m //= 2
1908 n //= 2
1909 while m % 5 == n % 5 == 0:
1910 m //= 5
1911 n //= 5
1912
1913 # compute nth root of xc*10**xe
1914 if n > 1:
1915 # if 1 < xc < 2**n then xc isn't an nth power
1916 if xc != 1 and xc_bits <= n:
1917 return None
1918
1919 xe, rem = divmod(xe, n)
1920 if rem != 0:
1921 return None
1922
1923 # compute nth root of xc using Newton's method
1924 a = 1L << -(-_nbits(xc)//n) # initial estimate
1925 while True:
1926 q, r = divmod(xc, a**(n-1))
1927 if a <= q:
1928 break
1929 else:
1930 a = (a*(n-1) + q)//n
1931 if not (a == q and r == 0):
1932 return None
1933 xc = a
1934
1935 # now xc*10**xe is the nth root of the original xc*10**xe
1936 # compute mth power of xc*10**xe
1937
1938 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1939 # 10**p and the result is not representable.
1940 if xc > 1 and m > p*100//_log10_lb(xc):
1941 return None
1942 xc = xc**m
1943 xe *= m
1944 if xc > 10**p:
1945 return None
1946
1947 # by this point the result *is* exactly representable
1948 # adjust the exponent to get as close as possible to the ideal
1949 # exponent, if necessary
1950 str_xc = str(xc)
1951 if other._isinteger() and other._sign == 0:
1952 ideal_exponent = self._exp*int(other)
1953 zeros = min(xe-ideal_exponent, p-len(str_xc))
1954 else:
1955 zeros = 0
1956 return Decimal((0, map(int, str_xc)+[0,]*zeros, xe-zeros))
1957
1958 def __pow__(self, other, modulo=None, context=None):
1959 """Return self ** other [ % modulo].
1960
1961 With two arguments, compute self**other.
1962
1963 With three arguments, compute (self**other) % modulo. For the
1964 three argument form, the following restrictions on the
1965 arguments hold:
1966
1967 - all three arguments must be integral
1968 - other must be nonnegative
1969 - either self or other (or both) must be nonzero
1970 - modulo must be nonzero and must have at most p digits,
1971 where p is the context precision.
1972
1973 If any of these restrictions is violated the InvalidOperation
1974 flag is raised.
1975
1976 The result of pow(self, other, modulo) is identical to the
1977 result that would be obtained by computing (self**other) %
1978 modulo with unbounded precision, but is computed more
1979 efficiently. It is always exact.
1980 """
1981
1982 if modulo is not None:
1983 return self._power_modulo(other, modulo, context)
1984
1985 other = _convert_other(other)
1986 if other is NotImplemented:
1987 return other
1988
1989 if context is None:
1990 context = getcontext()
1991
1992 # either argument is a NaN => result is NaN
1993 ans = self._check_nans(other, context)
1994 if ans:
1995 return ans
1996
1997 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1998 if not other:
1999 if not self:
2000 return context._raise_error(InvalidOperation, '0 ** 0')
2001 else:
2002 return Dec_p1
2003
2004 # result has sign 1 iff self._sign is 1 and other is an odd integer
2005 result_sign = 0
2006 if self._sign == 1:
2007 if other._isinteger():
2008 if not other._iseven():
2009 result_sign = 1
2010 else:
2011 # -ve**noninteger = NaN
2012 # (-0)**noninteger = 0**noninteger
2013 if self:
2014 return context._raise_error(InvalidOperation,
2015 'x ** y with x negative and y not an integer')
2016 # negate self, without doing any unwanted rounding
2017 self = Decimal((0, self._int, self._exp))
2018
2019 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2020 if not self:
2021 if other._sign == 0:
2022 return Decimal((result_sign, (0,), 0))
2023 else:
2024 return Infsign[result_sign]
2025
2026 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002027 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002028 if other._sign == 0:
2029 return Infsign[result_sign]
2030 else:
2031 return Decimal((result_sign, (0,), 0))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002032
Facundo Batista353750c2007-09-13 18:13:15 +00002033 # 1**other = 1, but the choice of exponent and the flags
2034 # depend on the exponent of self, and on whether other is a
2035 # positive integer, a negative integer, or neither
2036 if self == Dec_p1:
2037 if other._isinteger():
2038 # exp = max(self._exp*max(int(other), 0),
2039 # 1-context.prec) but evaluating int(other) directly
2040 # is dangerous until we know other is small (other
2041 # could be 1e999999999)
2042 if other._sign == 1:
2043 multiplier = 0
2044 elif other > context.prec:
2045 multiplier = context.prec
2046 else:
2047 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002048
Facundo Batista353750c2007-09-13 18:13:15 +00002049 exp = self._exp * multiplier
2050 if exp < 1-context.prec:
2051 exp = 1-context.prec
2052 context._raise_error(Rounded)
2053 else:
2054 context._raise_error(Inexact)
2055 context._raise_error(Rounded)
2056 exp = 1-context.prec
2057
2058 return Decimal((result_sign, (1,)+(0,)*-exp, exp))
2059
2060 # compute adjusted exponent of self
2061 self_adj = self.adjusted()
2062
2063 # self ** infinity is infinity if self > 1, 0 if self < 1
2064 # self ** -infinity is infinity if self < 1, 0 if self > 1
2065 if other._isinfinity():
2066 if (other._sign == 0) == (self_adj < 0):
2067 return Decimal((result_sign, (0,), 0))
2068 else:
2069 return Infsign[result_sign]
2070
2071 # from here on, the result always goes through the call
2072 # to _fix at the end of this function.
2073 ans = None
2074
2075 # crude test to catch cases of extreme overflow/underflow. If
2076 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2077 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2078 # self**other >= 10**(Emax+1), so overflow occurs. The test
2079 # for underflow is similar.
2080 bound = self._log10_exp_bound() + other.adjusted()
2081 if (self_adj >= 0) == (other._sign == 0):
2082 # self > 1 and other +ve, or self < 1 and other -ve
2083 # possibility of overflow
2084 if bound >= len(str(context.Emax)):
2085 ans = Decimal((result_sign, (1,), context.Emax+1))
2086 else:
2087 # self > 1 and other -ve, or self < 1 and other +ve
2088 # possibility of underflow to 0
2089 Etiny = context.Etiny()
2090 if bound >= len(str(-Etiny)):
2091 ans = Decimal((result_sign, (1,), Etiny-1))
2092
2093 # try for an exact result with precision +1
2094 if ans is None:
2095 ans = self._power_exact(other, context.prec + 1)
2096 if ans is not None and result_sign == 1:
2097 ans = Decimal((1, ans._int, ans._exp))
2098
2099 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2100 if ans is None:
2101 p = context.prec
2102 x = _WorkRep(self)
2103 xc, xe = x.int, x.exp
2104 y = _WorkRep(other)
2105 yc, ye = y.int, y.exp
2106 if y.sign == 1:
2107 yc = -yc
2108
2109 # compute correctly rounded result: start with precision +3,
2110 # then increase precision until result is unambiguously roundable
2111 extra = 3
2112 while True:
2113 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2114 if coeff % (5*10**(len(str(coeff))-p-1)):
2115 break
2116 extra += 3
2117
2118 ans = Decimal((result_sign, map(int, str(coeff)), exp))
2119
2120 # the specification says that for non-integer other we need to
2121 # raise Inexact, even when the result is actually exact. In
2122 # the same way, we need to raise Underflow here if the result
2123 # is subnormal. (The call to _fix will take care of raising
2124 # Rounded and Subnormal, as usual.)
2125 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002126 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002127 # pad with zeros up to length context.prec+1 if necessary
2128 if len(ans._int) <= context.prec:
2129 expdiff = context.prec+1 - len(ans._int)
2130 ans = Decimal((ans._sign, ans._int+(0,)*expdiff, ans._exp-expdiff))
2131 if ans.adjusted() < context.Emin:
2132 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002133
Facundo Batista353750c2007-09-13 18:13:15 +00002134 # unlike exp, ln and log10, the power function respects the
2135 # rounding mode; no need to use ROUND_HALF_EVEN here
2136 ans = ans._fix(context)
2137 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002138
2139 def __rpow__(self, other, context=None):
2140 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002141 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002142 if other is NotImplemented:
2143 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002144 return other.__pow__(self, context=context)
2145
2146 def normalize(self, context=None):
2147 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002148
Facundo Batista353750c2007-09-13 18:13:15 +00002149 if context is None:
2150 context = getcontext()
2151
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002152 if self._is_special:
2153 ans = self._check_nans(context=context)
2154 if ans:
2155 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002156
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002157 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002158 if dup._isinfinity():
2159 return dup
2160
2161 if not dup:
2162 return Decimal( (dup._sign, (0,), 0) )
Facundo Batista353750c2007-09-13 18:13:15 +00002163 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002164 end = len(dup._int)
2165 exp = dup._exp
Facundo Batista353750c2007-09-13 18:13:15 +00002166 while dup._int[end-1] == 0 and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002167 exp += 1
2168 end -= 1
2169 return Decimal( (dup._sign, dup._int[:end], exp) )
2170
Facundo Batistabd2fe832007-09-13 18:42:09 +00002171 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002172 """Quantize self so its exponent is the same as that of exp.
2173
2174 Similar to self._rescale(exp._exp) but with error checking.
2175 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002176 exp = _convert_other(exp, raiseit=True)
2177
Facundo Batista353750c2007-09-13 18:13:15 +00002178 if context is None:
2179 context = getcontext()
2180 if rounding is None:
2181 rounding = context.rounding
2182
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002183 if self._is_special or exp._is_special:
2184 ans = self._check_nans(exp, context)
2185 if ans:
2186 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002187
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002188 if exp._isinfinity() or self._isinfinity():
2189 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002190 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002191 return context._raise_error(InvalidOperation,
2192 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002193
Facundo Batistabd2fe832007-09-13 18:42:09 +00002194 # if we're not watching exponents, do a simple rescale
2195 if not watchexp:
2196 ans = self._rescale(exp._exp, rounding)
2197 # raise Inexact and Rounded where appropriate
2198 if ans._exp > self._exp:
2199 context._raise_error(Rounded)
2200 if ans != self:
2201 context._raise_error(Inexact)
2202 return ans
2203
Facundo Batista353750c2007-09-13 18:13:15 +00002204 # exp._exp should be between Etiny and Emax
2205 if not (context.Etiny() <= exp._exp <= context.Emax):
2206 return context._raise_error(InvalidOperation,
2207 'target exponent out of bounds in quantize')
2208
2209 if not self:
2210 ans = Decimal((self._sign, (0,), exp._exp))
2211 return ans._fix(context)
2212
2213 self_adjusted = self.adjusted()
2214 if self_adjusted > context.Emax:
2215 return context._raise_error(InvalidOperation,
2216 'exponent of quantize result too large for current context')
2217 if self_adjusted - exp._exp + 1 > context.prec:
2218 return context._raise_error(InvalidOperation,
2219 'quantize result has too many digits for current context')
2220
2221 ans = self._rescale(exp._exp, rounding)
2222 if ans.adjusted() > context.Emax:
2223 return context._raise_error(InvalidOperation,
2224 'exponent of quantize result too large for current context')
2225 if len(ans._int) > context.prec:
2226 return context._raise_error(InvalidOperation,
2227 'quantize result has too many digits for current context')
2228
2229 # raise appropriate flags
2230 if ans._exp > self._exp:
2231 context._raise_error(Rounded)
2232 if ans != self:
2233 context._raise_error(Inexact)
2234 if ans and ans.adjusted() < context.Emin:
2235 context._raise_error(Subnormal)
2236
2237 # call to fix takes care of any necessary folddown
2238 ans = ans._fix(context)
2239 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002240
2241 def same_quantum(self, other):
2242 """Test whether self and other have the same exponent.
2243
2244 same as self._exp == other._exp, except NaN == sNaN
2245 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002246 if self._is_special or other._is_special:
2247 if self._isnan() or other._isnan():
2248 return self._isnan() and other._isnan() and True
2249 if self._isinfinity() or other._isinfinity():
2250 return self._isinfinity() and other._isinfinity() and True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002251 return self._exp == other._exp
2252
Facundo Batista353750c2007-09-13 18:13:15 +00002253 def _rescale(self, exp, rounding):
2254 """Rescale self so that the exponent is exp, either by padding with zeros
2255 or by truncating digits, using the given rounding mode.
2256
2257 Specials are returned without change. This operation is
2258 quiet: it raises no flags, and uses no information from the
2259 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002260
2261 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002262 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002263 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002264 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002265 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002266 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002267 return Decimal((self._sign, (0,), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002268
Facundo Batista353750c2007-09-13 18:13:15 +00002269 if self._exp >= exp:
2270 # pad answer with zeros if necessary
2271 return Decimal((self._sign, self._int + (0,)*(self._exp - exp), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002272
Facundo Batista353750c2007-09-13 18:13:15 +00002273 # too many digits; round and lose data. If self.adjusted() <
2274 # exp-1, replace self by 10**(exp-1) before rounding
2275 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002276 if digits < 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002277 self = Decimal((self._sign, (1,), exp-1))
2278 digits = 0
2279 this_function = getattr(self, self._pick_rounding_function[rounding])
2280 return this_function(digits)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002281
Facundo Batista353750c2007-09-13 18:13:15 +00002282 def to_integral_exact(self, rounding=None, context=None):
2283 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002284
Facundo Batista353750c2007-09-13 18:13:15 +00002285 If no rounding mode is specified, take the rounding mode from
2286 the context. This method raises the Rounded and Inexact flags
2287 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002288
Facundo Batista353750c2007-09-13 18:13:15 +00002289 See also: to_integral_value, which does exactly the same as
2290 this method except that it doesn't raise Inexact or Rounded.
2291 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002292 if self._is_special:
2293 ans = self._check_nans(context=context)
2294 if ans:
2295 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002296 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002297 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002298 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002299 if not self:
2300 return Decimal((self._sign, (0,), 0))
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002301 if context is None:
2302 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002303 if rounding is None:
2304 rounding = context.rounding
2305 context._raise_error(Rounded)
2306 ans = self._rescale(0, rounding)
2307 if ans != self:
2308 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002309 return ans
2310
Facundo Batista353750c2007-09-13 18:13:15 +00002311 def to_integral_value(self, rounding=None, context=None):
2312 """Rounds to the nearest integer, without raising inexact, rounded."""
2313 if context is None:
2314 context = getcontext()
2315 if rounding is None:
2316 rounding = context.rounding
2317 if self._is_special:
2318 ans = self._check_nans(context=context)
2319 if ans:
2320 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002321 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002322 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002323 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002324 else:
2325 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002326
Facundo Batista353750c2007-09-13 18:13:15 +00002327 # the method name changed, but we provide also the old one, for compatibility
2328 to_integral = to_integral_value
2329
2330 def sqrt(self, context=None):
2331 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002332 if self._is_special:
2333 ans = self._check_nans(context=context)
2334 if ans:
2335 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002336
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002337 if self._isinfinity() and self._sign == 0:
2338 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002339
2340 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002341 # exponent = self._exp // 2. sqrt(-0) = -0
2342 ans = Decimal((self._sign, (0,), self._exp // 2))
2343 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002344
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002345 if context is None:
2346 context = getcontext()
2347
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002348 if self._sign == 1:
2349 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2350
Facundo Batista353750c2007-09-13 18:13:15 +00002351 # At this point self represents a positive number. Let p be
2352 # the desired precision and express self in the form c*100**e
2353 # with c a positive real number and e an integer, c and e
2354 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2355 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2356 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2357 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2358 # the closest integer to sqrt(c) with the even integer chosen
2359 # in the case of a tie.
2360 #
2361 # To ensure correct rounding in all cases, we use the
2362 # following trick: we compute the square root to an extra
2363 # place (precision p+1 instead of precision p), rounding down.
2364 # Then, if the result is inexact and its last digit is 0 or 5,
2365 # we increase the last digit to 1 or 6 respectively; if it's
2366 # exact we leave the last digit alone. Now the final round to
2367 # p places (or fewer in the case of underflow) will round
2368 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002369
Facundo Batista353750c2007-09-13 18:13:15 +00002370 # use an extra digit of precision
2371 prec = context.prec+1
2372
2373 # write argument in the form c*100**e where e = self._exp//2
2374 # is the 'ideal' exponent, to be used if the square root is
2375 # exactly representable. l is the number of 'digits' of c in
2376 # base 100, so that 100**(l-1) <= c < 100**l.
2377 op = _WorkRep(self)
2378 e = op.exp >> 1
2379 if op.exp & 1:
2380 c = op.int * 10
2381 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002382 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002383 c = op.int
2384 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002385
Facundo Batista353750c2007-09-13 18:13:15 +00002386 # rescale so that c has exactly prec base 100 'digits'
2387 shift = prec-l
2388 if shift >= 0:
2389 c *= 100**shift
2390 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002391 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002392 c, remainder = divmod(c, 100**-shift)
2393 exact = not remainder
2394 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002395
Facundo Batista353750c2007-09-13 18:13:15 +00002396 # find n = floor(sqrt(c)) using Newton's method
2397 n = 10**prec
2398 while True:
2399 q = c//n
2400 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002401 break
Facundo Batista353750c2007-09-13 18:13:15 +00002402 else:
2403 n = n + q >> 1
2404 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002405
Facundo Batista353750c2007-09-13 18:13:15 +00002406 if exact:
2407 # result is exact; rescale to use ideal exponent e
2408 if shift >= 0:
2409 # assert n % 10**shift == 0
2410 n //= 10**shift
2411 else:
2412 n *= 10**-shift
2413 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002414 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002415 # result is not exact; fix last digit as described above
2416 if n % 5 == 0:
2417 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002418
Facundo Batista353750c2007-09-13 18:13:15 +00002419 ans = Decimal((0, map(int, str(n)), e))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002420
Facundo Batista353750c2007-09-13 18:13:15 +00002421 # round, and fit to current context
2422 context = context._shallow_copy()
2423 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002424 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002425 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002426
Facundo Batista353750c2007-09-13 18:13:15 +00002427 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002428
2429 def max(self, other, context=None):
2430 """Returns the larger value.
2431
Facundo Batista353750c2007-09-13 18:13:15 +00002432 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002433 NaN (and signals if one is sNaN). Also rounds.
2434 """
Facundo Batista353750c2007-09-13 18:13:15 +00002435 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002436
Facundo Batista6c398da2007-09-17 17:30:13 +00002437 if context is None:
2438 context = getcontext()
2439
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002440 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002441 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002442 # number is always returned
2443 sn = self._isnan()
2444 on = other._isnan()
2445 if sn or on:
2446 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002447 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002448 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002449 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002450 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002451
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002452 c = self.__cmp__(other)
2453 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002454 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002455 # then an ordering is applied:
2456 #
Facundo Batista59c58842007-04-10 12:58:45 +00002457 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002458 # positive sign and min returns the operand with the negative sign
2459 #
Facundo Batista59c58842007-04-10 12:58:45 +00002460 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002461 # the result. This is exactly the ordering used in compare_total.
2462 c = self.compare_total(other)
2463
2464 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002465 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002466 else:
2467 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002468
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002469 if context._rounding_decision == ALWAYS_ROUND:
2470 return ans._fix(context)
2471 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002472
2473 def min(self, other, context=None):
2474 """Returns the smaller value.
2475
Facundo Batista59c58842007-04-10 12:58:45 +00002476 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002477 NaN (and signals if one is sNaN). Also rounds.
2478 """
Facundo Batista353750c2007-09-13 18:13:15 +00002479 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002480
Facundo Batista6c398da2007-09-17 17:30:13 +00002481 if context is None:
2482 context = getcontext()
2483
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002484 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002485 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002486 # number is always returned
2487 sn = self._isnan()
2488 on = other._isnan()
2489 if sn or on:
2490 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002491 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002492 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002493 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002494 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002495
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002496 c = self.__cmp__(other)
2497 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002498 c = self.compare_total(other)
2499
2500 if c == -1:
2501 ans = self
2502 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002503 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002504
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002505 if context._rounding_decision == ALWAYS_ROUND:
2506 return ans._fix(context)
2507 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002508
2509 def _isinteger(self):
2510 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002511 if self._is_special:
2512 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002513 if self._exp >= 0:
2514 return True
2515 rest = self._int[self._exp:]
2516 return rest == (0,)*len(rest)
2517
2518 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002519 """Returns True if self is even. Assumes self is an integer."""
2520 if not self or self._exp > 0:
2521 return True
Raymond Hettinger61992ef2004-08-06 23:42:16 +00002522 return self._int[-1+self._exp] & 1 == 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002523
2524 def adjusted(self):
2525 """Return the adjusted exponent of self"""
2526 try:
2527 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002528 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002529 except TypeError:
2530 return 0
2531
Facundo Batista353750c2007-09-13 18:13:15 +00002532 def canonical(self, context=None):
2533 """Returns the same Decimal object.
2534
2535 As we do not have different encodings for the same number, the
2536 received object already is in its canonical form.
2537 """
2538 return self
2539
2540 def compare_signal(self, other, context=None):
2541 """Compares self to the other operand numerically.
2542
2543 It's pretty much like compare(), but all NaNs signal, with signaling
2544 NaNs taking precedence over quiet NaNs.
2545 """
2546 if context is None:
2547 context = getcontext()
2548
2549 self_is_nan = self._isnan()
2550 other_is_nan = other._isnan()
2551 if self_is_nan == 2:
2552 return context._raise_error(InvalidOperation, 'sNaN',
2553 1, self)
2554 if other_is_nan == 2:
2555 return context._raise_error(InvalidOperation, 'sNaN',
2556 1, other)
2557 if self_is_nan:
2558 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2559 1, self)
2560 if other_is_nan:
2561 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2562 1, other)
2563 return self.compare(other, context=context)
2564
2565 def compare_total(self, other):
2566 """Compares self to other using the abstract representations.
2567
2568 This is not like the standard compare, which use their numerical
2569 value. Note that a total ordering is defined for all possible abstract
2570 representations.
2571 """
2572 # if one is negative and the other is positive, it's easy
2573 if self._sign and not other._sign:
2574 return Dec_n1
2575 if not self._sign and other._sign:
2576 return Dec_p1
2577 sign = self._sign
2578
2579 # let's handle both NaN types
2580 self_nan = self._isnan()
2581 other_nan = other._isnan()
2582 if self_nan or other_nan:
2583 if self_nan == other_nan:
2584 if self._int < other._int:
2585 if sign:
2586 return Dec_p1
2587 else:
2588 return Dec_n1
2589 if self._int > other._int:
2590 if sign:
2591 return Dec_n1
2592 else:
2593 return Dec_p1
2594 return Dec_0
2595
2596 if sign:
2597 if self_nan == 1:
2598 return Dec_n1
2599 if other_nan == 1:
2600 return Dec_p1
2601 if self_nan == 2:
2602 return Dec_n1
2603 if other_nan == 2:
2604 return Dec_p1
2605 else:
2606 if self_nan == 1:
2607 return Dec_p1
2608 if other_nan == 1:
2609 return Dec_n1
2610 if self_nan == 2:
2611 return Dec_p1
2612 if other_nan == 2:
2613 return Dec_n1
2614
2615 if self < other:
2616 return Dec_n1
2617 if self > other:
2618 return Dec_p1
2619
2620 if self._exp < other._exp:
2621 if sign:
2622 return Dec_p1
2623 else:
2624 return Dec_n1
2625 if self._exp > other._exp:
2626 if sign:
2627 return Dec_n1
2628 else:
2629 return Dec_p1
2630 return Dec_0
2631
2632
2633 def compare_total_mag(self, other):
2634 """Compares self to other using abstract repr., ignoring sign.
2635
2636 Like compare_total, but with operand's sign ignored and assumed to be 0.
2637 """
2638 s = self.copy_abs()
2639 o = other.copy_abs()
2640 return s.compare_total(o)
2641
2642 def copy_abs(self):
2643 """Returns a copy with the sign set to 0. """
2644 return Decimal((0, self._int, self._exp))
2645
2646 def copy_negate(self):
2647 """Returns a copy with the sign inverted."""
2648 if self._sign:
2649 return Decimal((0, self._int, self._exp))
2650 else:
2651 return Decimal((1, self._int, self._exp))
2652
2653 def copy_sign(self, other):
2654 """Returns self with the sign of other."""
2655 return Decimal((other._sign, self._int, self._exp))
2656
2657 def exp(self, context=None):
2658 """Returns e ** self."""
2659
2660 if context is None:
2661 context = getcontext()
2662
2663 # exp(NaN) = NaN
2664 ans = self._check_nans(context=context)
2665 if ans:
2666 return ans
2667
2668 # exp(-Infinity) = 0
2669 if self._isinfinity() == -1:
2670 return Dec_0
2671
2672 # exp(0) = 1
2673 if not self:
2674 return Dec_p1
2675
2676 # exp(Infinity) = Infinity
2677 if self._isinfinity() == 1:
2678 return Decimal(self)
2679
2680 # the result is now guaranteed to be inexact (the true
2681 # mathematical result is transcendental). There's no need to
2682 # raise Rounded and Inexact here---they'll always be raised as
2683 # a result of the call to _fix.
2684 p = context.prec
2685 adj = self.adjusted()
2686
2687 # we only need to do any computation for quite a small range
2688 # of adjusted exponents---for example, -29 <= adj <= 10 for
2689 # the default context. For smaller exponent the result is
2690 # indistinguishable from 1 at the given precision, while for
2691 # larger exponent the result either overflows or underflows.
2692 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2693 # overflow
2694 ans = Decimal((0, (1,), context.Emax+1))
2695 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2696 # underflow to 0
2697 ans = Decimal((0, (1,), context.Etiny()-1))
2698 elif self._sign == 0 and adj < -p:
2699 # p+1 digits; final round will raise correct flags
2700 ans = Decimal((0, (1,) + (0,)*(p-1) + (1,), -p))
2701 elif self._sign == 1 and adj < -p-1:
2702 # p+1 digits; final round will raise correct flags
2703 ans = Decimal((0, (9,)*(p+1), -p-1))
2704 # general case
2705 else:
2706 op = _WorkRep(self)
2707 c, e = op.int, op.exp
2708 if op.sign == 1:
2709 c = -c
2710
2711 # compute correctly rounded result: increase precision by
2712 # 3 digits at a time until we get an unambiguously
2713 # roundable result
2714 extra = 3
2715 while True:
2716 coeff, exp = _dexp(c, e, p+extra)
2717 if coeff % (5*10**(len(str(coeff))-p-1)):
2718 break
2719 extra += 3
2720
2721 ans = Decimal((0, map(int, str(coeff)), exp))
2722
2723 # at this stage, ans should round correctly with *any*
2724 # rounding mode, not just with ROUND_HALF_EVEN
2725 context = context._shallow_copy()
2726 rounding = context._set_rounding(ROUND_HALF_EVEN)
2727 ans = ans._fix(context)
2728 context.rounding = rounding
2729
2730 return ans
2731
2732 def is_canonical(self):
2733 """Returns 1 if self is canonical; otherwise returns 0."""
2734 return Dec_p1
2735
2736 def is_finite(self):
2737 """Returns 1 if self is finite, otherwise returns 0.
2738
2739 For it to be finite, it must be neither infinite nor a NaN.
2740 """
2741 if self._is_special:
2742 return Dec_0
2743 else:
2744 return Dec_p1
2745
2746 def is_infinite(self):
2747 """Returns 1 if self is an Infinite, otherwise returns 0."""
2748 if self._isinfinity():
2749 return Dec_p1
2750 else:
2751 return Dec_0
2752
2753 def is_nan(self):
2754 """Returns 1 if self is qNaN or sNaN, otherwise returns 0."""
2755 if self._isnan():
2756 return Dec_p1
2757 else:
2758 return Dec_0
2759
2760 def is_normal(self, context=None):
2761 """Returns 1 if self is a normal number, otherwise returns 0."""
2762 if self._is_special:
2763 return Dec_0
2764 if not self:
2765 return Dec_0
2766 if context is None:
2767 context = getcontext()
2768 if context.Emin <= self.adjusted() <= context.Emax:
2769 return Dec_p1
2770 else:
2771 return Dec_0
2772
2773 def is_qnan(self):
2774 """Returns 1 if self is a quiet NaN, otherwise returns 0."""
2775 if self._isnan() == 1:
2776 return Dec_p1
2777 else:
2778 return Dec_0
2779
2780 def is_signed(self):
2781 """Returns 1 if self is negative, otherwise returns 0."""
2782 return Decimal(self._sign)
2783
2784 def is_snan(self):
2785 """Returns 1 if self is a signaling NaN, otherwise returns 0."""
2786 if self._isnan() == 2:
2787 return Dec_p1
2788 else:
2789 return Dec_0
2790
2791 def is_subnormal(self, context=None):
2792 """Returns 1 if self is subnormal, otherwise returns 0."""
2793 if self._is_special:
2794 return Dec_0
2795 if not self:
2796 return Dec_0
2797 if context is None:
2798 context = getcontext()
2799
2800 r = self._exp + len(self._int)
2801 if r <= context.Emin:
2802 return Dec_p1
2803 return Dec_0
2804
2805 def is_zero(self):
2806 """Returns 1 if self is a zero, otherwise returns 0."""
2807 if self:
2808 return Dec_0
2809 else:
2810 return Dec_p1
2811
2812 def _ln_exp_bound(self):
2813 """Compute a lower bound for the adjusted exponent of self.ln().
2814 In other words, compute r such that self.ln() >= 10**r. Assumes
2815 that self is finite and positive and that self != 1.
2816 """
2817
2818 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2819 adj = self._exp + len(self._int) - 1
2820 if adj >= 1:
2821 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2822 return len(str(adj*23//10)) - 1
2823 if adj <= -2:
2824 # argument <= 0.1
2825 return len(str((-1-adj)*23//10)) - 1
2826 op = _WorkRep(self)
2827 c, e = op.int, op.exp
2828 if adj == 0:
2829 # 1 < self < 10
2830 num = str(c-10**-e)
2831 den = str(c)
2832 return len(num) - len(den) - (num < den)
2833 # adj == -1, 0.1 <= self < 1
2834 return e + len(str(10**-e - c)) - 1
2835
2836
2837 def ln(self, context=None):
2838 """Returns the natural (base e) logarithm of self."""
2839
2840 if context is None:
2841 context = getcontext()
2842
2843 # ln(NaN) = NaN
2844 ans = self._check_nans(context=context)
2845 if ans:
2846 return ans
2847
2848 # ln(0.0) == -Infinity
2849 if not self:
2850 return negInf
2851
2852 # ln(Infinity) = Infinity
2853 if self._isinfinity() == 1:
2854 return Inf
2855
2856 # ln(1.0) == 0.0
2857 if self == Dec_p1:
2858 return Dec_0
2859
2860 # ln(negative) raises InvalidOperation
2861 if self._sign == 1:
2862 return context._raise_error(InvalidOperation,
2863 'ln of a negative value')
2864
2865 # result is irrational, so necessarily inexact
2866 op = _WorkRep(self)
2867 c, e = op.int, op.exp
2868 p = context.prec
2869
2870 # correctly rounded result: repeatedly increase precision by 3
2871 # until we get an unambiguously roundable result
2872 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2873 while True:
2874 coeff = _dlog(c, e, places)
2875 # assert len(str(abs(coeff)))-p >= 1
2876 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2877 break
2878 places += 3
2879 ans = Decimal((int(coeff<0), map(int, str(abs(coeff))), -places))
2880
2881 context = context._shallow_copy()
2882 rounding = context._set_rounding(ROUND_HALF_EVEN)
2883 ans = ans._fix(context)
2884 context.rounding = rounding
2885 return ans
2886
2887 def _log10_exp_bound(self):
2888 """Compute a lower bound for the adjusted exponent of self.log10().
2889 In other words, find r such that self.log10() >= 10**r.
2890 Assumes that self is finite and positive and that self != 1.
2891 """
2892
2893 # For x >= 10 or x < 0.1 we only need a bound on the integer
2894 # part of log10(self), and this comes directly from the
2895 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2896 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2897 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2898
2899 adj = self._exp + len(self._int) - 1
2900 if adj >= 1:
2901 # self >= 10
2902 return len(str(adj))-1
2903 if adj <= -2:
2904 # self < 0.1
2905 return len(str(-1-adj))-1
2906 op = _WorkRep(self)
2907 c, e = op.int, op.exp
2908 if adj == 0:
2909 # 1 < self < 10
2910 num = str(c-10**-e)
2911 den = str(231*c)
2912 return len(num) - len(den) - (num < den) + 2
2913 # adj == -1, 0.1 <= self < 1
2914 num = str(10**-e-c)
2915 return len(num) + e - (num < "231") - 1
2916
2917 def log10(self, context=None):
2918 """Returns the base 10 logarithm of self."""
2919
2920 if context is None:
2921 context = getcontext()
2922
2923 # log10(NaN) = NaN
2924 ans = self._check_nans(context=context)
2925 if ans:
2926 return ans
2927
2928 # log10(0.0) == -Infinity
2929 if not self:
2930 return negInf
2931
2932 # log10(Infinity) = Infinity
2933 if self._isinfinity() == 1:
2934 return Inf
2935
2936 # log10(negative or -Infinity) raises InvalidOperation
2937 if self._sign == 1:
2938 return context._raise_error(InvalidOperation,
2939 'log10 of a negative value')
2940
2941 # log10(10**n) = n
2942 if self._int[0] == 1 and self._int[1:] == (0,)*(len(self._int) - 1):
2943 # answer may need rounding
2944 ans = Decimal(self._exp + len(self._int) - 1)
2945 else:
2946 # result is irrational, so necessarily inexact
2947 op = _WorkRep(self)
2948 c, e = op.int, op.exp
2949 p = context.prec
2950
2951 # correctly rounded result: repeatedly increase precision
2952 # until result is unambiguously roundable
2953 places = p-self._log10_exp_bound()+2
2954 while True:
2955 coeff = _dlog10(c, e, places)
2956 # assert len(str(abs(coeff)))-p >= 1
2957 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2958 break
2959 places += 3
2960 ans = Decimal((int(coeff<0), map(int, str(abs(coeff))), -places))
2961
2962 context = context._shallow_copy()
2963 rounding = context._set_rounding(ROUND_HALF_EVEN)
2964 ans = ans._fix(context)
2965 context.rounding = rounding
2966 return ans
2967
2968 def logb(self, context=None):
2969 """ Returns the exponent of the magnitude of self's MSD.
2970
2971 The result is the integer which is the exponent of the magnitude
2972 of the most significant digit of self (as though it were truncated
2973 to a single digit while maintaining the value of that digit and
2974 without limiting the resulting exponent).
2975 """
2976 # logb(NaN) = NaN
2977 ans = self._check_nans(context=context)
2978 if ans:
2979 return ans
2980
2981 if context is None:
2982 context = getcontext()
2983
2984 # logb(+/-Inf) = +Inf
2985 if self._isinfinity():
2986 return Inf
2987
2988 # logb(0) = -Inf, DivisionByZero
2989 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00002990 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00002991
2992 # otherwise, simply return the adjusted exponent of self, as a
2993 # Decimal. Note that no attempt is made to fit the result
2994 # into the current context.
2995 return Decimal(self.adjusted())
2996
2997 def _islogical(self):
2998 """Return True if self is a logical operand.
2999
3000 For being logical, it must be a finite numbers with a sign of 0,
3001 an exponent of 0, and a coefficient whose digits must all be
3002 either 0 or 1.
3003 """
3004 if self._sign != 0 or self._exp != 0:
3005 return False
3006 for dig in self._int:
3007 if dig not in (0, 1):
3008 return False
3009 return True
3010
3011 def _fill_logical(self, context, opa, opb):
3012 dif = context.prec - len(opa)
3013 if dif > 0:
3014 opa = (0,)*dif + opa
3015 elif dif < 0:
3016 opa = opa[-context.prec:]
3017 dif = context.prec - len(opb)
3018 if dif > 0:
3019 opb = (0,)*dif + opb
3020 elif dif < 0:
3021 opb = opb[-context.prec:]
3022 return opa, opb
3023
3024 def logical_and(self, other, context=None):
3025 """Applies an 'and' operation between self and other's digits."""
3026 if context is None:
3027 context = getcontext()
3028 if not self._islogical() or not other._islogical():
3029 return context._raise_error(InvalidOperation)
3030
3031 # fill to context.prec
3032 (opa, opb) = self._fill_logical(context, self._int, other._int)
3033
3034 # make the operation, and clean starting zeroes
3035 result = [a&b for a,b in zip(opa,opb)]
3036 for i,d in enumerate(result):
3037 if d == 1:
3038 break
3039 result = tuple(result[i:])
3040
3041 # if empty, we must have at least a zero
3042 if not result:
3043 result = (0,)
3044 return Decimal((0, result, 0))
3045
3046 def logical_invert(self, context=None):
3047 """Invert all its digits."""
3048 if context is None:
3049 context = getcontext()
3050 return self.logical_xor(Decimal((0,(1,)*context.prec,0)), context)
3051
3052 def logical_or(self, other, context=None):
3053 """Applies an 'or' operation between self and other's digits."""
3054 if context is None:
3055 context = getcontext()
3056 if not self._islogical() or not other._islogical():
3057 return context._raise_error(InvalidOperation)
3058
3059 # fill to context.prec
3060 (opa, opb) = self._fill_logical(context, self._int, other._int)
3061
3062 # make the operation, and clean starting zeroes
3063 result = [a|b for a,b in zip(opa,opb)]
3064 for i,d in enumerate(result):
3065 if d == 1:
3066 break
3067 result = tuple(result[i:])
3068
3069 # if empty, we must have at least a zero
3070 if not result:
3071 result = (0,)
3072 return Decimal((0, result, 0))
3073
3074 def logical_xor(self, other, context=None):
3075 """Applies an 'xor' operation between self and other's digits."""
3076 if context is None:
3077 context = getcontext()
3078 if not self._islogical() or not other._islogical():
3079 return context._raise_error(InvalidOperation)
3080
3081 # fill to context.prec
3082 (opa, opb) = self._fill_logical(context, self._int, other._int)
3083
3084 # make the operation, and clean starting zeroes
3085 result = [a^b for a,b in zip(opa,opb)]
3086 for i,d in enumerate(result):
3087 if d == 1:
3088 break
3089 result = tuple(result[i:])
3090
3091 # if empty, we must have at least a zero
3092 if not result:
3093 result = (0,)
3094 return Decimal((0, result, 0))
3095
3096 def max_mag(self, other, context=None):
3097 """Compares the values numerically with their sign ignored."""
3098 other = _convert_other(other, raiseit=True)
3099
Facundo Batista6c398da2007-09-17 17:30:13 +00003100 if context is None:
3101 context = getcontext()
3102
Facundo Batista353750c2007-09-13 18:13:15 +00003103 if self._is_special or other._is_special:
3104 # If one operand is a quiet NaN and the other is number, then the
3105 # number is always returned
3106 sn = self._isnan()
3107 on = other._isnan()
3108 if sn or on:
3109 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003110 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003111 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003112 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003113 return self._check_nans(other, context)
3114
3115 c = self.copy_abs().__cmp__(other.copy_abs())
3116 if c == 0:
3117 c = self.compare_total(other)
3118
3119 if c == -1:
3120 ans = other
3121 else:
3122 ans = self
3123
Facundo Batista353750c2007-09-13 18:13:15 +00003124 if context._rounding_decision == ALWAYS_ROUND:
3125 return ans._fix(context)
3126 return ans
3127
3128 def min_mag(self, other, context=None):
3129 """Compares the values numerically with their sign ignored."""
3130 other = _convert_other(other, raiseit=True)
3131
Facundo Batista6c398da2007-09-17 17:30:13 +00003132 if context is None:
3133 context = getcontext()
3134
Facundo Batista353750c2007-09-13 18:13:15 +00003135 if self._is_special or other._is_special:
3136 # If one operand is a quiet NaN and the other is number, then the
3137 # number is always returned
3138 sn = self._isnan()
3139 on = other._isnan()
3140 if sn or on:
3141 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003142 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003143 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003144 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003145 return self._check_nans(other, context)
3146
3147 c = self.copy_abs().__cmp__(other.copy_abs())
3148 if c == 0:
3149 c = self.compare_total(other)
3150
3151 if c == -1:
3152 ans = self
3153 else:
3154 ans = other
3155
Facundo Batista353750c2007-09-13 18:13:15 +00003156 if context._rounding_decision == ALWAYS_ROUND:
3157 return ans._fix(context)
3158 return ans
3159
3160 def next_minus(self, context=None):
3161 """Returns the largest representable number smaller than itself."""
3162 if context is None:
3163 context = getcontext()
3164
3165 ans = self._check_nans(context=context)
3166 if ans:
3167 return ans
3168
3169 if self._isinfinity() == -1:
3170 return negInf
3171 if self._isinfinity() == 1:
3172 return Decimal((0, (9,)*context.prec, context.Etop()))
3173
3174 context = context.copy()
3175 context._set_rounding(ROUND_FLOOR)
3176 context._ignore_all_flags()
3177 new_self = self._fix(context)
3178 if new_self != self:
3179 return new_self
3180 return self.__sub__(Decimal((0, (1,), context.Etiny()-1)), context)
3181
3182 def next_plus(self, context=None):
3183 """Returns the smallest representable number larger than itself."""
3184 if context is None:
3185 context = getcontext()
3186
3187 ans = self._check_nans(context=context)
3188 if ans:
3189 return ans
3190
3191 if self._isinfinity() == 1:
3192 return Inf
3193 if self._isinfinity() == -1:
3194 return Decimal((1, (9,)*context.prec, context.Etop()))
3195
3196 context = context.copy()
3197 context._set_rounding(ROUND_CEILING)
3198 context._ignore_all_flags()
3199 new_self = self._fix(context)
3200 if new_self != self:
3201 return new_self
3202 return self.__add__(Decimal((0, (1,), context.Etiny()-1)), context)
3203
3204 def next_toward(self, other, context=None):
3205 """Returns the number closest to self, in the direction towards other.
3206
3207 The result is the closest representable number to self
3208 (excluding self) that is in the direction towards other,
3209 unless both have the same value. If the two operands are
3210 numerically equal, then the result is a copy of self with the
3211 sign set to be the same as the sign of other.
3212 """
3213 other = _convert_other(other, raiseit=True)
3214
3215 if context is None:
3216 context = getcontext()
3217
3218 ans = self._check_nans(other, context)
3219 if ans:
3220 return ans
3221
3222 comparison = self.__cmp__(other)
3223 if comparison == 0:
3224 return Decimal((other._sign, self._int, self._exp))
3225
3226 if comparison == -1:
3227 ans = self.next_plus(context)
3228 else: # comparison == 1
3229 ans = self.next_minus(context)
3230
3231 # decide which flags to raise using value of ans
3232 if ans._isinfinity():
3233 context._raise_error(Overflow,
3234 'Infinite result from next_toward',
3235 ans._sign)
3236 context._raise_error(Rounded)
3237 context._raise_error(Inexact)
3238 elif ans.adjusted() < context.Emin:
3239 context._raise_error(Underflow)
3240 context._raise_error(Subnormal)
3241 context._raise_error(Rounded)
3242 context._raise_error(Inexact)
3243 # if precision == 1 then we don't raise Clamped for a
3244 # result 0E-Etiny.
3245 if not ans:
3246 context._raise_error(Clamped)
3247
3248 return ans
3249
3250 def number_class(self, context=None):
3251 """Returns an indication of the class of self.
3252
3253 The class is one of the following strings:
3254 -sNaN
3255 -NaN
3256 -Infinity
3257 -Normal
3258 -Subnormal
3259 -Zero
3260 +Zero
3261 +Subnormal
3262 +Normal
3263 +Infinity
3264 """
3265 if self.is_snan():
3266 return "sNaN"
3267 if self.is_qnan():
3268 return "NaN"
3269 inf = self._isinfinity()
3270 if inf == 1:
3271 return "+Infinity"
3272 if inf == -1:
3273 return "-Infinity"
3274 if self.is_zero():
3275 if self._sign:
3276 return "-Zero"
3277 else:
3278 return "+Zero"
3279 if context is None:
3280 context = getcontext()
3281 if self.is_subnormal(context=context):
3282 if self._sign:
3283 return "-Subnormal"
3284 else:
3285 return "+Subnormal"
3286 # just a normal, regular, boring number, :)
3287 if self._sign:
3288 return "-Normal"
3289 else:
3290 return "+Normal"
3291
3292 def radix(self):
3293 """Just returns 10, as this is Decimal, :)"""
3294 return Decimal(10)
3295
3296 def rotate(self, other, context=None):
3297 """Returns a rotated copy of self, value-of-other times."""
3298 if context is None:
3299 context = getcontext()
3300
3301 ans = self._check_nans(other, context)
3302 if ans:
3303 return ans
3304
3305 if other._exp != 0:
3306 return context._raise_error(InvalidOperation)
3307 if not (-context.prec <= int(other) <= context.prec):
3308 return context._raise_error(InvalidOperation)
3309
3310 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003311 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003312
3313 # get values, pad if necessary
3314 torot = int(other)
3315 rotdig = self._int
3316 topad = context.prec - len(rotdig)
3317 if topad:
3318 rotdig = ((0,)*topad) + rotdig
3319
3320 # let's rotate!
3321 rotated = rotdig[torot:] + rotdig[:torot]
3322
3323 # clean starting zeroes
3324 for i,d in enumerate(rotated):
3325 if d != 0:
3326 break
3327 rotated = rotated[i:]
3328
3329 return Decimal((self._sign, rotated, self._exp))
3330
3331
3332 def scaleb (self, other, context=None):
3333 """Returns self operand after adding the second value to its exp."""
3334 if context is None:
3335 context = getcontext()
3336
3337 ans = self._check_nans(other, context)
3338 if ans:
3339 return ans
3340
3341 if other._exp != 0:
3342 return context._raise_error(InvalidOperation)
3343 liminf = -2 * (context.Emax + context.prec)
3344 limsup = 2 * (context.Emax + context.prec)
3345 if not (liminf <= int(other) <= limsup):
3346 return context._raise_error(InvalidOperation)
3347
3348 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003349 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003350
3351 d = Decimal((self._sign, self._int, self._exp + int(other)))
3352 d = d._fix(context)
3353 return d
3354
3355 def shift(self, other, context=None):
3356 """Returns a shifted copy of self, value-of-other times."""
3357 if context is None:
3358 context = getcontext()
3359
3360 ans = self._check_nans(other, context)
3361 if ans:
3362 return ans
3363
3364 if other._exp != 0:
3365 return context._raise_error(InvalidOperation)
3366 if not (-context.prec <= int(other) <= context.prec):
3367 return context._raise_error(InvalidOperation)
3368
3369 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003370 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003371
3372 # get values, pad if necessary
3373 torot = int(other)
3374 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003375 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003376 rotdig = self._int
3377 topad = context.prec - len(rotdig)
3378 if topad:
3379 rotdig = ((0,)*topad) + rotdig
3380
3381 # let's shift!
3382 if torot < 0:
3383 rotated = rotdig[:torot]
3384 else:
3385 rotated = (rotdig + ((0,) * torot))
3386 rotated = rotated[-context.prec:]
3387
3388 # clean starting zeroes
3389 if rotated:
3390 for i,d in enumerate(rotated):
3391 if d != 0:
3392 break
3393 rotated = rotated[i:]
3394 else:
3395 rotated = (0,)
3396
3397 return Decimal((self._sign, rotated, self._exp))
3398
3399
Facundo Batista59c58842007-04-10 12:58:45 +00003400 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003401 def __reduce__(self):
3402 return (self.__class__, (str(self),))
3403
3404 def __copy__(self):
3405 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003406 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003407 return self.__class__(str(self))
3408
3409 def __deepcopy__(self, memo):
3410 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003411 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003412 return self.__class__(str(self))
3413
Facundo Batista59c58842007-04-10 12:58:45 +00003414##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003415
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003416
3417# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003418rounding_functions = [name for name in Decimal.__dict__.keys()
3419 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003420for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003421 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003422 globalname = name[1:].upper()
3423 val = globals()[globalname]
3424 Decimal._pick_rounding_function[val] = name
3425
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003426del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003427
Nick Coghlanced12182006-09-02 03:54:17 +00003428class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003429 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003430
Nick Coghlanced12182006-09-02 03:54:17 +00003431 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003432 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003433 """
3434 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003435 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003436 def __enter__(self):
3437 self.saved_context = getcontext()
3438 setcontext(self.new_context)
3439 return self.new_context
3440 def __exit__(self, t, v, tb):
3441 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003442
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003443class Context(object):
3444 """Contains the context for a Decimal instance.
3445
3446 Contains:
3447 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003448 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003449 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003450 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003451 raised when it is caused. Otherwise, a value is
3452 substituted in.
3453 flags - When an exception is caused, flags[exception] is incremented.
3454 (Whether or not the trap_enabler is set)
3455 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003456 Emin - Minimum exponent
3457 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003458 capitals - If 1, 1*10^1 is printed as 1E+1.
3459 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003460 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003461 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003462
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003463 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003464 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003465 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003466 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003467 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003468 _ignored_flags=None):
3469 if flags is None:
3470 flags = []
3471 if _ignored_flags is None:
3472 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003473 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003474 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003475 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003476 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003477 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003478 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003479 for name, val in locals().items():
3480 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003481 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003482 else:
3483 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003484 del self.self
3485
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003486 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003487 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003488 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003489 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3490 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3491 % vars(self))
3492 names = [f.__name__ for f, v in self.flags.items() if v]
3493 s.append('flags=[' + ', '.join(names) + ']')
3494 names = [t.__name__ for t, v in self.traps.items() if v]
3495 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003496 return ', '.join(s) + ')'
3497
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003498 def clear_flags(self):
3499 """Reset all flags to zero"""
3500 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003501 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003502
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003503 def _shallow_copy(self):
3504 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003505 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003506 self._rounding_decision, self.Emin, self.Emax,
3507 self.capitals, self._clamp, self._ignored_flags)
3508 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003509
3510 def copy(self):
3511 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003512 nc = Context(self.prec, self.rounding, self.traps.copy(),
3513 self.flags.copy(), self._rounding_decision, self.Emin,
3514 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003515 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003516 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003517
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003518 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003519 """Handles an error
3520
3521 If the flag is in _ignored_flags, returns the default response.
3522 Otherwise, it increments the flag, then, if the corresponding
3523 trap_enabler is set, it reaises the exception. Otherwise, it returns
3524 the default value after incrementing the flag.
3525 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003526 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003527 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003528 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003529 return error().handle(self, *args)
3530
3531 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003532 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003533 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003534 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003535
3536 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003537 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003538 raise error, explanation
3539
3540 def _ignore_all_flags(self):
3541 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003542 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003543
3544 def _ignore_flags(self, *flags):
3545 """Ignore the flags, if they are raised"""
3546 # Do not mutate-- This way, copies of a context leave the original
3547 # alone.
3548 self._ignored_flags = (self._ignored_flags + list(flags))
3549 return list(flags)
3550
3551 def _regard_flags(self, *flags):
3552 """Stop ignoring the flags, if they are raised"""
3553 if flags and isinstance(flags[0], (tuple,list)):
3554 flags = flags[0]
3555 for flag in flags:
3556 self._ignored_flags.remove(flag)
3557
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003558 def __hash__(self):
3559 """A Context cannot be hashed."""
3560 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003561 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003562
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003563 def Etiny(self):
3564 """Returns Etiny (= Emin - prec + 1)"""
3565 return int(self.Emin - self.prec + 1)
3566
3567 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003568 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003569 return int(self.Emax - self.prec + 1)
3570
3571 def _set_rounding_decision(self, type):
3572 """Sets the rounding decision.
3573
3574 Sets the rounding decision, and returns the current (previous)
3575 rounding decision. Often used like:
3576
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003577 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003578 # That so you don't change the calling context
3579 # if an error occurs in the middle (say DivisionImpossible is raised).
3580
3581 rounding = context._set_rounding_decision(NEVER_ROUND)
3582 instance = instance / Decimal(2)
3583 context._set_rounding_decision(rounding)
3584
3585 This will make it not round for that operation.
3586 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003587
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003588 rounding = self._rounding_decision
3589 self._rounding_decision = type
3590 return rounding
3591
3592 def _set_rounding(self, type):
3593 """Sets the rounding type.
3594
3595 Sets the rounding type, and returns the current (previous)
3596 rounding type. Often used like:
3597
3598 context = context.copy()
3599 # so you don't change the calling context
3600 # if an error occurs in the middle.
3601 rounding = context._set_rounding(ROUND_UP)
3602 val = self.__sub__(other, context=context)
3603 context._set_rounding(rounding)
3604
3605 This will make it round up for that operation.
3606 """
3607 rounding = self.rounding
3608 self.rounding= type
3609 return rounding
3610
Raymond Hettingerfed52962004-07-14 15:41:57 +00003611 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003612 """Creates a new Decimal instance but using self as context."""
3613 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003614 if d._isnan() and len(d._int) > self.prec - self._clamp:
3615 return self._raise_error(ConversionSyntax,
3616 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003617 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003618
Facundo Batista59c58842007-04-10 12:58:45 +00003619 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003620 def abs(self, a):
3621 """Returns the absolute value of the operand.
3622
3623 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003624 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003625 the plus operation on the operand.
3626
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003627 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003628 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003629 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003630 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003631 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003632 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003633 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003634 Decimal("101.5")
3635 """
3636 return a.__abs__(context=self)
3637
3638 def add(self, a, b):
3639 """Return the sum of the two operands.
3640
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003641 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003642 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003643 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003644 Decimal("1.02E+4")
3645 """
3646 return a.__add__(b, context=self)
3647
3648 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003649 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003650
Facundo Batista353750c2007-09-13 18:13:15 +00003651 def canonical(self, a):
3652 """Returns the same Decimal object.
3653
3654 As we do not have different encodings for the same number, the
3655 received object already is in its canonical form.
3656
3657 >>> ExtendedContext.canonical(Decimal('2.50'))
3658 Decimal("2.50")
3659 """
3660 return a.canonical(context=self)
3661
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003662 def compare(self, a, b):
3663 """Compares values numerically.
3664
3665 If the signs of the operands differ, a value representing each operand
3666 ('-1' if the operand is less than zero, '0' if the operand is zero or
3667 negative zero, or '1' if the operand is greater than zero) is used in
3668 place of that operand for the comparison instead of the actual
3669 operand.
3670
3671 The comparison is then effected by subtracting the second operand from
3672 the first and then returning a value according to the result of the
3673 subtraction: '-1' if the result is less than zero, '0' if the result is
3674 zero or negative zero, or '1' if the result is greater than zero.
3675
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003676 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003677 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003678 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003679 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003680 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003681 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003682 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003683 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003684 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003685 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003686 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003687 Decimal("-1")
3688 """
3689 return a.compare(b, context=self)
3690
Facundo Batista353750c2007-09-13 18:13:15 +00003691 def compare_signal(self, a, b):
3692 """Compares the values of the two operands numerically.
3693
3694 It's pretty much like compare(), but all NaNs signal, with signaling
3695 NaNs taking precedence over quiet NaNs.
3696
3697 >>> c = ExtendedContext
3698 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3699 Decimal("-1")
3700 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3701 Decimal("0")
3702 >>> c.flags[InvalidOperation] = 0
3703 >>> print c.flags[InvalidOperation]
3704 0
3705 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3706 Decimal("NaN")
3707 >>> print c.flags[InvalidOperation]
3708 1
3709 >>> c.flags[InvalidOperation] = 0
3710 >>> print c.flags[InvalidOperation]
3711 0
3712 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3713 Decimal("NaN")
3714 >>> print c.flags[InvalidOperation]
3715 1
3716 """
3717 return a.compare_signal(b, context=self)
3718
3719 def compare_total(self, a, b):
3720 """Compares two operands using their abstract representation.
3721
3722 This is not like the standard compare, which use their numerical
3723 value. Note that a total ordering is defined for all possible abstract
3724 representations.
3725
3726 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3727 Decimal("-1")
3728 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3729 Decimal("-1")
3730 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3731 Decimal("-1")
3732 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3733 Decimal("0")
3734 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3735 Decimal("1")
3736 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3737 Decimal("-1")
3738 """
3739 return a.compare_total(b)
3740
3741 def compare_total_mag(self, a, b):
3742 """Compares two operands using their abstract representation ignoring sign.
3743
3744 Like compare_total, but with operand's sign ignored and assumed to be 0.
3745 """
3746 return a.compare_total_mag(b)
3747
3748 def copy_abs(self, a):
3749 """Returns a copy of the operand with the sign set to 0.
3750
3751 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3752 Decimal("2.1")
3753 >>> ExtendedContext.copy_abs(Decimal('-100'))
3754 Decimal("100")
3755 """
3756 return a.copy_abs()
3757
3758 def copy_decimal(self, a):
3759 """Returns a copy of the decimal objet.
3760
3761 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3762 Decimal("2.1")
3763 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3764 Decimal("-1.00")
3765 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003766 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003767
3768 def copy_negate(self, a):
3769 """Returns a copy of the operand with the sign inverted.
3770
3771 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3772 Decimal("-101.5")
3773 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3774 Decimal("101.5")
3775 """
3776 return a.copy_negate()
3777
3778 def copy_sign(self, a, b):
3779 """Copies the second operand's sign to the first one.
3780
3781 In detail, it returns a copy of the first operand with the sign
3782 equal to the sign of the second operand.
3783
3784 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3785 Decimal("1.50")
3786 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3787 Decimal("1.50")
3788 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3789 Decimal("-1.50")
3790 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3791 Decimal("-1.50")
3792 """
3793 return a.copy_sign(b)
3794
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003795 def divide(self, a, b):
3796 """Decimal division in a specified context.
3797
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003798 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003799 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003800 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003801 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003802 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003803 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003804 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003805 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003806 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003807 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003808 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003809 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003810 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003811 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003812 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003813 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003814 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003815 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003816 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003817 Decimal("1.20E+6")
3818 """
3819 return a.__div__(b, context=self)
3820
3821 def divide_int(self, a, b):
3822 """Divides two numbers and returns the integer part of the result.
3823
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003824 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003825 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003826 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003827 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003828 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003829 Decimal("3")
3830 """
3831 return a.__floordiv__(b, context=self)
3832
3833 def divmod(self, a, b):
3834 return a.__divmod__(b, context=self)
3835
Facundo Batista353750c2007-09-13 18:13:15 +00003836 def exp(self, a):
3837 """Returns e ** a.
3838
3839 >>> c = ExtendedContext.copy()
3840 >>> c.Emin = -999
3841 >>> c.Emax = 999
3842 >>> c.exp(Decimal('-Infinity'))
3843 Decimal("0")
3844 >>> c.exp(Decimal('-1'))
3845 Decimal("0.367879441")
3846 >>> c.exp(Decimal('0'))
3847 Decimal("1")
3848 >>> c.exp(Decimal('1'))
3849 Decimal("2.71828183")
3850 >>> c.exp(Decimal('0.693147181'))
3851 Decimal("2.00000000")
3852 >>> c.exp(Decimal('+Infinity'))
3853 Decimal("Infinity")
3854 """
3855 return a.exp(context=self)
3856
3857 def fma(self, a, b, c):
3858 """Returns a multiplied by b, plus c.
3859
3860 The first two operands are multiplied together, using multiply,
3861 the third operand is then added to the result of that
3862 multiplication, using add, all with only one final rounding.
3863
3864 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3865 Decimal("22")
3866 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3867 Decimal("-8")
3868 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3869 Decimal("1.38435736E+12")
3870 """
3871 return a.fma(b, c, context=self)
3872
3873 def is_canonical(self, a):
3874 """Returns 1 if the operand is canonical; otherwise returns 0.
3875
3876 >>> ExtendedContext.is_canonical(Decimal('2.50'))
3877 Decimal("1")
3878 """
3879 return Dec_p1
3880
3881 def is_finite(self, a):
3882 """Returns 1 if the operand is finite, otherwise returns 0.
3883
3884 For it to be finite, it must be neither infinite nor a NaN.
3885
3886 >>> ExtendedContext.is_finite(Decimal('2.50'))
3887 Decimal("1")
3888 >>> ExtendedContext.is_finite(Decimal('-0.3'))
3889 Decimal("1")
3890 >>> ExtendedContext.is_finite(Decimal('0'))
3891 Decimal("1")
3892 >>> ExtendedContext.is_finite(Decimal('Inf'))
3893 Decimal("0")
3894 >>> ExtendedContext.is_finite(Decimal('NaN'))
3895 Decimal("0")
3896 """
3897 return a.is_finite()
3898
3899 def is_infinite(self, a):
3900 """Returns 1 if the operand is an Infinite, otherwise returns 0.
3901
3902 >>> ExtendedContext.is_infinite(Decimal('2.50'))
3903 Decimal("0")
3904 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
3905 Decimal("1")
3906 >>> ExtendedContext.is_infinite(Decimal('NaN'))
3907 Decimal("0")
3908 """
3909 return a.is_infinite()
3910
3911 def is_nan(self, a):
3912 """Returns 1 if the operand is qNaN or sNaN, otherwise returns 0.
3913
3914 >>> ExtendedContext.is_nan(Decimal('2.50'))
3915 Decimal("0")
3916 >>> ExtendedContext.is_nan(Decimal('NaN'))
3917 Decimal("1")
3918 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
3919 Decimal("1")
3920 """
3921 return a.is_nan()
3922
3923 def is_normal(self, a):
3924 """Returns 1 if the operand is a normal number, otherwise returns 0.
3925
3926 >>> c = ExtendedContext.copy()
3927 >>> c.Emin = -999
3928 >>> c.Emax = 999
3929 >>> c.is_normal(Decimal('2.50'))
3930 Decimal("1")
3931 >>> c.is_normal(Decimal('0.1E-999'))
3932 Decimal("0")
3933 >>> c.is_normal(Decimal('0.00'))
3934 Decimal("0")
3935 >>> c.is_normal(Decimal('-Inf'))
3936 Decimal("0")
3937 >>> c.is_normal(Decimal('NaN'))
3938 Decimal("0")
3939 """
3940 return a.is_normal(context=self)
3941
3942 def is_qnan(self, a):
3943 """Returns 1 if the operand is a quiet NaN, otherwise returns 0.
3944
3945 >>> ExtendedContext.is_qnan(Decimal('2.50'))
3946 Decimal("0")
3947 >>> ExtendedContext.is_qnan(Decimal('NaN'))
3948 Decimal("1")
3949 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
3950 Decimal("0")
3951 """
3952 return a.is_qnan()
3953
3954 def is_signed(self, a):
3955 """Returns 1 if the operand is negative, otherwise returns 0.
3956
3957 >>> ExtendedContext.is_signed(Decimal('2.50'))
3958 Decimal("0")
3959 >>> ExtendedContext.is_signed(Decimal('-12'))
3960 Decimal("1")
3961 >>> ExtendedContext.is_signed(Decimal('-0'))
3962 Decimal("1")
3963 """
3964 return a.is_signed()
3965
3966 def is_snan(self, a):
3967 """Returns 1 if the operand is a signaling NaN, otherwise returns 0.
3968
3969 >>> ExtendedContext.is_snan(Decimal('2.50'))
3970 Decimal("0")
3971 >>> ExtendedContext.is_snan(Decimal('NaN'))
3972 Decimal("0")
3973 >>> ExtendedContext.is_snan(Decimal('sNaN'))
3974 Decimal("1")
3975 """
3976 return a.is_snan()
3977
3978 def is_subnormal(self, a):
3979 """Returns 1 if the operand is subnormal, otherwise returns 0.
3980
3981 >>> c = ExtendedContext.copy()
3982 >>> c.Emin = -999
3983 >>> c.Emax = 999
3984 >>> c.is_subnormal(Decimal('2.50'))
3985 Decimal("0")
3986 >>> c.is_subnormal(Decimal('0.1E-999'))
3987 Decimal("1")
3988 >>> c.is_subnormal(Decimal('0.00'))
3989 Decimal("0")
3990 >>> c.is_subnormal(Decimal('-Inf'))
3991 Decimal("0")
3992 >>> c.is_subnormal(Decimal('NaN'))
3993 Decimal("0")
3994 """
3995 return a.is_subnormal(context=self)
3996
3997 def is_zero(self, a):
3998 """Returns 1 if the operand is a zero, otherwise returns 0.
3999
4000 >>> ExtendedContext.is_zero(Decimal('0'))
4001 Decimal("1")
4002 >>> ExtendedContext.is_zero(Decimal('2.50'))
4003 Decimal("0")
4004 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
4005 Decimal("1")
4006 """
4007 return a.is_zero()
4008
4009 def ln(self, a):
4010 """Returns the natural (base e) logarithm of the operand.
4011
4012 >>> c = ExtendedContext.copy()
4013 >>> c.Emin = -999
4014 >>> c.Emax = 999
4015 >>> c.ln(Decimal('0'))
4016 Decimal("-Infinity")
4017 >>> c.ln(Decimal('1.000'))
4018 Decimal("0")
4019 >>> c.ln(Decimal('2.71828183'))
4020 Decimal("1.00000000")
4021 >>> c.ln(Decimal('10'))
4022 Decimal("2.30258509")
4023 >>> c.ln(Decimal('+Infinity'))
4024 Decimal("Infinity")
4025 """
4026 return a.ln(context=self)
4027
4028 def log10(self, a):
4029 """Returns the base 10 logarithm of the operand.
4030
4031 >>> c = ExtendedContext.copy()
4032 >>> c.Emin = -999
4033 >>> c.Emax = 999
4034 >>> c.log10(Decimal('0'))
4035 Decimal("-Infinity")
4036 >>> c.log10(Decimal('0.001'))
4037 Decimal("-3")
4038 >>> c.log10(Decimal('1.000'))
4039 Decimal("0")
4040 >>> c.log10(Decimal('2'))
4041 Decimal("0.301029996")
4042 >>> c.log10(Decimal('10'))
4043 Decimal("1")
4044 >>> c.log10(Decimal('70'))
4045 Decimal("1.84509804")
4046 >>> c.log10(Decimal('+Infinity'))
4047 Decimal("Infinity")
4048 """
4049 return a.log10(context=self)
4050
4051 def logb(self, a):
4052 """ Returns the exponent of the magnitude of the operand's MSD.
4053
4054 The result is the integer which is the exponent of the magnitude
4055 of the most significant digit of the operand (as though the
4056 operand were truncated to a single digit while maintaining the
4057 value of that digit and without limiting the resulting exponent).
4058
4059 >>> ExtendedContext.logb(Decimal('250'))
4060 Decimal("2")
4061 >>> ExtendedContext.logb(Decimal('2.50'))
4062 Decimal("0")
4063 >>> ExtendedContext.logb(Decimal('0.03'))
4064 Decimal("-2")
4065 >>> ExtendedContext.logb(Decimal('0'))
4066 Decimal("-Infinity")
4067 """
4068 return a.logb(context=self)
4069
4070 def logical_and(self, a, b):
4071 """Applies the logical operation 'and' between each operand's digits.
4072
4073 The operands must be both logical numbers.
4074
4075 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4076 Decimal("0")
4077 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4078 Decimal("0")
4079 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4080 Decimal("0")
4081 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4082 Decimal("1")
4083 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4084 Decimal("1000")
4085 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4086 Decimal("10")
4087 """
4088 return a.logical_and(b, context=self)
4089
4090 def logical_invert(self, a):
4091 """Invert all the digits in the operand.
4092
4093 The operand must be a logical number.
4094
4095 >>> ExtendedContext.logical_invert(Decimal('0'))
4096 Decimal("111111111")
4097 >>> ExtendedContext.logical_invert(Decimal('1'))
4098 Decimal("111111110")
4099 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4100 Decimal("0")
4101 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4102 Decimal("10101010")
4103 """
4104 return a.logical_invert(context=self)
4105
4106 def logical_or(self, a, b):
4107 """Applies the logical operation 'or' between each operand's digits.
4108
4109 The operands must be both logical numbers.
4110
4111 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4112 Decimal("0")
4113 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4114 Decimal("1")
4115 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4116 Decimal("1")
4117 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4118 Decimal("1")
4119 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4120 Decimal("1110")
4121 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4122 Decimal("1110")
4123 """
4124 return a.logical_or(b, context=self)
4125
4126 def logical_xor(self, a, b):
4127 """Applies the logical operation 'xor' between each operand's digits.
4128
4129 The operands must be both logical numbers.
4130
4131 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4132 Decimal("0")
4133 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4134 Decimal("1")
4135 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4136 Decimal("1")
4137 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4138 Decimal("0")
4139 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4140 Decimal("110")
4141 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4142 Decimal("1101")
4143 """
4144 return a.logical_xor(b, context=self)
4145
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004146 def max(self, a,b):
4147 """max compares two values numerically and returns the maximum.
4148
4149 If either operand is a NaN then the general rules apply.
4150 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004151 operation. If they are numerically equal then the left-hand operand
4152 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004153 infinity) of the two operands is chosen as the result.
4154
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004155 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004156 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004157 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004158 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004159 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004160 Decimal("1")
4161 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4162 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004163 """
4164 return a.max(b, context=self)
4165
Facundo Batista353750c2007-09-13 18:13:15 +00004166 def max_mag(self, a, b):
4167 """Compares the values numerically with their sign ignored."""
4168 return a.max_mag(b, context=self)
4169
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004170 def min(self, a,b):
4171 """min compares two values numerically and returns the minimum.
4172
4173 If either operand is a NaN then the general rules apply.
4174 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004175 operation. If they are numerically equal then the left-hand operand
4176 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004177 infinity) of the two operands is chosen as the result.
4178
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004179 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004180 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004181 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004182 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004183 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004184 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004185 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4186 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004187 """
4188 return a.min(b, context=self)
4189
Facundo Batista353750c2007-09-13 18:13:15 +00004190 def min_mag(self, a, b):
4191 """Compares the values numerically with their sign ignored."""
4192 return a.min_mag(b, context=self)
4193
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004194 def minus(self, a):
4195 """Minus corresponds to unary prefix minus in Python.
4196
4197 The operation is evaluated using the same rules as subtract; the
4198 operation minus(a) is calculated as subtract('0', a) where the '0'
4199 has the same exponent as the operand.
4200
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004201 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004202 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004203 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004204 Decimal("1.3")
4205 """
4206 return a.__neg__(context=self)
4207
4208 def multiply(self, a, b):
4209 """multiply multiplies two operands.
4210
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004211 If either operand is a special value then the general rules apply.
4212 Otherwise, the operands are multiplied together ('long multiplication'),
4213 resulting in a number which may be as long as the sum of the lengths
4214 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004215
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004216 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004217 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004218 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004219 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004220 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004221 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004222 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004223 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004224 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004225 Decimal("4.28135971E+11")
4226 """
4227 return a.__mul__(b, context=self)
4228
Facundo Batista353750c2007-09-13 18:13:15 +00004229 def next_minus(self, a):
4230 """Returns the largest representable number smaller than a.
4231
4232 >>> c = ExtendedContext.copy()
4233 >>> c.Emin = -999
4234 >>> c.Emax = 999
4235 >>> ExtendedContext.next_minus(Decimal('1'))
4236 Decimal("0.999999999")
4237 >>> c.next_minus(Decimal('1E-1007'))
4238 Decimal("0E-1007")
4239 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4240 Decimal("-1.00000004")
4241 >>> c.next_minus(Decimal('Infinity'))
4242 Decimal("9.99999999E+999")
4243 """
4244 return a.next_minus(context=self)
4245
4246 def next_plus(self, a):
4247 """Returns the smallest representable number larger than a.
4248
4249 >>> c = ExtendedContext.copy()
4250 >>> c.Emin = -999
4251 >>> c.Emax = 999
4252 >>> ExtendedContext.next_plus(Decimal('1'))
4253 Decimal("1.00000001")
4254 >>> c.next_plus(Decimal('-1E-1007'))
4255 Decimal("-0E-1007")
4256 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4257 Decimal("-1.00000002")
4258 >>> c.next_plus(Decimal('-Infinity'))
4259 Decimal("-9.99999999E+999")
4260 """
4261 return a.next_plus(context=self)
4262
4263 def next_toward(self, a, b):
4264 """Returns the number closest to a, in direction towards b.
4265
4266 The result is the closest representable number from the first
4267 operand (but not the first operand) that is in the direction
4268 towards the second operand, unless the operands have the same
4269 value.
4270
4271 >>> c = ExtendedContext.copy()
4272 >>> c.Emin = -999
4273 >>> c.Emax = 999
4274 >>> c.next_toward(Decimal('1'), Decimal('2'))
4275 Decimal("1.00000001")
4276 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4277 Decimal("-0E-1007")
4278 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4279 Decimal("-1.00000002")
4280 >>> c.next_toward(Decimal('1'), Decimal('0'))
4281 Decimal("0.999999999")
4282 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4283 Decimal("0E-1007")
4284 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4285 Decimal("-1.00000004")
4286 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4287 Decimal("-0.00")
4288 """
4289 return a.next_toward(b, context=self)
4290
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004291 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004292 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004293
4294 Essentially a plus operation with all trailing zeros removed from the
4295 result.
4296
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004297 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004298 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004299 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004300 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004301 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004302 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004303 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004304 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004305 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004306 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004307 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004308 Decimal("0")
4309 """
4310 return a.normalize(context=self)
4311
Facundo Batista353750c2007-09-13 18:13:15 +00004312 def number_class(self, a):
4313 """Returns an indication of the class of the operand.
4314
4315 The class is one of the following strings:
4316 -sNaN
4317 -NaN
4318 -Infinity
4319 -Normal
4320 -Subnormal
4321 -Zero
4322 +Zero
4323 +Subnormal
4324 +Normal
4325 +Infinity
4326
4327 >>> c = Context(ExtendedContext)
4328 >>> c.Emin = -999
4329 >>> c.Emax = 999
4330 >>> c.number_class(Decimal('Infinity'))
4331 '+Infinity'
4332 >>> c.number_class(Decimal('1E-10'))
4333 '+Normal'
4334 >>> c.number_class(Decimal('2.50'))
4335 '+Normal'
4336 >>> c.number_class(Decimal('0.1E-999'))
4337 '+Subnormal'
4338 >>> c.number_class(Decimal('0'))
4339 '+Zero'
4340 >>> c.number_class(Decimal('-0'))
4341 '-Zero'
4342 >>> c.number_class(Decimal('-0.1E-999'))
4343 '-Subnormal'
4344 >>> c.number_class(Decimal('-1E-10'))
4345 '-Normal'
4346 >>> c.number_class(Decimal('-2.50'))
4347 '-Normal'
4348 >>> c.number_class(Decimal('-Infinity'))
4349 '-Infinity'
4350 >>> c.number_class(Decimal('NaN'))
4351 'NaN'
4352 >>> c.number_class(Decimal('-NaN'))
4353 'NaN'
4354 >>> c.number_class(Decimal('sNaN'))
4355 'sNaN'
4356 """
4357 return a.number_class(context=self)
4358
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004359 def plus(self, a):
4360 """Plus corresponds to unary prefix plus in Python.
4361
4362 The operation is evaluated using the same rules as add; the
4363 operation plus(a) is calculated as add('0', a) where the '0'
4364 has the same exponent as the operand.
4365
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004366 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004367 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004368 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004369 Decimal("-1.3")
4370 """
4371 return a.__pos__(context=self)
4372
4373 def power(self, a, b, modulo=None):
4374 """Raises a to the power of b, to modulo if given.
4375
Facundo Batista353750c2007-09-13 18:13:15 +00004376 With two arguments, compute a**b. If a is negative then b
4377 must be integral. The result will be inexact unless b is
4378 integral and the result is finite and can be expressed exactly
4379 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004380
Facundo Batista353750c2007-09-13 18:13:15 +00004381 With three arguments, compute (a**b) % modulo. For the
4382 three argument form, the following restrictions on the
4383 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004384
Facundo Batista353750c2007-09-13 18:13:15 +00004385 - all three arguments must be integral
4386 - b must be nonnegative
4387 - at least one of a or b must be nonzero
4388 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004389
Facundo Batista353750c2007-09-13 18:13:15 +00004390 The result of pow(a, b, modulo) is identical to the result
4391 that would be obtained by computing (a**b) % modulo with
4392 unbounded precision, but is computed more efficiently. It is
4393 always exact.
4394
4395 >>> c = ExtendedContext.copy()
4396 >>> c.Emin = -999
4397 >>> c.Emax = 999
4398 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004399 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004400 >>> c.power(Decimal('-2'), Decimal('3'))
4401 Decimal("-8")
4402 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004403 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004404 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004405 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004406 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4407 Decimal("2.00000000")
4408 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004409 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004410 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004411 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004412 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004413 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004414 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004415 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004416 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004417 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004418 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004419 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004420 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004421 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004422 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004423 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004424
4425 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4426 Decimal("11")
4427 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4428 Decimal("-11")
4429 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4430 Decimal("1")
4431 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4432 Decimal("11")
4433 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4434 Decimal("11729830")
4435 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4436 Decimal("-0")
4437 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4438 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004439 """
4440 return a.__pow__(b, modulo, context=self)
4441
4442 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004443 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004444
4445 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004446 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004447 exponent is being increased), multiplied by a positive power of ten (if
4448 the exponent is being decreased), or is unchanged (if the exponent is
4449 already equal to that of the right-hand operand).
4450
4451 Unlike other operations, if the length of the coefficient after the
4452 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004453 operation condition is raised. This guarantees that, unless there is
4454 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004455 equal to that of the right-hand operand.
4456
4457 Also unlike other operations, quantize will never raise Underflow, even
4458 if the result is subnormal and inexact.
4459
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004460 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004461 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004462 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004463 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004464 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004465 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004466 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004467 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004468 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004469 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004470 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004471 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004472 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004473 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004474 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004475 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004476 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004477 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004478 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004479 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004480 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004481 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004482 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004483 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004484 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004485 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004486 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004487 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004488 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004489 Decimal("2E+2")
4490 """
4491 return a.quantize(b, context=self)
4492
Facundo Batista353750c2007-09-13 18:13:15 +00004493 def radix(self):
4494 """Just returns 10, as this is Decimal, :)
4495
4496 >>> ExtendedContext.radix()
4497 Decimal("10")
4498 """
4499 return Decimal(10)
4500
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004501 def remainder(self, a, b):
4502 """Returns the remainder from integer division.
4503
4504 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004505 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004506 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004507 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004508
4509 This operation will fail under the same conditions as integer division
4510 (that is, if integer division on the same two operands would fail, the
4511 remainder cannot be calculated).
4512
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004513 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004514 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004515 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004516 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004517 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004518 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004519 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004520 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004521 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004522 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004523 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004524 Decimal("1.0")
4525 """
4526 return a.__mod__(b, context=self)
4527
4528 def remainder_near(self, a, b):
4529 """Returns to be "a - b * n", where n is the integer nearest the exact
4530 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004531 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004532 sign of a.
4533
4534 This operation will fail under the same conditions as integer division
4535 (that is, if integer division on the same two operands would fail, the
4536 remainder cannot be calculated).
4537
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004538 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004539 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004540 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004541 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004542 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004543 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004544 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004545 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004546 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004547 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004548 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004549 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004550 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004551 Decimal("-0.3")
4552 """
4553 return a.remainder_near(b, context=self)
4554
Facundo Batista353750c2007-09-13 18:13:15 +00004555 def rotate(self, a, b):
4556 """Returns a rotated copy of a, b times.
4557
4558 The coefficient of the result is a rotated copy of the digits in
4559 the coefficient of the first operand. The number of places of
4560 rotation is taken from the absolute value of the second operand,
4561 with the rotation being to the left if the second operand is
4562 positive or to the right otherwise.
4563
4564 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4565 Decimal("400000003")
4566 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4567 Decimal("12")
4568 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4569 Decimal("891234567")
4570 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4571 Decimal("123456789")
4572 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4573 Decimal("345678912")
4574 """
4575 return a.rotate(b, context=self)
4576
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004577 def same_quantum(self, a, b):
4578 """Returns True if the two operands have the same exponent.
4579
4580 The result is never affected by either the sign or the coefficient of
4581 either operand.
4582
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004583 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004584 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004585 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004586 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004587 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004588 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004589 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004590 True
4591 """
4592 return a.same_quantum(b)
4593
Facundo Batista353750c2007-09-13 18:13:15 +00004594 def scaleb (self, a, b):
4595 """Returns the first operand after adding the second value its exp.
4596
4597 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4598 Decimal("0.0750")
4599 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4600 Decimal("7.50")
4601 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4602 Decimal("7.50E+3")
4603 """
4604 return a.scaleb (b, context=self)
4605
4606 def shift(self, a, b):
4607 """Returns a shifted copy of a, b times.
4608
4609 The coefficient of the result is a shifted copy of the digits
4610 in the coefficient of the first operand. The number of places
4611 to shift is taken from the absolute value of the second operand,
4612 with the shift being to the left if the second operand is
4613 positive or to the right otherwise. Digits shifted into the
4614 coefficient are zeros.
4615
4616 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4617 Decimal("400000000")
4618 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4619 Decimal("0")
4620 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4621 Decimal("1234567")
4622 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4623 Decimal("123456789")
4624 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4625 Decimal("345678900")
4626 """
4627 return a.shift(b, context=self)
4628
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004629 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004630 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004631
4632 If the result must be inexact, it is rounded using the round-half-even
4633 algorithm.
4634
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004635 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004636 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004637 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004638 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004639 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004640 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004641 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004642 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004643 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004644 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004645 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004646 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004647 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004648 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004649 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004650 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004651 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004652 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004653 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004654 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004655 """
4656 return a.sqrt(context=self)
4657
4658 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004659 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004660
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004661 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004662 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004663 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004664 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004665 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004666 Decimal("-0.77")
4667 """
4668 return a.__sub__(b, context=self)
4669
4670 def to_eng_string(self, a):
4671 """Converts a number to a string, using scientific notation.
4672
4673 The operation is not affected by the context.
4674 """
4675 return a.to_eng_string(context=self)
4676
4677 def to_sci_string(self, a):
4678 """Converts a number to a string, using scientific notation.
4679
4680 The operation is not affected by the context.
4681 """
4682 return a.__str__(context=self)
4683
Facundo Batista353750c2007-09-13 18:13:15 +00004684 def to_integral_exact(self, a):
4685 """Rounds to an integer.
4686
4687 When the operand has a negative exponent, the result is the same
4688 as using the quantize() operation using the given operand as the
4689 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4690 of the operand as the precision setting; Inexact and Rounded flags
4691 are allowed in this operation. The rounding mode is taken from the
4692 context.
4693
4694 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4695 Decimal("2")
4696 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4697 Decimal("100")
4698 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4699 Decimal("100")
4700 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4701 Decimal("102")
4702 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4703 Decimal("-102")
4704 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4705 Decimal("1.0E+6")
4706 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4707 Decimal("7.89E+77")
4708 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4709 Decimal("-Infinity")
4710 """
4711 return a.to_integral_exact(context=self)
4712
4713 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004714 """Rounds to an integer.
4715
4716 When the operand has a negative exponent, the result is the same
4717 as using the quantize() operation using the given operand as the
4718 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4719 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004720 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004721
Facundo Batista353750c2007-09-13 18:13:15 +00004722 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004723 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004724 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004725 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004726 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004727 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004728 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004729 Decimal("102")
Facundo Batista353750c2007-09-13 18:13:15 +00004730 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004731 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004732 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004733 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004734 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004735 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004736 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004737 Decimal("-Infinity")
4738 """
Facundo Batista353750c2007-09-13 18:13:15 +00004739 return a.to_integral_value(context=self)
4740
4741 # the method name changed, but we provide also the old one, for compatibility
4742 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004743
4744class _WorkRep(object):
4745 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004746 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004747 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004748 # exp: None, int, or string
4749
4750 def __init__(self, value=None):
4751 if value is None:
4752 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004753 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004754 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004755 elif isinstance(value, Decimal):
4756 self.sign = value._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004757 cum = 0
Raymond Hettinger17931de2004-10-27 06:21:46 +00004758 for digit in value._int:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004759 cum = cum * 10 + digit
4760 self.int = cum
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004761 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004762 else:
4763 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004764 self.sign = value[0]
4765 self.int = value[1]
4766 self.exp = value[2]
4767
4768 def __repr__(self):
4769 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4770
4771 __str__ = __repr__
4772
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004773
4774
4775def _normalize(op1, op2, shouldround = 0, prec = 0):
4776 """Normalizes op1, op2 to have the same exp and length of coefficient.
4777
4778 Done during addition.
4779 """
Facundo Batista353750c2007-09-13 18:13:15 +00004780 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004781 tmp = op2
4782 other = op1
4783 else:
4784 tmp = op1
4785 other = op2
4786
Facundo Batista353750c2007-09-13 18:13:15 +00004787 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4788 # Then adding 10**exp to tmp has the same effect (after rounding)
4789 # as adding any positive quantity smaller than 10**exp; similarly
4790 # for subtraction. So if other is smaller than 10**exp we replace
4791 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4792 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004793 tmp_len = len(str(tmp.int))
4794 other_len = len(str(other.int))
Facundo Batista353750c2007-09-13 18:13:15 +00004795 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4796 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004797 other.int = 1
Facundo Batista353750c2007-09-13 18:13:15 +00004798 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004799
Facundo Batista353750c2007-09-13 18:13:15 +00004800 tmp.int *= 10 ** (tmp.exp - other.exp)
4801 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004802 return op1, op2
4803
Facundo Batista353750c2007-09-13 18:13:15 +00004804##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4805
4806# This function from Tim Peters was taken from here:
4807# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4808# The correction being in the function definition is for speed, and
4809# the whole function is not resolved with math.log because of avoiding
4810# the use of floats.
4811def _nbits(n, correction = {
4812 '0': 4, '1': 3, '2': 2, '3': 2,
4813 '4': 1, '5': 1, '6': 1, '7': 1,
4814 '8': 0, '9': 0, 'a': 0, 'b': 0,
4815 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4816 """Number of bits in binary representation of the positive integer n,
4817 or 0 if n == 0.
4818 """
4819 if n < 0:
4820 raise ValueError("The argument to _nbits should be nonnegative.")
4821 hex_n = "%x" % n
4822 return 4*len(hex_n) - correction[hex_n[0]]
4823
4824def _sqrt_nearest(n, a):
4825 """Closest integer to the square root of the positive integer n. a is
4826 an initial approximation to the square root. Any positive integer
4827 will do for a, but the closer a is to the square root of n the
4828 faster convergence will be.
4829
4830 """
4831 if n <= 0 or a <= 0:
4832 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4833
4834 b=0
4835 while a != b:
4836 b, a = a, a--n//a>>1
4837 return a
4838
4839def _rshift_nearest(x, shift):
4840 """Given an integer x and a nonnegative integer shift, return closest
4841 integer to x / 2**shift; use round-to-even in case of a tie.
4842
4843 """
4844 b, q = 1L << shift, x >> shift
4845 return q + (2*(x & (b-1)) + (q&1) > b)
4846
4847def _div_nearest(a, b):
4848 """Closest integer to a/b, a and b positive integers; rounds to even
4849 in the case of a tie.
4850
4851 """
4852 q, r = divmod(a, b)
4853 return q + (2*r + (q&1) > b)
4854
4855def _ilog(x, M, L = 8):
4856 """Integer approximation to M*log(x/M), with absolute error boundable
4857 in terms only of x/M.
4858
4859 Given positive integers x and M, return an integer approximation to
4860 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4861 between the approximation and the exact result is at most 22. For
4862 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4863 both cases these are upper bounds on the error; it will usually be
4864 much smaller."""
4865
4866 # The basic algorithm is the following: let log1p be the function
4867 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4868 # the reduction
4869 #
4870 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4871 #
4872 # repeatedly until the argument to log1p is small (< 2**-L in
4873 # absolute value). For small y we can use the Taylor series
4874 # expansion
4875 #
4876 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4877 #
4878 # truncating at T such that y**T is small enough. The whole
4879 # computation is carried out in a form of fixed-point arithmetic,
4880 # with a real number z being represented by an integer
4881 # approximation to z*M. To avoid loss of precision, the y below
4882 # is actually an integer approximation to 2**R*y*M, where R is the
4883 # number of reductions performed so far.
4884
4885 y = x-M
4886 # argument reduction; R = number of reductions performed
4887 R = 0
4888 while (R <= L and long(abs(y)) << L-R >= M or
4889 R > L and abs(y) >> R-L >= M):
4890 y = _div_nearest(long(M*y) << 1,
4891 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4892 R += 1
4893
4894 # Taylor series with T terms
4895 T = -int(-10*len(str(M))//(3*L))
4896 yshift = _rshift_nearest(y, R)
4897 w = _div_nearest(M, T)
4898 for k in xrange(T-1, 0, -1):
4899 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4900
4901 return _div_nearest(w*y, M)
4902
4903def _dlog10(c, e, p):
4904 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4905 approximation to 10**p * log10(c*10**e), with an absolute error of
4906 at most 1. Assumes that c*10**e is not exactly 1."""
4907
4908 # increase precision by 2; compensate for this by dividing
4909 # final result by 100
4910 p += 2
4911
4912 # write c*10**e as d*10**f with either:
4913 # f >= 0 and 1 <= d <= 10, or
4914 # f <= 0 and 0.1 <= d <= 1.
4915 # Thus for c*10**e close to 1, f = 0
4916 l = len(str(c))
4917 f = e+l - (e+l >= 1)
4918
4919 if p > 0:
4920 M = 10**p
4921 k = e+p-f
4922 if k >= 0:
4923 c *= 10**k
4924 else:
4925 c = _div_nearest(c, 10**-k)
4926
4927 log_d = _ilog(c, M) # error < 5 + 22 = 27
4928 log_10 = _ilog(10*M, M) # error < 15
4929 log_d = _div_nearest(log_d*M, log_10)
4930 log_tenpower = f*M # exact
4931 else:
4932 log_d = 0 # error < 2.31
4933 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4934
4935 return _div_nearest(log_tenpower+log_d, 100)
4936
4937def _dlog(c, e, p):
4938 """Given integers c, e and p with c > 0, compute an integer
4939 approximation to 10**p * log(c*10**e), with an absolute error of
4940 at most 1. Assumes that c*10**e is not exactly 1."""
4941
4942 # Increase precision by 2. The precision increase is compensated
4943 # for at the end with a division by 100.
4944 p += 2
4945
4946 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4947 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4948 # as 10**p * log(d) + 10**p*f * log(10).
4949 l = len(str(c))
4950 f = e+l - (e+l >= 1)
4951
4952 # compute approximation to 10**p*log(d), with error < 27
4953 if p > 0:
4954 k = e+p-f
4955 if k >= 0:
4956 c *= 10**k
4957 else:
4958 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4959
4960 # _ilog magnifies existing error in c by a factor of at most 10
4961 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4962 else:
4963 # p <= 0: just approximate the whole thing by 0; error < 2.31
4964 log_d = 0
4965
4966 # compute approximation to 10**p*f*log(10), with error < 17
4967 if f:
4968 sign_f = [-1, 1][f > 0]
4969 if p >= 0:
4970 M = 10**p * abs(f)
4971 else:
4972 M = _div_nearest(abs(f), 10**-p) # M = 10**p*|f|, error <= 0.5
4973
4974 if M:
4975 f_log_ten = sign_f*_ilog(10*M, M) # M*log(10), error <= 1.2 + 15 < 17
4976 else:
4977 f_log_ten = 0
4978 else:
4979 f_log_ten = 0
4980
4981 # error in sum < 17+27 = 44; error after division < 0.44 + 0.5 < 1
4982 return _div_nearest(f_log_ten + log_d, 100)
4983
4984def _iexp(x, M, L=8):
4985 """Given integers x and M, M > 0, such that x/M is small in absolute
4986 value, compute an integer approximation to M*exp(x/M). For 0 <=
4987 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4988 is usually much smaller)."""
4989
4990 # Algorithm: to compute exp(z) for a real number z, first divide z
4991 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4992 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4993 # series
4994 #
4995 # expm1(x) = x + x**2/2! + x**3/3! + ...
4996 #
4997 # Now use the identity
4998 #
4999 # expm1(2x) = expm1(x)*(expm1(x)+2)
5000 #
5001 # R times to compute the sequence expm1(z/2**R),
5002 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5003
5004 # Find R such that x/2**R/M <= 2**-L
5005 R = _nbits((long(x)<<L)//M)
5006
5007 # Taylor series. (2**L)**T > M
5008 T = -int(-10*len(str(M))//(3*L))
5009 y = _div_nearest(x, T)
5010 Mshift = long(M)<<R
5011 for i in xrange(T-1, 0, -1):
5012 y = _div_nearest(x*(Mshift + y), Mshift * i)
5013
5014 # Expansion
5015 for k in xrange(R-1, -1, -1):
5016 Mshift = long(M)<<(k+2)
5017 y = _div_nearest(y*(y+Mshift), Mshift)
5018
5019 return M+y
5020
5021def _dexp(c, e, p):
5022 """Compute an approximation to exp(c*10**e), with p decimal places of
5023 precision.
5024
5025 Returns d, f such that:
5026
5027 10**(p-1) <= d <= 10**p, and
5028 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5029
5030 In other words, d*10**f is an approximation to exp(c*10**e) with p
5031 digits of precision, and with an error in d of at most 1. This is
5032 almost, but not quite, the same as the error being < 1ulp: when d
5033 = 10**(p-1) the error could be up to 10 ulp."""
5034
5035 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5036 p += 2
5037
5038 # compute log10 with extra precision = adjusted exponent of c*10**e
5039 extra = max(0, e + len(str(c)) - 1)
5040 q = p + extra
5041 log10 = _dlog(10, 0, q) # error <= 1
5042
5043 # compute quotient c*10**e/(log10/10**q) = c*10**(e+q)/log10,
5044 # rounding down
5045 shift = e+q
5046 if shift >= 0:
5047 cshift = c*10**shift
5048 else:
5049 cshift = c//10**-shift
5050 quot, rem = divmod(cshift, log10)
5051
5052 # reduce remainder back to original precision
5053 rem = _div_nearest(rem, 10**extra)
5054
5055 # error in result of _iexp < 120; error after division < 0.62
5056 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5057
5058def _dpower(xc, xe, yc, ye, p):
5059 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5060 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5061
5062 10**(p-1) <= c <= 10**p, and
5063 (c-1)*10**e < x**y < (c+1)*10**e
5064
5065 in other words, c*10**e is an approximation to x**y with p digits
5066 of precision, and with an error in c of at most 1. (This is
5067 almost, but not quite, the same as the error being < 1ulp: when c
5068 == 10**(p-1) we can only guarantee error < 10ulp.)
5069
5070 We assume that: x is positive and not equal to 1, and y is nonzero.
5071 """
5072
5073 # Find b such that 10**(b-1) <= |y| <= 10**b
5074 b = len(str(abs(yc))) + ye
5075
5076 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5077 lxc = _dlog(xc, xe, p+b+1)
5078
5079 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5080 shift = ye-b
5081 if shift >= 0:
5082 pc = lxc*yc*10**shift
5083 else:
5084 pc = _div_nearest(lxc*yc, 10**-shift)
5085
5086 if pc == 0:
5087 # we prefer a result that isn't exactly 1; this makes it
5088 # easier to compute a correctly rounded result in __pow__
5089 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5090 coeff, exp = 10**(p-1)+1, 1-p
5091 else:
5092 coeff, exp = 10**p-1, -p
5093 else:
5094 coeff, exp = _dexp(pc, -(p+1), p+1)
5095 coeff = _div_nearest(coeff, 10)
5096 exp += 1
5097
5098 return coeff, exp
5099
5100def _log10_lb(c, correction = {
5101 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5102 '6': 23, '7': 16, '8': 10, '9': 5}):
5103 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5104 if c <= 0:
5105 raise ValueError("The argument to _log10_lb should be nonnegative.")
5106 str_c = str(c)
5107 return 100*len(str_c) - correction[str_c[0]]
5108
Facundo Batista59c58842007-04-10 12:58:45 +00005109##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005110
Facundo Batista353750c2007-09-13 18:13:15 +00005111def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005112 """Convert other to Decimal.
5113
5114 Verifies that it's ok to use in an implicit construction.
5115 """
5116 if isinstance(other, Decimal):
5117 return other
5118 if isinstance(other, (int, long)):
5119 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005120 if raiseit:
5121 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005122 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005123
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005124_infinity_map = {
5125 'inf' : 1,
5126 'infinity' : 1,
5127 '+inf' : 1,
5128 '+infinity' : 1,
5129 '-inf' : -1,
5130 '-infinity' : -1
5131}
5132
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005133def _isinfinity(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005134 """Determines whether a string or float is infinity.
5135
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005136 +1 for negative infinity; 0 for finite ; +1 for positive infinity
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005137 """
5138 num = str(num).lower()
5139 return _infinity_map.get(num, 0)
5140
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005141def _isnan(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005142 """Determines whether a string or float is NaN
5143
5144 (1, sign, diagnostic info as string) => NaN
5145 (2, sign, diagnostic info as string) => sNaN
5146 0 => not a NaN
5147 """
5148 num = str(num).lower()
5149 if not num:
5150 return 0
5151
Facundo Batista59c58842007-04-10 12:58:45 +00005152 # Get the sign, get rid of trailing [+-]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005153 sign = 0
5154 if num[0] == '+':
5155 num = num[1:]
Facundo Batista59c58842007-04-10 12:58:45 +00005156 elif num[0] == '-': # elif avoids '+-nan'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005157 num = num[1:]
5158 sign = 1
5159
5160 if num.startswith('nan'):
Facundo Batista59c58842007-04-10 12:58:45 +00005161 if len(num) > 3 and not num[3:].isdigit(): # diagnostic info
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005162 return 0
5163 return (1, sign, num[3:].lstrip('0'))
5164 if num.startswith('snan'):
5165 if len(num) > 4 and not num[4:].isdigit():
5166 return 0
5167 return (2, sign, num[4:].lstrip('0'))
5168 return 0
5169
5170
Facundo Batista59c58842007-04-10 12:58:45 +00005171##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005172
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005173# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005174# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005175
5176DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005177 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005178 traps=[DivisionByZero, Overflow, InvalidOperation],
5179 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005180 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005181 Emax=999999999,
5182 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005183 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005184)
5185
5186# Pre-made alternate contexts offered by the specification
5187# Don't change these; the user should be able to select these
5188# contexts and be able to reproduce results from other implementations
5189# of the spec.
5190
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005191BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005192 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005193 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5194 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005195)
5196
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005197ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005198 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005199 traps=[],
5200 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005201)
5202
5203
Facundo Batista59c58842007-04-10 12:58:45 +00005204##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005205
Facundo Batista59c58842007-04-10 12:58:45 +00005206# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005207Inf = Decimal('Inf')
5208negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005209NaN = Decimal('NaN')
5210Dec_0 = Decimal(0)
5211Dec_p1 = Decimal(1)
5212Dec_n1 = Decimal(-1)
5213Dec_p2 = Decimal(2)
5214Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005215
Facundo Batista59c58842007-04-10 12:58:45 +00005216# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005217Infsign = (Inf, negInf)
5218
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005219
Facundo Batista59c58842007-04-10 12:58:45 +00005220##### crud for parsing strings #############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005221import re
5222
5223# There's an optional sign at the start, and an optional exponent
5224# at the end. The exponent has an optional sign and at least one
5225# digit. In between, must have either at least one digit followed
5226# by an optional fraction, or a decimal point followed by at least
5227# one digit. Yuck.
5228
5229_parser = re.compile(r"""
5230# \s*
5231 (?P<sign>[-+])?
5232 (
5233 (?P<int>\d+) (\. (?P<frac>\d*))?
5234 |
5235 \. (?P<onlyfrac>\d+)
5236 )
5237 ([eE](?P<exp>[-+]? \d+))?
5238# \s*
5239 $
Facundo Batista59c58842007-04-10 12:58:45 +00005240""", re.VERBOSE).match # Uncomment the \s* to allow leading or trailing spaces.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005241
5242del re
5243
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005244def _string2exact(s):
Facundo Batista59c58842007-04-10 12:58:45 +00005245 """Return sign, n, p s.t.
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00005246
Facundo Batista59c58842007-04-10 12:58:45 +00005247 Float string value == -1**sign * n * 10**p exactly
5248 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005249 m = _parser(s)
5250 if m is None:
5251 raise ValueError("invalid literal for Decimal: %r" % s)
5252
5253 if m.group('sign') == "-":
5254 sign = 1
5255 else:
5256 sign = 0
5257
5258 exp = m.group('exp')
5259 if exp is None:
5260 exp = 0
5261 else:
5262 exp = int(exp)
5263
5264 intpart = m.group('int')
5265 if intpart is None:
5266 intpart = ""
5267 fracpart = m.group('onlyfrac')
5268 else:
5269 fracpart = m.group('frac')
5270 if fracpart is None:
5271 fracpart = ""
5272
5273 exp -= len(fracpart)
5274
5275 mantissa = intpart + fracpart
5276 tmp = map(int, mantissa)
5277 backup = tmp
5278 while tmp and tmp[0] == 0:
5279 del tmp[0]
5280
5281 # It's a zero
5282 if not tmp:
5283 if backup:
5284 return (sign, tuple(backup), exp)
5285 return (sign, (0,), exp)
5286 mantissa = tuple(tmp)
5287
5288 return (sign, mantissa, exp)
5289
5290
5291if __name__ == '__main__':
5292 import doctest, sys
5293 doctest.testmod(sys.modules[__name__])