blob: 4137d065f159dfa9a881f4638a75f290148114a5 [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))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000769 i = int(self)
770 if self == Decimal(i):
771 return hash(i)
772 assert self.__nonzero__() # '-0' handled by integer case
773 return hash(str(self.normalize()))
774
775 def as_tuple(self):
776 """Represents the number as a triple tuple.
777
778 To show the internals exactly as they are.
779 """
780 return (self._sign, self._int, self._exp)
781
782 def __repr__(self):
783 """Represents the number as an instance of Decimal."""
784 # Invariant: eval(repr(d)) == d
785 return 'Decimal("%s")' % str(self)
786
Facundo Batista353750c2007-09-13 18:13:15 +0000787 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000788 """Return string representation of the number in scientific notation.
789
790 Captures all of the information in the underlying representation.
791 """
792
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000793 if self._is_special:
794 if self._isnan():
795 minus = '-'*self._sign
796 if self._int == (0,):
797 info = ''
798 else:
799 info = ''.join(map(str, self._int))
800 if self._isnan() == 2:
801 return minus + 'sNaN' + info
802 return minus + 'NaN' + info
803 if self._isinfinity():
804 minus = '-'*self._sign
805 return minus + 'Infinity'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000806
807 if context is None:
808 context = getcontext()
809
810 tmp = map(str, self._int)
811 numdigits = len(self._int)
812 leftdigits = self._exp + numdigits
Facundo Batista59c58842007-04-10 12:58:45 +0000813 if eng and not self: # self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
814 if self._exp < 0 and self._exp >= -6: # short, no need for e/E
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000815 s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
816 return s
Facundo Batista59c58842007-04-10 12:58:45 +0000817 # exp is closest mult. of 3 >= self._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000818 exp = ((self._exp - 1)// 3 + 1) * 3
819 if exp != self._exp:
820 s = '0.'+'0'*(exp - self._exp)
821 else:
822 s = '0'
823 if exp != 0:
824 if context.capitals:
825 s += 'E'
826 else:
827 s += 'e'
828 if exp > 0:
Facundo Batista59c58842007-04-10 12:58:45 +0000829 s += '+' # 0.0e+3, not 0.0e3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000830 s += str(exp)
831 s = '-'*self._sign + s
832 return s
833 if eng:
834 dotplace = (leftdigits-1)%3+1
835 adjexp = leftdigits -1 - (leftdigits-1)%3
836 else:
837 adjexp = leftdigits-1
838 dotplace = 1
839 if self._exp == 0:
840 pass
841 elif self._exp < 0 and adjexp >= 0:
842 tmp.insert(leftdigits, '.')
843 elif self._exp < 0 and adjexp >= -6:
844 tmp[0:0] = ['0'] * int(-leftdigits)
845 tmp.insert(0, '0.')
846 else:
847 if numdigits > dotplace:
848 tmp.insert(dotplace, '.')
849 elif numdigits < dotplace:
850 tmp.extend(['0']*(dotplace-numdigits))
851 if adjexp:
852 if not context.capitals:
853 tmp.append('e')
854 else:
855 tmp.append('E')
856 if adjexp > 0:
857 tmp.append('+')
858 tmp.append(str(adjexp))
859 if eng:
860 while tmp[0:1] == ['0']:
861 tmp[0:1] = []
862 if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
863 tmp[0:0] = ['0']
864 if self._sign:
865 tmp.insert(0, '-')
866
867 return ''.join(tmp)
868
869 def to_eng_string(self, context=None):
870 """Convert to engineering-type string.
871
872 Engineering notation has an exponent which is a multiple of 3, so there
873 are up to 3 digits left of the decimal place.
874
875 Same rules for when in exponential and when as a value as in __str__.
876 """
Facundo Batista353750c2007-09-13 18:13:15 +0000877 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000878
879 def __neg__(self, context=None):
880 """Returns a copy with the sign switched.
881
882 Rounds, if it has reason.
883 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000884 if self._is_special:
885 ans = self._check_nans(context=context)
886 if ans:
887 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000888
889 if not self:
890 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +0000891 ans = self.copy_sign(Dec_0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000892 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000893 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000894
895 if context is None:
896 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000897 if context._rounding_decision == ALWAYS_ROUND:
Facundo Batista353750c2007-09-13 18:13:15 +0000898 return ans._fix(context)
899 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000900
901 def __pos__(self, context=None):
902 """Returns a copy, unless it is a sNaN.
903
904 Rounds the number (if more then precision digits)
905 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000906 if self._is_special:
907 ans = self._check_nans(context=context)
908 if ans:
909 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000910
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000911 if not self:
912 # + (-0) = 0
Facundo Batista353750c2007-09-13 18:13:15 +0000913 ans = self.copy_sign(Dec_0)
914 else:
915 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000916
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000917 if context is None:
918 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000919 if context._rounding_decision == ALWAYS_ROUND:
Facundo Batista353750c2007-09-13 18:13:15 +0000920 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000921 return ans
922
923 def __abs__(self, round=1, context=None):
924 """Returns the absolute value of self.
925
926 If the second argument is 0, do not round.
927 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000928 if self._is_special:
929 ans = self._check_nans(context=context)
930 if ans:
931 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000932
933 if not round:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000934 if context is None:
935 context = getcontext()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000936 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000937 context._set_rounding_decision(NEVER_ROUND)
938
939 if self._sign:
940 ans = self.__neg__(context=context)
941 else:
942 ans = self.__pos__(context=context)
943
944 return ans
945
946 def __add__(self, other, context=None):
947 """Returns self + other.
948
949 -INF + INF (or the reverse) cause InvalidOperation errors.
950 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000951 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000952 if other is NotImplemented:
953 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000954
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000955 if context is None:
956 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000957
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000958 if self._is_special or other._is_special:
959 ans = self._check_nans(other, context)
960 if ans:
961 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000962
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000963 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000964 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000965 if self._sign != other._sign and other._isinfinity():
966 return context._raise_error(InvalidOperation, '-INF + INF')
967 return Decimal(self)
968 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000969 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000970
971 shouldround = context._rounding_decision == ALWAYS_ROUND
972
973 exp = min(self._exp, other._exp)
974 negativezero = 0
975 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +0000976 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000977 negativezero = 1
978
979 if not self and not other:
980 sign = min(self._sign, other._sign)
981 if negativezero:
982 sign = 1
Facundo Batista353750c2007-09-13 18:13:15 +0000983 ans = Decimal( (sign, (0,), exp))
984 if shouldround:
985 ans = ans._fix(context)
986 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000987 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +0000988 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +0000989 ans = other._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000990 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000991 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000992 return ans
993 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +0000994 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +0000995 ans = self._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000996 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000997 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000998 return ans
999
1000 op1 = _WorkRep(self)
1001 op2 = _WorkRep(other)
1002 op1, op2 = _normalize(op1, op2, shouldround, context.prec)
1003
1004 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001005 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001006 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001007 if op1.int == op2.int:
Facundo Batista353750c2007-09-13 18:13:15 +00001008 ans = Decimal((negativezero, (0,), exp))
1009 if shouldround:
1010 ans = ans._fix(context)
1011 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001012 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001013 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001014 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001015 if op1.sign == 1:
1016 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001017 op1.sign, op2.sign = op2.sign, op1.sign
1018 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001019 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001020 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001021 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001022 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001023 op1.sign, op2.sign = (0, 0)
1024 else:
1025 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001026 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001027
Raymond Hettinger17931de2004-10-27 06:21:46 +00001028 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001029 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001030 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001031 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001032
1033 result.exp = op1.exp
1034 ans = Decimal(result)
1035 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001036 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001037 return ans
1038
1039 __radd__ = __add__
1040
1041 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001042 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001043 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001044 if other is NotImplemented:
1045 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001046
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001047 if self._is_special or other._is_special:
1048 ans = self._check_nans(other, context=context)
1049 if ans:
1050 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001051
Facundo Batista353750c2007-09-13 18:13:15 +00001052 # self - other is computed as self + other.copy_negate()
1053 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001054
1055 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001056 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001057 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001058 if other is NotImplemented:
1059 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001060
Facundo Batista353750c2007-09-13 18:13:15 +00001061 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001062
Facundo Batista353750c2007-09-13 18:13:15 +00001063 def _increment(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001064 """Special case of add, adding 1eExponent
1065
1066 Since it is common, (rounding, for example) this adds
1067 (sign)*one E self._exp to the number more efficiently than add.
1068
Facundo Batista353750c2007-09-13 18:13:15 +00001069 Assumes that self is nonspecial.
1070
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001071 For example:
1072 Decimal('5.624e10')._increment() == Decimal('5.625e10')
1073 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001074 L = list(self._int)
1075 L[-1] += 1
1076 spot = len(L)-1
1077 while L[spot] == 10:
1078 L[spot] = 0
1079 if spot == 0:
1080 L[0:0] = [1]
1081 break
1082 L[spot-1] += 1
1083 spot -= 1
Facundo Batista353750c2007-09-13 18:13:15 +00001084 return Decimal((self._sign, L, self._exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001085
1086 def __mul__(self, other, context=None):
1087 """Return self * other.
1088
1089 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1090 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001091 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001092 if other is NotImplemented:
1093 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001094
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001095 if context is None:
1096 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001097
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001098 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001099
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001100 if self._is_special or other._is_special:
1101 ans = self._check_nans(other, context)
1102 if ans:
1103 return ans
1104
1105 if self._isinfinity():
1106 if not other:
1107 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1108 return Infsign[resultsign]
1109
1110 if other._isinfinity():
1111 if not self:
1112 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1113 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001114
1115 resultexp = self._exp + other._exp
1116 shouldround = context._rounding_decision == ALWAYS_ROUND
1117
1118 # Special case for multiplying by zero
1119 if not self or not other:
1120 ans = Decimal((resultsign, (0,), resultexp))
1121 if shouldround:
Facundo Batista59c58842007-04-10 12:58:45 +00001122 # Fixing in case the exponent is out of bounds
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001123 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001124 return ans
1125
1126 # Special case for multiplying by power of 10
1127 if self._int == (1,):
1128 ans = Decimal((resultsign, other._int, resultexp))
1129 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001130 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001131 return ans
1132 if other._int == (1,):
1133 ans = Decimal((resultsign, self._int, resultexp))
1134 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001135 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001136 return ans
1137
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001138 op1 = _WorkRep(self)
1139 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001140
Facundo Batista59c58842007-04-10 12:58:45 +00001141 ans = Decimal((resultsign, map(int, str(op1.int * op2.int)), resultexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001142 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001143 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001144
1145 return ans
1146 __rmul__ = __mul__
1147
1148 def __div__(self, other, context=None):
1149 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001150 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001151 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001152 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001153
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001154 if context is None:
1155 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001156
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001157 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001158
1159 if self._is_special or other._is_special:
1160 ans = self._check_nans(other, context)
1161 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001162 return ans
1163
1164 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001165 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001166
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001167 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001168 return Infsign[sign]
1169
1170 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001171 context._raise_error(Clamped, 'Division by infinity')
1172 return Decimal((sign, (0,), context.Etiny()))
1173
1174 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001175 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001176 if not self:
1177 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001178 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001179
Facundo Batistacce8df22007-09-18 16:53:18 +00001180 if not self:
1181 exp = self._exp - other._exp
1182 coeff = 0
1183 else:
1184 # OK, so neither = 0, INF or NaN
1185 shift = len(other._int) - len(self._int) + context.prec + 1
1186 exp = self._exp - other._exp - shift
1187 op1 = _WorkRep(self)
1188 op2 = _WorkRep(other)
1189 if shift >= 0:
1190 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1191 else:
1192 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1193 if remainder:
1194 # result is not exact; adjust to ensure correct rounding
1195 if coeff % 5 == 0:
1196 coeff += 1
1197 else:
1198 # result is exact; get as close to ideal exponent as possible
1199 ideal_exp = self._exp - other._exp
1200 while exp < ideal_exp and coeff % 10 == 0:
1201 coeff //= 10
1202 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001203
Facundo Batistacce8df22007-09-18 16:53:18 +00001204 ans = Decimal((sign, map(int, str(coeff)), exp))
1205 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001206
Facundo Batistacce8df22007-09-18 16:53:18 +00001207 __truediv__ = __div__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001208
Facundo Batistacce8df22007-09-18 16:53:18 +00001209 def _divide(self, other, context):
1210 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001211
Facundo Batistacce8df22007-09-18 16:53:18 +00001212 Assumes that neither self nor other is a NaN, that self is not
1213 infinite and that other is nonzero.
1214 """
1215 sign = self._sign ^ other._sign
1216 if other._isinfinity():
1217 ideal_exp = self._exp
1218 else:
1219 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001220
Facundo Batistacce8df22007-09-18 16:53:18 +00001221 expdiff = self.adjusted() - other.adjusted()
1222 if not self or other._isinfinity() or expdiff <= -2:
1223 return (Decimal((sign, (0,), 0)),
1224 self._rescale(ideal_exp, context.rounding))
1225 if expdiff <= context.prec:
1226 op1 = _WorkRep(self)
1227 op2 = _WorkRep(other)
1228 if op1.exp >= op2.exp:
1229 op1.int *= 10**(op1.exp - op2.exp)
1230 else:
1231 op2.int *= 10**(op2.exp - op1.exp)
1232 q, r = divmod(op1.int, op2.int)
1233 if q < 10**context.prec:
1234 return (Decimal((sign, map(int, str(q)), 0)),
1235 Decimal((self._sign, map(int, str(r)), ideal_exp)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001236
Facundo Batistacce8df22007-09-18 16:53:18 +00001237 # Here the quotient is too large to be representable
1238 ans = context._raise_error(DivisionImpossible,
1239 'quotient too large in //, % or divmod')
1240 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001241
1242 def __rdiv__(self, other, context=None):
1243 """Swaps self/other and returns __div__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001244 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001245 if other is NotImplemented:
1246 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001247 return other.__div__(self, context=context)
1248 __rtruediv__ = __rdiv__
1249
1250 def __divmod__(self, other, context=None):
1251 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001252 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001253 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001254 other = _convert_other(other)
1255 if other is NotImplemented:
1256 return other
1257
1258 if context is None:
1259 context = getcontext()
1260
1261 ans = self._check_nans(other, context)
1262 if ans:
1263 return (ans, ans)
1264
1265 sign = self._sign ^ other._sign
1266 if self._isinfinity():
1267 if other._isinfinity():
1268 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1269 return ans, ans
1270 else:
1271 return (Infsign[sign],
1272 context._raise_error(InvalidOperation, 'INF % x'))
1273
1274 if not other:
1275 if not self:
1276 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1277 return ans, ans
1278 else:
1279 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1280 context._raise_error(InvalidOperation, 'x % 0'))
1281
1282 quotient, remainder = self._divide(other, context)
1283 if context._rounding_decision == ALWAYS_ROUND:
1284 remainder = remainder._fix(context)
1285 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001286
1287 def __rdivmod__(self, other, context=None):
1288 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001289 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001290 if other is NotImplemented:
1291 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001292 return other.__divmod__(self, context=context)
1293
1294 def __mod__(self, other, context=None):
1295 """
1296 self % other
1297 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001298 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001299 if other is NotImplemented:
1300 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001301
Facundo Batistacce8df22007-09-18 16:53:18 +00001302 if context is None:
1303 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001304
Facundo Batistacce8df22007-09-18 16:53:18 +00001305 ans = self._check_nans(other, context)
1306 if ans:
1307 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001308
Facundo Batistacce8df22007-09-18 16:53:18 +00001309 if self._isinfinity():
1310 return context._raise_error(InvalidOperation, 'INF % x')
1311 elif not other:
1312 if self:
1313 return context._raise_error(InvalidOperation, 'x % 0')
1314 else:
1315 return context._raise_error(DivisionUndefined, '0 % 0')
1316
1317 remainder = self._divide(other, context)[1]
1318 if context._rounding_decision == ALWAYS_ROUND:
1319 remainder = remainder._fix(context)
1320 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001321
1322 def __rmod__(self, other, context=None):
1323 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001324 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001325 if other is NotImplemented:
1326 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001327 return other.__mod__(self, context=context)
1328
1329 def remainder_near(self, other, context=None):
1330 """
1331 Remainder nearest to 0- abs(remainder-near) <= other/2
1332 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001333 if context is None:
1334 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001335
Facundo Batista353750c2007-09-13 18:13:15 +00001336 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001337
Facundo Batista353750c2007-09-13 18:13:15 +00001338 ans = self._check_nans(other, context)
1339 if ans:
1340 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001341
Facundo Batista353750c2007-09-13 18:13:15 +00001342 # self == +/-infinity -> InvalidOperation
1343 if self._isinfinity():
1344 return context._raise_error(InvalidOperation,
1345 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001346
Facundo Batista353750c2007-09-13 18:13:15 +00001347 # other == 0 -> either InvalidOperation or DivisionUndefined
1348 if not other:
1349 if self:
1350 return context._raise_error(InvalidOperation,
1351 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001352 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001353 return context._raise_error(DivisionUndefined,
1354 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001355
Facundo Batista353750c2007-09-13 18:13:15 +00001356 # other = +/-infinity -> remainder = self
1357 if other._isinfinity():
1358 ans = Decimal(self)
1359 return ans._fix(context)
1360
1361 # self = 0 -> remainder = self, with ideal exponent
1362 ideal_exponent = min(self._exp, other._exp)
1363 if not self:
1364 ans = Decimal((self._sign, (0,), ideal_exponent))
1365 return ans._fix(context)
1366
1367 # catch most cases of large or small quotient
1368 expdiff = self.adjusted() - other.adjusted()
1369 if expdiff >= context.prec + 1:
1370 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001371 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001372 if expdiff <= -2:
1373 # expdiff <= -2 => abs(self/other) < 0.1
1374 ans = self._rescale(ideal_exponent, context.rounding)
1375 return ans._fix(context)
1376
1377 # adjust both arguments to have the same exponent, then divide
1378 op1 = _WorkRep(self)
1379 op2 = _WorkRep(other)
1380 if op1.exp >= op2.exp:
1381 op1.int *= 10**(op1.exp - op2.exp)
1382 else:
1383 op2.int *= 10**(op2.exp - op1.exp)
1384 q, r = divmod(op1.int, op2.int)
1385 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1386 # 10**ideal_exponent. Apply correction to ensure that
1387 # abs(remainder) <= abs(other)/2
1388 if 2*r + (q&1) > op2.int:
1389 r -= op2.int
1390 q += 1
1391
1392 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001393 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001394
1395 # result has same sign as self unless r is negative
1396 sign = self._sign
1397 if r < 0:
1398 sign = 1-sign
1399 r = -r
1400
1401 ans = Decimal((sign, map(int, str(r)), ideal_exponent))
1402 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001403
1404 def __floordiv__(self, other, context=None):
1405 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001406 other = _convert_other(other)
1407 if other is NotImplemented:
1408 return other
1409
1410 if context is None:
1411 context = getcontext()
1412
1413 ans = self._check_nans(other, context)
1414 if ans:
1415 return ans
1416
1417 if self._isinfinity():
1418 if other._isinfinity():
1419 return context._raise_error(InvalidOperation, 'INF // INF')
1420 else:
1421 return Infsign[self._sign ^ other._sign]
1422
1423 if not other:
1424 if self:
1425 return context._raise_error(DivisionByZero, 'x // 0',
1426 self._sign ^ other._sign)
1427 else:
1428 return context._raise_error(DivisionUndefined, '0 // 0')
1429
1430 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001431
1432 def __rfloordiv__(self, other, context=None):
1433 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001434 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001435 if other is NotImplemented:
1436 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001437 return other.__floordiv__(self, context=context)
1438
1439 def __float__(self):
1440 """Float representation."""
1441 return float(str(self))
1442
1443 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001444 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001445 if self._is_special:
1446 if self._isnan():
1447 context = getcontext()
1448 return context._raise_error(InvalidContext)
1449 elif self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001450 raise OverflowError("Cannot convert infinity to long")
Facundo Batista353750c2007-09-13 18:13:15 +00001451 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001452 if self._exp >= 0:
Facundo Batista353750c2007-09-13 18:13:15 +00001453 return s*int(''.join(map(str, self._int)))*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001454 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001455 return s*int(''.join(map(str, self._int))[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001456
1457 def __long__(self):
1458 """Converts to a long.
1459
1460 Equivalent to long(int(self))
1461 """
1462 return long(self.__int__())
1463
Facundo Batista353750c2007-09-13 18:13:15 +00001464 def _fix_nan(self, context):
1465 """Decapitate the payload of a NaN to fit the context"""
1466 payload = self._int
1467
1468 # maximum length of payload is precision if _clamp=0,
1469 # precision-1 if _clamp=1.
1470 max_payload_len = context.prec - context._clamp
1471 if len(payload) > max_payload_len:
1472 pos = len(payload)-max_payload_len
1473 while pos < len(payload) and payload[pos] == 0:
1474 pos += 1
1475 payload = payload[pos:]
1476 return Decimal((self._sign, payload, self._exp))
Facundo Batista6c398da2007-09-17 17:30:13 +00001477 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001478
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001479 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001480 """Round if it is necessary to keep self within prec precision.
1481
1482 Rounds and fixes the exponent. Does not raise on a sNaN.
1483
1484 Arguments:
1485 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001486 context - context used.
1487 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001488
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001489 if context is None:
1490 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001491
Facundo Batista353750c2007-09-13 18:13:15 +00001492 if self._is_special:
1493 if self._isnan():
1494 # decapitate payload if necessary
1495 return self._fix_nan(context)
1496 else:
1497 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001498 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001499
Facundo Batista353750c2007-09-13 18:13:15 +00001500 # if self is zero then exponent should be between Etiny and
1501 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1502 Etiny = context.Etiny()
1503 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001504 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001505 exp_max = [context.Emax, Etop][context._clamp]
1506 new_exp = min(max(self._exp, Etiny), exp_max)
1507 if new_exp != self._exp:
1508 context._raise_error(Clamped)
1509 return Decimal((self._sign, (0,), new_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001510 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001511 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001512
1513 # exp_min is the smallest allowable exponent of the result,
1514 # equal to max(self.adjusted()-context.prec+1, Etiny)
1515 exp_min = len(self._int) + self._exp - context.prec
1516 if exp_min > Etop:
1517 # overflow: exp_min > Etop iff self.adjusted() > Emax
1518 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001519 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001520 return context._raise_error(Overflow, 'above Emax', self._sign)
1521 self_is_subnormal = exp_min < Etiny
1522 if self_is_subnormal:
1523 context._raise_error(Subnormal)
1524 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001525
Facundo Batista353750c2007-09-13 18:13:15 +00001526 # round if self has too many digits
1527 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001528 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001529 ans = self._rescale(exp_min, context.rounding)
1530 if ans != self:
1531 context._raise_error(Inexact)
1532 if self_is_subnormal:
1533 context._raise_error(Underflow)
1534 if not ans:
1535 # raise Clamped on underflow to 0
1536 context._raise_error(Clamped)
1537 elif len(ans._int) == context.prec+1:
1538 # we get here only if rescaling rounds the
1539 # cofficient up to exactly 10**context.prec
1540 if ans._exp < Etop:
1541 ans = Decimal((ans._sign, ans._int[:-1], ans._exp+1))
1542 else:
1543 # Inexact and Rounded have already been raised
1544 ans = context._raise_error(Overflow, 'above Emax',
1545 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001546 return ans
1547
Facundo Batista353750c2007-09-13 18:13:15 +00001548 # fold down if _clamp == 1 and self has too few digits
1549 if context._clamp == 1 and self._exp > Etop:
1550 context._raise_error(Clamped)
1551 self_padded = self._int + (0,)*(self._exp - Etop)
1552 return Decimal((self._sign, self_padded, Etop))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001553
Facundo Batista353750c2007-09-13 18:13:15 +00001554 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001555 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001556
1557 _pick_rounding_function = {}
1558
Facundo Batista353750c2007-09-13 18:13:15 +00001559 # for each of the rounding functions below:
1560 # self is a finite, nonzero Decimal
1561 # prec is an integer satisfying 0 <= prec < len(self._int)
1562 # the rounded result will have exponent self._exp + len(self._int) - prec;
1563
1564 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001565 """Also known as round-towards-0, truncate."""
Facundo Batista353750c2007-09-13 18:13:15 +00001566 newexp = self._exp + len(self._int) - prec
1567 return Decimal((self._sign, self._int[:prec] or (0,), newexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001568
Facundo Batista353750c2007-09-13 18:13:15 +00001569 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001570 """Rounds away from 0."""
Facundo Batista353750c2007-09-13 18:13:15 +00001571 newexp = self._exp + len(self._int) - prec
1572 tmp = Decimal((self._sign, self._int[:prec] or (0,), newexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001573 for digit in self._int[prec:]:
1574 if digit != 0:
Facundo Batista353750c2007-09-13 18:13:15 +00001575 return tmp._increment()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001576 return tmp
1577
Facundo Batista353750c2007-09-13 18:13:15 +00001578 def _round_half_up(self, prec):
1579 """Rounds 5 up (away from 0)"""
1580 if self._int[prec] >= 5:
1581 return self._round_up(prec)
1582 else:
1583 return self._round_down(prec)
1584
1585 def _round_half_down(self, prec):
1586 """Round 5 down"""
1587 if self._int[prec] == 5:
1588 for digit in self._int[prec+1:]:
1589 if digit != 0:
1590 break
1591 else:
1592 return self._round_down(prec)
1593 return self._round_half_up(prec)
1594
1595 def _round_half_even(self, prec):
1596 """Round 5 to even, rest to nearest."""
1597 if prec and self._int[prec-1] & 1:
1598 return self._round_half_up(prec)
1599 else:
1600 return self._round_half_down(prec)
1601
1602 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001603 """Rounds up (not away from 0 if negative.)"""
1604 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001605 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001606 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001607 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001608
Facundo Batista353750c2007-09-13 18:13:15 +00001609 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001610 """Rounds down (not towards 0 if negative)"""
1611 if not 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_05up(self, prec):
1617 """Round down unless digit prec-1 is 0 or 5."""
1618 if prec == 0 or self._int[prec-1] in (0, 5):
1619 return self._round_up(prec)
1620 else:
1621 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001622
Facundo Batista353750c2007-09-13 18:13:15 +00001623 def fma(self, other, third, context=None):
1624 """Fused multiply-add.
1625
1626 Returns self*other+third with no rounding of the intermediate
1627 product self*other.
1628
1629 self and other are multiplied together, with no rounding of
1630 the result. The third operand is then added to the result,
1631 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001632 """
Facundo Batista353750c2007-09-13 18:13:15 +00001633
1634 other = _convert_other(other, raiseit=True)
1635 third = _convert_other(third, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001636
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001637 if context is None:
1638 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001639
Facundo Batista353750c2007-09-13 18:13:15 +00001640 # do self*other in fresh context with no traps and no rounding
1641 mul_context = Context(traps=[], flags=[],
1642 _rounding_decision=NEVER_ROUND)
1643 product = self.__mul__(other, mul_context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001644
Facundo Batista353750c2007-09-13 18:13:15 +00001645 if mul_context.flags[InvalidOperation]:
1646 # reraise in current context
1647 return context._raise_error(InvalidOperation,
1648 'invalid multiplication in fma',
1649 1, product)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001650
Facundo Batista353750c2007-09-13 18:13:15 +00001651 ans = product.__add__(third, context)
1652 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001653
Facundo Batista353750c2007-09-13 18:13:15 +00001654 def _power_modulo(self, other, modulo, context=None):
1655 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001656
Facundo Batista353750c2007-09-13 18:13:15 +00001657 # if can't convert other and modulo to Decimal, raise
1658 # TypeError; there's no point returning NotImplemented (no
1659 # equivalent of __rpow__ for three argument pow)
1660 other = _convert_other(other, raiseit=True)
1661 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001662
Facundo Batista353750c2007-09-13 18:13:15 +00001663 if context is None:
1664 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001665
Facundo Batista353750c2007-09-13 18:13:15 +00001666 # deal with NaNs: if there are any sNaNs then first one wins,
1667 # (i.e. behaviour for NaNs is identical to that of fma)
1668 self_is_nan = self._isnan()
1669 other_is_nan = other._isnan()
1670 modulo_is_nan = modulo._isnan()
1671 if self_is_nan or other_is_nan or modulo_is_nan:
1672 if self_is_nan == 2:
1673 return context._raise_error(InvalidOperation, 'sNaN',
1674 1, self)
1675 if other_is_nan == 2:
1676 return context._raise_error(InvalidOperation, 'sNaN',
1677 1, other)
1678 if modulo_is_nan == 2:
1679 return context._raise_error(InvalidOperation, 'sNaN',
1680 1, modulo)
1681 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001682 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001683 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001684 return other._fix_nan(context)
1685 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001686
Facundo Batista353750c2007-09-13 18:13:15 +00001687 # check inputs: we apply same restrictions as Python's pow()
1688 if not (self._isinteger() and
1689 other._isinteger() and
1690 modulo._isinteger()):
1691 return context._raise_error(InvalidOperation,
1692 'pow() 3rd argument not allowed '
1693 'unless all arguments are integers')
1694 if other < 0:
1695 return context._raise_error(InvalidOperation,
1696 'pow() 2nd argument cannot be '
1697 'negative when 3rd argument specified')
1698 if not modulo:
1699 return context._raise_error(InvalidOperation,
1700 'pow() 3rd argument cannot be 0')
1701
1702 # additional restriction for decimal: the modulus must be less
1703 # than 10**prec in absolute value
1704 if modulo.adjusted() >= context.prec:
1705 return context._raise_error(InvalidOperation,
1706 'insufficient precision: pow() 3rd '
1707 'argument must not have more than '
1708 'precision digits')
1709
1710 # define 0**0 == NaN, for consistency with two-argument pow
1711 # (even though it hurts!)
1712 if not other and not self:
1713 return context._raise_error(InvalidOperation,
1714 'at least one of pow() 1st argument '
1715 'and 2nd argument must be nonzero ;'
1716 '0**0 is not defined')
1717
1718 # compute sign of result
1719 if other._iseven():
1720 sign = 0
1721 else:
1722 sign = self._sign
1723
1724 # convert modulo to a Python integer, and self and other to
1725 # Decimal integers (i.e. force their exponents to be >= 0)
1726 modulo = abs(int(modulo))
1727 base = _WorkRep(self.to_integral_value())
1728 exponent = _WorkRep(other.to_integral_value())
1729
1730 # compute result using integer pow()
1731 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1732 for i in xrange(exponent.exp):
1733 base = pow(base, 10, modulo)
1734 base = pow(base, exponent.int, modulo)
1735
1736 return Decimal((sign, map(int, str(base)), 0))
1737
1738 def _power_exact(self, other, p):
1739 """Attempt to compute self**other exactly.
1740
1741 Given Decimals self and other and an integer p, attempt to
1742 compute an exact result for the power self**other, with p
1743 digits of precision. Return None if self**other is not
1744 exactly representable in p digits.
1745
1746 Assumes that elimination of special cases has already been
1747 performed: self and other must both be nonspecial; self must
1748 be positive and not numerically equal to 1; other must be
1749 nonzero. For efficiency, other._exp should not be too large,
1750 so that 10**abs(other._exp) is a feasible calculation."""
1751
1752 # In the comments below, we write x for the value of self and
1753 # y for the value of other. Write x = xc*10**xe and y =
1754 # yc*10**ye.
1755
1756 # The main purpose of this method is to identify the *failure*
1757 # of x**y to be exactly representable with as little effort as
1758 # possible. So we look for cheap and easy tests that
1759 # eliminate the possibility of x**y being exact. Only if all
1760 # these tests are passed do we go on to actually compute x**y.
1761
1762 # Here's the main idea. First normalize both x and y. We
1763 # express y as a rational m/n, with m and n relatively prime
1764 # and n>0. Then for x**y to be exactly representable (at
1765 # *any* precision), xc must be the nth power of a positive
1766 # integer and xe must be divisible by n. If m is negative
1767 # then additionally xc must be a power of either 2 or 5, hence
1768 # a power of 2**n or 5**n.
1769 #
1770 # There's a limit to how small |y| can be: if y=m/n as above
1771 # then:
1772 #
1773 # (1) if xc != 1 then for the result to be representable we
1774 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1775 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1776 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1777 # representable.
1778 #
1779 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1780 # |y| < 1/|xe| then the result is not representable.
1781 #
1782 # Note that since x is not equal to 1, at least one of (1) and
1783 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1784 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1785 #
1786 # There's also a limit to how large y can be, at least if it's
1787 # positive: the normalized result will have coefficient xc**y,
1788 # so if it's representable then xc**y < 10**p, and y <
1789 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1790 # not exactly representable.
1791
1792 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1793 # so |y| < 1/xe and the result is not representable.
1794 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1795 # < 1/nbits(xc).
1796
1797 x = _WorkRep(self)
1798 xc, xe = x.int, x.exp
1799 while xc % 10 == 0:
1800 xc //= 10
1801 xe += 1
1802
1803 y = _WorkRep(other)
1804 yc, ye = y.int, y.exp
1805 while yc % 10 == 0:
1806 yc //= 10
1807 ye += 1
1808
1809 # case where xc == 1: result is 10**(xe*y), with xe*y
1810 # required to be an integer
1811 if xc == 1:
1812 if ye >= 0:
1813 exponent = xe*yc*10**ye
1814 else:
1815 exponent, remainder = divmod(xe*yc, 10**-ye)
1816 if remainder:
1817 return None
1818 if y.sign == 1:
1819 exponent = -exponent
1820 # if other is a nonnegative integer, use ideal exponent
1821 if other._isinteger() and other._sign == 0:
1822 ideal_exponent = self._exp*int(other)
1823 zeros = min(exponent-ideal_exponent, p-1)
1824 else:
1825 zeros = 0
1826 return Decimal((0, (1,) + (0,)*zeros, exponent-zeros))
1827
1828 # case where y is negative: xc must be either a power
1829 # of 2 or a power of 5.
1830 if y.sign == 1:
1831 last_digit = xc % 10
1832 if last_digit in (2,4,6,8):
1833 # quick test for power of 2
1834 if xc & -xc != xc:
1835 return None
1836 # now xc is a power of 2; e is its exponent
1837 e = _nbits(xc)-1
1838 # find e*y and xe*y; both must be integers
1839 if ye >= 0:
1840 y_as_int = yc*10**ye
1841 e = e*y_as_int
1842 xe = xe*y_as_int
1843 else:
1844 ten_pow = 10**-ye
1845 e, remainder = divmod(e*yc, ten_pow)
1846 if remainder:
1847 return None
1848 xe, remainder = divmod(xe*yc, ten_pow)
1849 if remainder:
1850 return None
1851
1852 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1853 return None
1854 xc = 5**e
1855
1856 elif last_digit == 5:
1857 # e >= log_5(xc) if xc is a power of 5; we have
1858 # equality all the way up to xc=5**2658
1859 e = _nbits(xc)*28//65
1860 xc, remainder = divmod(5**e, xc)
1861 if remainder:
1862 return None
1863 while xc % 5 == 0:
1864 xc //= 5
1865 e -= 1
1866 if ye >= 0:
1867 y_as_integer = yc*10**ye
1868 e = e*y_as_integer
1869 xe = xe*y_as_integer
1870 else:
1871 ten_pow = 10**-ye
1872 e, remainder = divmod(e*yc, ten_pow)
1873 if remainder:
1874 return None
1875 xe, remainder = divmod(xe*yc, ten_pow)
1876 if remainder:
1877 return None
1878 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1879 return None
1880 xc = 2**e
1881 else:
1882 return None
1883
1884 if xc >= 10**p:
1885 return None
1886 xe = -e-xe
1887 return Decimal((0, map(int, str(xc)), xe))
1888
1889 # now y is positive; find m and n such that y = m/n
1890 if ye >= 0:
1891 m, n = yc*10**ye, 1
1892 else:
1893 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1894 return None
1895 xc_bits = _nbits(xc)
1896 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1897 return None
1898 m, n = yc, 10**(-ye)
1899 while m % 2 == n % 2 == 0:
1900 m //= 2
1901 n //= 2
1902 while m % 5 == n % 5 == 0:
1903 m //= 5
1904 n //= 5
1905
1906 # compute nth root of xc*10**xe
1907 if n > 1:
1908 # if 1 < xc < 2**n then xc isn't an nth power
1909 if xc != 1 and xc_bits <= n:
1910 return None
1911
1912 xe, rem = divmod(xe, n)
1913 if rem != 0:
1914 return None
1915
1916 # compute nth root of xc using Newton's method
1917 a = 1L << -(-_nbits(xc)//n) # initial estimate
1918 while True:
1919 q, r = divmod(xc, a**(n-1))
1920 if a <= q:
1921 break
1922 else:
1923 a = (a*(n-1) + q)//n
1924 if not (a == q and r == 0):
1925 return None
1926 xc = a
1927
1928 # now xc*10**xe is the nth root of the original xc*10**xe
1929 # compute mth power of xc*10**xe
1930
1931 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1932 # 10**p and the result is not representable.
1933 if xc > 1 and m > p*100//_log10_lb(xc):
1934 return None
1935 xc = xc**m
1936 xe *= m
1937 if xc > 10**p:
1938 return None
1939
1940 # by this point the result *is* exactly representable
1941 # adjust the exponent to get as close as possible to the ideal
1942 # exponent, if necessary
1943 str_xc = str(xc)
1944 if other._isinteger() and other._sign == 0:
1945 ideal_exponent = self._exp*int(other)
1946 zeros = min(xe-ideal_exponent, p-len(str_xc))
1947 else:
1948 zeros = 0
1949 return Decimal((0, map(int, str_xc)+[0,]*zeros, xe-zeros))
1950
1951 def __pow__(self, other, modulo=None, context=None):
1952 """Return self ** other [ % modulo].
1953
1954 With two arguments, compute self**other.
1955
1956 With three arguments, compute (self**other) % modulo. For the
1957 three argument form, the following restrictions on the
1958 arguments hold:
1959
1960 - all three arguments must be integral
1961 - other must be nonnegative
1962 - either self or other (or both) must be nonzero
1963 - modulo must be nonzero and must have at most p digits,
1964 where p is the context precision.
1965
1966 If any of these restrictions is violated the InvalidOperation
1967 flag is raised.
1968
1969 The result of pow(self, other, modulo) is identical to the
1970 result that would be obtained by computing (self**other) %
1971 modulo with unbounded precision, but is computed more
1972 efficiently. It is always exact.
1973 """
1974
1975 if modulo is not None:
1976 return self._power_modulo(other, modulo, context)
1977
1978 other = _convert_other(other)
1979 if other is NotImplemented:
1980 return other
1981
1982 if context is None:
1983 context = getcontext()
1984
1985 # either argument is a NaN => result is NaN
1986 ans = self._check_nans(other, context)
1987 if ans:
1988 return ans
1989
1990 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1991 if not other:
1992 if not self:
1993 return context._raise_error(InvalidOperation, '0 ** 0')
1994 else:
1995 return Dec_p1
1996
1997 # result has sign 1 iff self._sign is 1 and other is an odd integer
1998 result_sign = 0
1999 if self._sign == 1:
2000 if other._isinteger():
2001 if not other._iseven():
2002 result_sign = 1
2003 else:
2004 # -ve**noninteger = NaN
2005 # (-0)**noninteger = 0**noninteger
2006 if self:
2007 return context._raise_error(InvalidOperation,
2008 'x ** y with x negative and y not an integer')
2009 # negate self, without doing any unwanted rounding
2010 self = Decimal((0, self._int, self._exp))
2011
2012 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2013 if not self:
2014 if other._sign == 0:
2015 return Decimal((result_sign, (0,), 0))
2016 else:
2017 return Infsign[result_sign]
2018
2019 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002020 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002021 if other._sign == 0:
2022 return Infsign[result_sign]
2023 else:
2024 return Decimal((result_sign, (0,), 0))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002025
Facundo Batista353750c2007-09-13 18:13:15 +00002026 # 1**other = 1, but the choice of exponent and the flags
2027 # depend on the exponent of self, and on whether other is a
2028 # positive integer, a negative integer, or neither
2029 if self == Dec_p1:
2030 if other._isinteger():
2031 # exp = max(self._exp*max(int(other), 0),
2032 # 1-context.prec) but evaluating int(other) directly
2033 # is dangerous until we know other is small (other
2034 # could be 1e999999999)
2035 if other._sign == 1:
2036 multiplier = 0
2037 elif other > context.prec:
2038 multiplier = context.prec
2039 else:
2040 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002041
Facundo Batista353750c2007-09-13 18:13:15 +00002042 exp = self._exp * multiplier
2043 if exp < 1-context.prec:
2044 exp = 1-context.prec
2045 context._raise_error(Rounded)
2046 else:
2047 context._raise_error(Inexact)
2048 context._raise_error(Rounded)
2049 exp = 1-context.prec
2050
2051 return Decimal((result_sign, (1,)+(0,)*-exp, exp))
2052
2053 # compute adjusted exponent of self
2054 self_adj = self.adjusted()
2055
2056 # self ** infinity is infinity if self > 1, 0 if self < 1
2057 # self ** -infinity is infinity if self < 1, 0 if self > 1
2058 if other._isinfinity():
2059 if (other._sign == 0) == (self_adj < 0):
2060 return Decimal((result_sign, (0,), 0))
2061 else:
2062 return Infsign[result_sign]
2063
2064 # from here on, the result always goes through the call
2065 # to _fix at the end of this function.
2066 ans = None
2067
2068 # crude test to catch cases of extreme overflow/underflow. If
2069 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2070 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2071 # self**other >= 10**(Emax+1), so overflow occurs. The test
2072 # for underflow is similar.
2073 bound = self._log10_exp_bound() + other.adjusted()
2074 if (self_adj >= 0) == (other._sign == 0):
2075 # self > 1 and other +ve, or self < 1 and other -ve
2076 # possibility of overflow
2077 if bound >= len(str(context.Emax)):
2078 ans = Decimal((result_sign, (1,), context.Emax+1))
2079 else:
2080 # self > 1 and other -ve, or self < 1 and other +ve
2081 # possibility of underflow to 0
2082 Etiny = context.Etiny()
2083 if bound >= len(str(-Etiny)):
2084 ans = Decimal((result_sign, (1,), Etiny-1))
2085
2086 # try for an exact result with precision +1
2087 if ans is None:
2088 ans = self._power_exact(other, context.prec + 1)
2089 if ans is not None and result_sign == 1:
2090 ans = Decimal((1, ans._int, ans._exp))
2091
2092 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2093 if ans is None:
2094 p = context.prec
2095 x = _WorkRep(self)
2096 xc, xe = x.int, x.exp
2097 y = _WorkRep(other)
2098 yc, ye = y.int, y.exp
2099 if y.sign == 1:
2100 yc = -yc
2101
2102 # compute correctly rounded result: start with precision +3,
2103 # then increase precision until result is unambiguously roundable
2104 extra = 3
2105 while True:
2106 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2107 if coeff % (5*10**(len(str(coeff))-p-1)):
2108 break
2109 extra += 3
2110
2111 ans = Decimal((result_sign, map(int, str(coeff)), exp))
2112
2113 # the specification says that for non-integer other we need to
2114 # raise Inexact, even when the result is actually exact. In
2115 # the same way, we need to raise Underflow here if the result
2116 # is subnormal. (The call to _fix will take care of raising
2117 # Rounded and Subnormal, as usual.)
2118 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002119 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002120 # pad with zeros up to length context.prec+1 if necessary
2121 if len(ans._int) <= context.prec:
2122 expdiff = context.prec+1 - len(ans._int)
2123 ans = Decimal((ans._sign, ans._int+(0,)*expdiff, ans._exp-expdiff))
2124 if ans.adjusted() < context.Emin:
2125 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002126
Facundo Batista353750c2007-09-13 18:13:15 +00002127 # unlike exp, ln and log10, the power function respects the
2128 # rounding mode; no need to use ROUND_HALF_EVEN here
2129 ans = ans._fix(context)
2130 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002131
2132 def __rpow__(self, other, context=None):
2133 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002134 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002135 if other is NotImplemented:
2136 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002137 return other.__pow__(self, context=context)
2138
2139 def normalize(self, context=None):
2140 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002141
Facundo Batista353750c2007-09-13 18:13:15 +00002142 if context is None:
2143 context = getcontext()
2144
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002145 if self._is_special:
2146 ans = self._check_nans(context=context)
2147 if ans:
2148 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002149
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002150 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002151 if dup._isinfinity():
2152 return dup
2153
2154 if not dup:
2155 return Decimal( (dup._sign, (0,), 0) )
Facundo Batista353750c2007-09-13 18:13:15 +00002156 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002157 end = len(dup._int)
2158 exp = dup._exp
Facundo Batista353750c2007-09-13 18:13:15 +00002159 while dup._int[end-1] == 0 and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002160 exp += 1
2161 end -= 1
2162 return Decimal( (dup._sign, dup._int[:end], exp) )
2163
Facundo Batistabd2fe832007-09-13 18:42:09 +00002164 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002165 """Quantize self so its exponent is the same as that of exp.
2166
2167 Similar to self._rescale(exp._exp) but with error checking.
2168 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002169 exp = _convert_other(exp, raiseit=True)
2170
Facundo Batista353750c2007-09-13 18:13:15 +00002171 if context is None:
2172 context = getcontext()
2173 if rounding is None:
2174 rounding = context.rounding
2175
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002176 if self._is_special or exp._is_special:
2177 ans = self._check_nans(exp, context)
2178 if ans:
2179 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002180
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002181 if exp._isinfinity() or self._isinfinity():
2182 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002183 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002184 return context._raise_error(InvalidOperation,
2185 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002186
Facundo Batistabd2fe832007-09-13 18:42:09 +00002187 # if we're not watching exponents, do a simple rescale
2188 if not watchexp:
2189 ans = self._rescale(exp._exp, rounding)
2190 # raise Inexact and Rounded where appropriate
2191 if ans._exp > self._exp:
2192 context._raise_error(Rounded)
2193 if ans != self:
2194 context._raise_error(Inexact)
2195 return ans
2196
Facundo Batista353750c2007-09-13 18:13:15 +00002197 # exp._exp should be between Etiny and Emax
2198 if not (context.Etiny() <= exp._exp <= context.Emax):
2199 return context._raise_error(InvalidOperation,
2200 'target exponent out of bounds in quantize')
2201
2202 if not self:
2203 ans = Decimal((self._sign, (0,), exp._exp))
2204 return ans._fix(context)
2205
2206 self_adjusted = self.adjusted()
2207 if self_adjusted > context.Emax:
2208 return context._raise_error(InvalidOperation,
2209 'exponent of quantize result too large for current context')
2210 if self_adjusted - exp._exp + 1 > context.prec:
2211 return context._raise_error(InvalidOperation,
2212 'quantize result has too many digits for current context')
2213
2214 ans = self._rescale(exp._exp, rounding)
2215 if ans.adjusted() > context.Emax:
2216 return context._raise_error(InvalidOperation,
2217 'exponent of quantize result too large for current context')
2218 if len(ans._int) > context.prec:
2219 return context._raise_error(InvalidOperation,
2220 'quantize result has too many digits for current context')
2221
2222 # raise appropriate flags
2223 if ans._exp > self._exp:
2224 context._raise_error(Rounded)
2225 if ans != self:
2226 context._raise_error(Inexact)
2227 if ans and ans.adjusted() < context.Emin:
2228 context._raise_error(Subnormal)
2229
2230 # call to fix takes care of any necessary folddown
2231 ans = ans._fix(context)
2232 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002233
2234 def same_quantum(self, other):
2235 """Test whether self and other have the same exponent.
2236
2237 same as self._exp == other._exp, except NaN == sNaN
2238 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002239 if self._is_special or other._is_special:
2240 if self._isnan() or other._isnan():
2241 return self._isnan() and other._isnan() and True
2242 if self._isinfinity() or other._isinfinity():
2243 return self._isinfinity() and other._isinfinity() and True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002244 return self._exp == other._exp
2245
Facundo Batista353750c2007-09-13 18:13:15 +00002246 def _rescale(self, exp, rounding):
2247 """Rescale self so that the exponent is exp, either by padding with zeros
2248 or by truncating digits, using the given rounding mode.
2249
2250 Specials are returned without change. This operation is
2251 quiet: it raises no flags, and uses no information from the
2252 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002253
2254 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002255 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002256 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002257 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002258 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002259 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002260 return Decimal((self._sign, (0,), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002261
Facundo Batista353750c2007-09-13 18:13:15 +00002262 if self._exp >= exp:
2263 # pad answer with zeros if necessary
2264 return Decimal((self._sign, self._int + (0,)*(self._exp - exp), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002265
Facundo Batista353750c2007-09-13 18:13:15 +00002266 # too many digits; round and lose data. If self.adjusted() <
2267 # exp-1, replace self by 10**(exp-1) before rounding
2268 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002269 if digits < 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002270 self = Decimal((self._sign, (1,), exp-1))
2271 digits = 0
2272 this_function = getattr(self, self._pick_rounding_function[rounding])
2273 return this_function(digits)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002274
Facundo Batista353750c2007-09-13 18:13:15 +00002275 def to_integral_exact(self, rounding=None, context=None):
2276 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002277
Facundo Batista353750c2007-09-13 18:13:15 +00002278 If no rounding mode is specified, take the rounding mode from
2279 the context. This method raises the Rounded and Inexact flags
2280 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002281
Facundo Batista353750c2007-09-13 18:13:15 +00002282 See also: to_integral_value, which does exactly the same as
2283 this method except that it doesn't raise Inexact or Rounded.
2284 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002285 if self._is_special:
2286 ans = self._check_nans(context=context)
2287 if ans:
2288 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002289 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002290 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002291 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002292 if not self:
2293 return Decimal((self._sign, (0,), 0))
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002294 if context is None:
2295 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002296 if rounding is None:
2297 rounding = context.rounding
2298 context._raise_error(Rounded)
2299 ans = self._rescale(0, rounding)
2300 if ans != self:
2301 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002302 return ans
2303
Facundo Batista353750c2007-09-13 18:13:15 +00002304 def to_integral_value(self, rounding=None, context=None):
2305 """Rounds to the nearest integer, without raising inexact, rounded."""
2306 if context is None:
2307 context = getcontext()
2308 if rounding is None:
2309 rounding = context.rounding
2310 if self._is_special:
2311 ans = self._check_nans(context=context)
2312 if ans:
2313 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002314 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002315 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002316 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002317 else:
2318 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002319
Facundo Batista353750c2007-09-13 18:13:15 +00002320 # the method name changed, but we provide also the old one, for compatibility
2321 to_integral = to_integral_value
2322
2323 def sqrt(self, context=None):
2324 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002325 if self._is_special:
2326 ans = self._check_nans(context=context)
2327 if ans:
2328 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002329
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002330 if self._isinfinity() and self._sign == 0:
2331 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002332
2333 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002334 # exponent = self._exp // 2. sqrt(-0) = -0
2335 ans = Decimal((self._sign, (0,), self._exp // 2))
2336 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002337
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002338 if context is None:
2339 context = getcontext()
2340
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002341 if self._sign == 1:
2342 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2343
Facundo Batista353750c2007-09-13 18:13:15 +00002344 # At this point self represents a positive number. Let p be
2345 # the desired precision and express self in the form c*100**e
2346 # with c a positive real number and e an integer, c and e
2347 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2348 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2349 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2350 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2351 # the closest integer to sqrt(c) with the even integer chosen
2352 # in the case of a tie.
2353 #
2354 # To ensure correct rounding in all cases, we use the
2355 # following trick: we compute the square root to an extra
2356 # place (precision p+1 instead of precision p), rounding down.
2357 # Then, if the result is inexact and its last digit is 0 or 5,
2358 # we increase the last digit to 1 or 6 respectively; if it's
2359 # exact we leave the last digit alone. Now the final round to
2360 # p places (or fewer in the case of underflow) will round
2361 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002362
Facundo Batista353750c2007-09-13 18:13:15 +00002363 # use an extra digit of precision
2364 prec = context.prec+1
2365
2366 # write argument in the form c*100**e where e = self._exp//2
2367 # is the 'ideal' exponent, to be used if the square root is
2368 # exactly representable. l is the number of 'digits' of c in
2369 # base 100, so that 100**(l-1) <= c < 100**l.
2370 op = _WorkRep(self)
2371 e = op.exp >> 1
2372 if op.exp & 1:
2373 c = op.int * 10
2374 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002375 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002376 c = op.int
2377 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002378
Facundo Batista353750c2007-09-13 18:13:15 +00002379 # rescale so that c has exactly prec base 100 'digits'
2380 shift = prec-l
2381 if shift >= 0:
2382 c *= 100**shift
2383 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002384 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002385 c, remainder = divmod(c, 100**-shift)
2386 exact = not remainder
2387 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002388
Facundo Batista353750c2007-09-13 18:13:15 +00002389 # find n = floor(sqrt(c)) using Newton's method
2390 n = 10**prec
2391 while True:
2392 q = c//n
2393 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002394 break
Facundo Batista353750c2007-09-13 18:13:15 +00002395 else:
2396 n = n + q >> 1
2397 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002398
Facundo Batista353750c2007-09-13 18:13:15 +00002399 if exact:
2400 # result is exact; rescale to use ideal exponent e
2401 if shift >= 0:
2402 # assert n % 10**shift == 0
2403 n //= 10**shift
2404 else:
2405 n *= 10**-shift
2406 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002407 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002408 # result is not exact; fix last digit as described above
2409 if n % 5 == 0:
2410 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002411
Facundo Batista353750c2007-09-13 18:13:15 +00002412 ans = Decimal((0, map(int, str(n)), e))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002413
Facundo Batista353750c2007-09-13 18:13:15 +00002414 # round, and fit to current context
2415 context = context._shallow_copy()
2416 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002417 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002418 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002419
Facundo Batista353750c2007-09-13 18:13:15 +00002420 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002421
2422 def max(self, other, context=None):
2423 """Returns the larger value.
2424
Facundo Batista353750c2007-09-13 18:13:15 +00002425 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002426 NaN (and signals if one is sNaN). Also rounds.
2427 """
Facundo Batista353750c2007-09-13 18:13:15 +00002428 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002429
Facundo Batista6c398da2007-09-17 17:30:13 +00002430 if context is None:
2431 context = getcontext()
2432
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002433 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002434 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002435 # number is always returned
2436 sn = self._isnan()
2437 on = other._isnan()
2438 if sn or on:
2439 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002440 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002441 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002442 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002443 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002444
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002445 c = self.__cmp__(other)
2446 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002447 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002448 # then an ordering is applied:
2449 #
Facundo Batista59c58842007-04-10 12:58:45 +00002450 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002451 # positive sign and min returns the operand with the negative sign
2452 #
Facundo Batista59c58842007-04-10 12:58:45 +00002453 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002454 # the result. This is exactly the ordering used in compare_total.
2455 c = self.compare_total(other)
2456
2457 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002458 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002459 else:
2460 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002461
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002462 if context._rounding_decision == ALWAYS_ROUND:
2463 return ans._fix(context)
2464 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002465
2466 def min(self, other, context=None):
2467 """Returns the smaller value.
2468
Facundo Batista59c58842007-04-10 12:58:45 +00002469 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002470 NaN (and signals if one is sNaN). Also rounds.
2471 """
Facundo Batista353750c2007-09-13 18:13:15 +00002472 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002473
Facundo Batista6c398da2007-09-17 17:30:13 +00002474 if context is None:
2475 context = getcontext()
2476
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002477 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002478 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002479 # number is always returned
2480 sn = self._isnan()
2481 on = other._isnan()
2482 if sn or on:
2483 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002484 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002485 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002486 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002487 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002488
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002489 c = self.__cmp__(other)
2490 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002491 c = self.compare_total(other)
2492
2493 if c == -1:
2494 ans = self
2495 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002496 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002497
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002498 if context._rounding_decision == ALWAYS_ROUND:
2499 return ans._fix(context)
2500 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002501
2502 def _isinteger(self):
2503 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002504 if self._is_special:
2505 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002506 if self._exp >= 0:
2507 return True
2508 rest = self._int[self._exp:]
2509 return rest == (0,)*len(rest)
2510
2511 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002512 """Returns True if self is even. Assumes self is an integer."""
2513 if not self or self._exp > 0:
2514 return True
Raymond Hettinger61992ef2004-08-06 23:42:16 +00002515 return self._int[-1+self._exp] & 1 == 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002516
2517 def adjusted(self):
2518 """Return the adjusted exponent of self"""
2519 try:
2520 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002521 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002522 except TypeError:
2523 return 0
2524
Facundo Batista353750c2007-09-13 18:13:15 +00002525 def canonical(self, context=None):
2526 """Returns the same Decimal object.
2527
2528 As we do not have different encodings for the same number, the
2529 received object already is in its canonical form.
2530 """
2531 return self
2532
2533 def compare_signal(self, other, context=None):
2534 """Compares self to the other operand numerically.
2535
2536 It's pretty much like compare(), but all NaNs signal, with signaling
2537 NaNs taking precedence over quiet NaNs.
2538 """
2539 if context is None:
2540 context = getcontext()
2541
2542 self_is_nan = self._isnan()
2543 other_is_nan = other._isnan()
2544 if self_is_nan == 2:
2545 return context._raise_error(InvalidOperation, 'sNaN',
2546 1, self)
2547 if other_is_nan == 2:
2548 return context._raise_error(InvalidOperation, 'sNaN',
2549 1, other)
2550 if self_is_nan:
2551 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2552 1, self)
2553 if other_is_nan:
2554 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2555 1, other)
2556 return self.compare(other, context=context)
2557
2558 def compare_total(self, other):
2559 """Compares self to other using the abstract representations.
2560
2561 This is not like the standard compare, which use their numerical
2562 value. Note that a total ordering is defined for all possible abstract
2563 representations.
2564 """
2565 # if one is negative and the other is positive, it's easy
2566 if self._sign and not other._sign:
2567 return Dec_n1
2568 if not self._sign and other._sign:
2569 return Dec_p1
2570 sign = self._sign
2571
2572 # let's handle both NaN types
2573 self_nan = self._isnan()
2574 other_nan = other._isnan()
2575 if self_nan or other_nan:
2576 if self_nan == other_nan:
2577 if self._int < other._int:
2578 if sign:
2579 return Dec_p1
2580 else:
2581 return Dec_n1
2582 if self._int > other._int:
2583 if sign:
2584 return Dec_n1
2585 else:
2586 return Dec_p1
2587 return Dec_0
2588
2589 if sign:
2590 if self_nan == 1:
2591 return Dec_n1
2592 if other_nan == 1:
2593 return Dec_p1
2594 if self_nan == 2:
2595 return Dec_n1
2596 if other_nan == 2:
2597 return Dec_p1
2598 else:
2599 if self_nan == 1:
2600 return Dec_p1
2601 if other_nan == 1:
2602 return Dec_n1
2603 if self_nan == 2:
2604 return Dec_p1
2605 if other_nan == 2:
2606 return Dec_n1
2607
2608 if self < other:
2609 return Dec_n1
2610 if self > other:
2611 return Dec_p1
2612
2613 if self._exp < other._exp:
2614 if sign:
2615 return Dec_p1
2616 else:
2617 return Dec_n1
2618 if self._exp > other._exp:
2619 if sign:
2620 return Dec_n1
2621 else:
2622 return Dec_p1
2623 return Dec_0
2624
2625
2626 def compare_total_mag(self, other):
2627 """Compares self to other using abstract repr., ignoring sign.
2628
2629 Like compare_total, but with operand's sign ignored and assumed to be 0.
2630 """
2631 s = self.copy_abs()
2632 o = other.copy_abs()
2633 return s.compare_total(o)
2634
2635 def copy_abs(self):
2636 """Returns a copy with the sign set to 0. """
2637 return Decimal((0, self._int, self._exp))
2638
2639 def copy_negate(self):
2640 """Returns a copy with the sign inverted."""
2641 if self._sign:
2642 return Decimal((0, self._int, self._exp))
2643 else:
2644 return Decimal((1, self._int, self._exp))
2645
2646 def copy_sign(self, other):
2647 """Returns self with the sign of other."""
2648 return Decimal((other._sign, self._int, self._exp))
2649
2650 def exp(self, context=None):
2651 """Returns e ** self."""
2652
2653 if context is None:
2654 context = getcontext()
2655
2656 # exp(NaN) = NaN
2657 ans = self._check_nans(context=context)
2658 if ans:
2659 return ans
2660
2661 # exp(-Infinity) = 0
2662 if self._isinfinity() == -1:
2663 return Dec_0
2664
2665 # exp(0) = 1
2666 if not self:
2667 return Dec_p1
2668
2669 # exp(Infinity) = Infinity
2670 if self._isinfinity() == 1:
2671 return Decimal(self)
2672
2673 # the result is now guaranteed to be inexact (the true
2674 # mathematical result is transcendental). There's no need to
2675 # raise Rounded and Inexact here---they'll always be raised as
2676 # a result of the call to _fix.
2677 p = context.prec
2678 adj = self.adjusted()
2679
2680 # we only need to do any computation for quite a small range
2681 # of adjusted exponents---for example, -29 <= adj <= 10 for
2682 # the default context. For smaller exponent the result is
2683 # indistinguishable from 1 at the given precision, while for
2684 # larger exponent the result either overflows or underflows.
2685 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2686 # overflow
2687 ans = Decimal((0, (1,), context.Emax+1))
2688 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2689 # underflow to 0
2690 ans = Decimal((0, (1,), context.Etiny()-1))
2691 elif self._sign == 0 and adj < -p:
2692 # p+1 digits; final round will raise correct flags
2693 ans = Decimal((0, (1,) + (0,)*(p-1) + (1,), -p))
2694 elif self._sign == 1 and adj < -p-1:
2695 # p+1 digits; final round will raise correct flags
2696 ans = Decimal((0, (9,)*(p+1), -p-1))
2697 # general case
2698 else:
2699 op = _WorkRep(self)
2700 c, e = op.int, op.exp
2701 if op.sign == 1:
2702 c = -c
2703
2704 # compute correctly rounded result: increase precision by
2705 # 3 digits at a time until we get an unambiguously
2706 # roundable result
2707 extra = 3
2708 while True:
2709 coeff, exp = _dexp(c, e, p+extra)
2710 if coeff % (5*10**(len(str(coeff))-p-1)):
2711 break
2712 extra += 3
2713
2714 ans = Decimal((0, map(int, str(coeff)), exp))
2715
2716 # at this stage, ans should round correctly with *any*
2717 # rounding mode, not just with ROUND_HALF_EVEN
2718 context = context._shallow_copy()
2719 rounding = context._set_rounding(ROUND_HALF_EVEN)
2720 ans = ans._fix(context)
2721 context.rounding = rounding
2722
2723 return ans
2724
2725 def is_canonical(self):
2726 """Returns 1 if self is canonical; otherwise returns 0."""
2727 return Dec_p1
2728
2729 def is_finite(self):
2730 """Returns 1 if self is finite, otherwise returns 0.
2731
2732 For it to be finite, it must be neither infinite nor a NaN.
2733 """
2734 if self._is_special:
2735 return Dec_0
2736 else:
2737 return Dec_p1
2738
2739 def is_infinite(self):
2740 """Returns 1 if self is an Infinite, otherwise returns 0."""
2741 if self._isinfinity():
2742 return Dec_p1
2743 else:
2744 return Dec_0
2745
2746 def is_nan(self):
2747 """Returns 1 if self is qNaN or sNaN, otherwise returns 0."""
2748 if self._isnan():
2749 return Dec_p1
2750 else:
2751 return Dec_0
2752
2753 def is_normal(self, context=None):
2754 """Returns 1 if self is a normal number, otherwise returns 0."""
2755 if self._is_special:
2756 return Dec_0
2757 if not self:
2758 return Dec_0
2759 if context is None:
2760 context = getcontext()
2761 if context.Emin <= self.adjusted() <= context.Emax:
2762 return Dec_p1
2763 else:
2764 return Dec_0
2765
2766 def is_qnan(self):
2767 """Returns 1 if self is a quiet NaN, otherwise returns 0."""
2768 if self._isnan() == 1:
2769 return Dec_p1
2770 else:
2771 return Dec_0
2772
2773 def is_signed(self):
2774 """Returns 1 if self is negative, otherwise returns 0."""
2775 return Decimal(self._sign)
2776
2777 def is_snan(self):
2778 """Returns 1 if self is a signaling NaN, otherwise returns 0."""
2779 if self._isnan() == 2:
2780 return Dec_p1
2781 else:
2782 return Dec_0
2783
2784 def is_subnormal(self, context=None):
2785 """Returns 1 if self is subnormal, otherwise returns 0."""
2786 if self._is_special:
2787 return Dec_0
2788 if not self:
2789 return Dec_0
2790 if context is None:
2791 context = getcontext()
2792
2793 r = self._exp + len(self._int)
2794 if r <= context.Emin:
2795 return Dec_p1
2796 return Dec_0
2797
2798 def is_zero(self):
2799 """Returns 1 if self is a zero, otherwise returns 0."""
2800 if self:
2801 return Dec_0
2802 else:
2803 return Dec_p1
2804
2805 def _ln_exp_bound(self):
2806 """Compute a lower bound for the adjusted exponent of self.ln().
2807 In other words, compute r such that self.ln() >= 10**r. Assumes
2808 that self is finite and positive and that self != 1.
2809 """
2810
2811 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2812 adj = self._exp + len(self._int) - 1
2813 if adj >= 1:
2814 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2815 return len(str(adj*23//10)) - 1
2816 if adj <= -2:
2817 # argument <= 0.1
2818 return len(str((-1-adj)*23//10)) - 1
2819 op = _WorkRep(self)
2820 c, e = op.int, op.exp
2821 if adj == 0:
2822 # 1 < self < 10
2823 num = str(c-10**-e)
2824 den = str(c)
2825 return len(num) - len(den) - (num < den)
2826 # adj == -1, 0.1 <= self < 1
2827 return e + len(str(10**-e - c)) - 1
2828
2829
2830 def ln(self, context=None):
2831 """Returns the natural (base e) logarithm of self."""
2832
2833 if context is None:
2834 context = getcontext()
2835
2836 # ln(NaN) = NaN
2837 ans = self._check_nans(context=context)
2838 if ans:
2839 return ans
2840
2841 # ln(0.0) == -Infinity
2842 if not self:
2843 return negInf
2844
2845 # ln(Infinity) = Infinity
2846 if self._isinfinity() == 1:
2847 return Inf
2848
2849 # ln(1.0) == 0.0
2850 if self == Dec_p1:
2851 return Dec_0
2852
2853 # ln(negative) raises InvalidOperation
2854 if self._sign == 1:
2855 return context._raise_error(InvalidOperation,
2856 'ln of a negative value')
2857
2858 # result is irrational, so necessarily inexact
2859 op = _WorkRep(self)
2860 c, e = op.int, op.exp
2861 p = context.prec
2862
2863 # correctly rounded result: repeatedly increase precision by 3
2864 # until we get an unambiguously roundable result
2865 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2866 while True:
2867 coeff = _dlog(c, e, places)
2868 # assert len(str(abs(coeff)))-p >= 1
2869 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2870 break
2871 places += 3
2872 ans = Decimal((int(coeff<0), map(int, str(abs(coeff))), -places))
2873
2874 context = context._shallow_copy()
2875 rounding = context._set_rounding(ROUND_HALF_EVEN)
2876 ans = ans._fix(context)
2877 context.rounding = rounding
2878 return ans
2879
2880 def _log10_exp_bound(self):
2881 """Compute a lower bound for the adjusted exponent of self.log10().
2882 In other words, find r such that self.log10() >= 10**r.
2883 Assumes that self is finite and positive and that self != 1.
2884 """
2885
2886 # For x >= 10 or x < 0.1 we only need a bound on the integer
2887 # part of log10(self), and this comes directly from the
2888 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2889 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2890 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2891
2892 adj = self._exp + len(self._int) - 1
2893 if adj >= 1:
2894 # self >= 10
2895 return len(str(adj))-1
2896 if adj <= -2:
2897 # self < 0.1
2898 return len(str(-1-adj))-1
2899 op = _WorkRep(self)
2900 c, e = op.int, op.exp
2901 if adj == 0:
2902 # 1 < self < 10
2903 num = str(c-10**-e)
2904 den = str(231*c)
2905 return len(num) - len(den) - (num < den) + 2
2906 # adj == -1, 0.1 <= self < 1
2907 num = str(10**-e-c)
2908 return len(num) + e - (num < "231") - 1
2909
2910 def log10(self, context=None):
2911 """Returns the base 10 logarithm of self."""
2912
2913 if context is None:
2914 context = getcontext()
2915
2916 # log10(NaN) = NaN
2917 ans = self._check_nans(context=context)
2918 if ans:
2919 return ans
2920
2921 # log10(0.0) == -Infinity
2922 if not self:
2923 return negInf
2924
2925 # log10(Infinity) = Infinity
2926 if self._isinfinity() == 1:
2927 return Inf
2928
2929 # log10(negative or -Infinity) raises InvalidOperation
2930 if self._sign == 1:
2931 return context._raise_error(InvalidOperation,
2932 'log10 of a negative value')
2933
2934 # log10(10**n) = n
2935 if self._int[0] == 1 and self._int[1:] == (0,)*(len(self._int) - 1):
2936 # answer may need rounding
2937 ans = Decimal(self._exp + len(self._int) - 1)
2938 else:
2939 # result is irrational, so necessarily inexact
2940 op = _WorkRep(self)
2941 c, e = op.int, op.exp
2942 p = context.prec
2943
2944 # correctly rounded result: repeatedly increase precision
2945 # until result is unambiguously roundable
2946 places = p-self._log10_exp_bound()+2
2947 while True:
2948 coeff = _dlog10(c, e, places)
2949 # assert len(str(abs(coeff)))-p >= 1
2950 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2951 break
2952 places += 3
2953 ans = Decimal((int(coeff<0), map(int, str(abs(coeff))), -places))
2954
2955 context = context._shallow_copy()
2956 rounding = context._set_rounding(ROUND_HALF_EVEN)
2957 ans = ans._fix(context)
2958 context.rounding = rounding
2959 return ans
2960
2961 def logb(self, context=None):
2962 """ Returns the exponent of the magnitude of self's MSD.
2963
2964 The result is the integer which is the exponent of the magnitude
2965 of the most significant digit of self (as though it were truncated
2966 to a single digit while maintaining the value of that digit and
2967 without limiting the resulting exponent).
2968 """
2969 # logb(NaN) = NaN
2970 ans = self._check_nans(context=context)
2971 if ans:
2972 return ans
2973
2974 if context is None:
2975 context = getcontext()
2976
2977 # logb(+/-Inf) = +Inf
2978 if self._isinfinity():
2979 return Inf
2980
2981 # logb(0) = -Inf, DivisionByZero
2982 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00002983 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00002984
2985 # otherwise, simply return the adjusted exponent of self, as a
2986 # Decimal. Note that no attempt is made to fit the result
2987 # into the current context.
2988 return Decimal(self.adjusted())
2989
2990 def _islogical(self):
2991 """Return True if self is a logical operand.
2992
2993 For being logical, it must be a finite numbers with a sign of 0,
2994 an exponent of 0, and a coefficient whose digits must all be
2995 either 0 or 1.
2996 """
2997 if self._sign != 0 or self._exp != 0:
2998 return False
2999 for dig in self._int:
3000 if dig not in (0, 1):
3001 return False
3002 return True
3003
3004 def _fill_logical(self, context, opa, opb):
3005 dif = context.prec - len(opa)
3006 if dif > 0:
3007 opa = (0,)*dif + opa
3008 elif dif < 0:
3009 opa = opa[-context.prec:]
3010 dif = context.prec - len(opb)
3011 if dif > 0:
3012 opb = (0,)*dif + opb
3013 elif dif < 0:
3014 opb = opb[-context.prec:]
3015 return opa, opb
3016
3017 def logical_and(self, other, context=None):
3018 """Applies an 'and' operation between self and other's digits."""
3019 if context is None:
3020 context = getcontext()
3021 if not self._islogical() or not other._islogical():
3022 return context._raise_error(InvalidOperation)
3023
3024 # fill to context.prec
3025 (opa, opb) = self._fill_logical(context, self._int, other._int)
3026
3027 # make the operation, and clean starting zeroes
3028 result = [a&b for a,b in zip(opa,opb)]
3029 for i,d in enumerate(result):
3030 if d == 1:
3031 break
3032 result = tuple(result[i:])
3033
3034 # if empty, we must have at least a zero
3035 if not result:
3036 result = (0,)
3037 return Decimal((0, result, 0))
3038
3039 def logical_invert(self, context=None):
3040 """Invert all its digits."""
3041 if context is None:
3042 context = getcontext()
3043 return self.logical_xor(Decimal((0,(1,)*context.prec,0)), context)
3044
3045 def logical_or(self, other, context=None):
3046 """Applies an 'or' operation between self and other's digits."""
3047 if context is None:
3048 context = getcontext()
3049 if not self._islogical() or not other._islogical():
3050 return context._raise_error(InvalidOperation)
3051
3052 # fill to context.prec
3053 (opa, opb) = self._fill_logical(context, self._int, other._int)
3054
3055 # make the operation, and clean starting zeroes
3056 result = [a|b for a,b in zip(opa,opb)]
3057 for i,d in enumerate(result):
3058 if d == 1:
3059 break
3060 result = tuple(result[i:])
3061
3062 # if empty, we must have at least a zero
3063 if not result:
3064 result = (0,)
3065 return Decimal((0, result, 0))
3066
3067 def logical_xor(self, other, context=None):
3068 """Applies an 'xor' operation between self and other's digits."""
3069 if context is None:
3070 context = getcontext()
3071 if not self._islogical() or not other._islogical():
3072 return context._raise_error(InvalidOperation)
3073
3074 # fill to context.prec
3075 (opa, opb) = self._fill_logical(context, self._int, other._int)
3076
3077 # make the operation, and clean starting zeroes
3078 result = [a^b for a,b in zip(opa,opb)]
3079 for i,d in enumerate(result):
3080 if d == 1:
3081 break
3082 result = tuple(result[i:])
3083
3084 # if empty, we must have at least a zero
3085 if not result:
3086 result = (0,)
3087 return Decimal((0, result, 0))
3088
3089 def max_mag(self, other, context=None):
3090 """Compares the values numerically with their sign ignored."""
3091 other = _convert_other(other, raiseit=True)
3092
Facundo Batista6c398da2007-09-17 17:30:13 +00003093 if context is None:
3094 context = getcontext()
3095
Facundo Batista353750c2007-09-13 18:13:15 +00003096 if self._is_special or other._is_special:
3097 # If one operand is a quiet NaN and the other is number, then the
3098 # number is always returned
3099 sn = self._isnan()
3100 on = other._isnan()
3101 if sn or on:
3102 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003103 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003104 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003105 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003106 return self._check_nans(other, context)
3107
3108 c = self.copy_abs().__cmp__(other.copy_abs())
3109 if c == 0:
3110 c = self.compare_total(other)
3111
3112 if c == -1:
3113 ans = other
3114 else:
3115 ans = self
3116
Facundo Batista353750c2007-09-13 18:13:15 +00003117 if context._rounding_decision == ALWAYS_ROUND:
3118 return ans._fix(context)
3119 return ans
3120
3121 def min_mag(self, other, context=None):
3122 """Compares the values numerically with their sign ignored."""
3123 other = _convert_other(other, raiseit=True)
3124
Facundo Batista6c398da2007-09-17 17:30:13 +00003125 if context is None:
3126 context = getcontext()
3127
Facundo Batista353750c2007-09-13 18:13:15 +00003128 if self._is_special or other._is_special:
3129 # If one operand is a quiet NaN and the other is number, then the
3130 # number is always returned
3131 sn = self._isnan()
3132 on = other._isnan()
3133 if sn or on:
3134 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003135 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003136 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003137 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003138 return self._check_nans(other, context)
3139
3140 c = self.copy_abs().__cmp__(other.copy_abs())
3141 if c == 0:
3142 c = self.compare_total(other)
3143
3144 if c == -1:
3145 ans = self
3146 else:
3147 ans = other
3148
Facundo Batista353750c2007-09-13 18:13:15 +00003149 if context._rounding_decision == ALWAYS_ROUND:
3150 return ans._fix(context)
3151 return ans
3152
3153 def next_minus(self, context=None):
3154 """Returns the largest representable number smaller than itself."""
3155 if context is None:
3156 context = getcontext()
3157
3158 ans = self._check_nans(context=context)
3159 if ans:
3160 return ans
3161
3162 if self._isinfinity() == -1:
3163 return negInf
3164 if self._isinfinity() == 1:
3165 return Decimal((0, (9,)*context.prec, context.Etop()))
3166
3167 context = context.copy()
3168 context._set_rounding(ROUND_FLOOR)
3169 context._ignore_all_flags()
3170 new_self = self._fix(context)
3171 if new_self != self:
3172 return new_self
3173 return self.__sub__(Decimal((0, (1,), context.Etiny()-1)), context)
3174
3175 def next_plus(self, context=None):
3176 """Returns the smallest representable number larger than itself."""
3177 if context is None:
3178 context = getcontext()
3179
3180 ans = self._check_nans(context=context)
3181 if ans:
3182 return ans
3183
3184 if self._isinfinity() == 1:
3185 return Inf
3186 if self._isinfinity() == -1:
3187 return Decimal((1, (9,)*context.prec, context.Etop()))
3188
3189 context = context.copy()
3190 context._set_rounding(ROUND_CEILING)
3191 context._ignore_all_flags()
3192 new_self = self._fix(context)
3193 if new_self != self:
3194 return new_self
3195 return self.__add__(Decimal((0, (1,), context.Etiny()-1)), context)
3196
3197 def next_toward(self, other, context=None):
3198 """Returns the number closest to self, in the direction towards other.
3199
3200 The result is the closest representable number to self
3201 (excluding self) that is in the direction towards other,
3202 unless both have the same value. If the two operands are
3203 numerically equal, then the result is a copy of self with the
3204 sign set to be the same as the sign of other.
3205 """
3206 other = _convert_other(other, raiseit=True)
3207
3208 if context is None:
3209 context = getcontext()
3210
3211 ans = self._check_nans(other, context)
3212 if ans:
3213 return ans
3214
3215 comparison = self.__cmp__(other)
3216 if comparison == 0:
3217 return Decimal((other._sign, self._int, self._exp))
3218
3219 if comparison == -1:
3220 ans = self.next_plus(context)
3221 else: # comparison == 1
3222 ans = self.next_minus(context)
3223
3224 # decide which flags to raise using value of ans
3225 if ans._isinfinity():
3226 context._raise_error(Overflow,
3227 'Infinite result from next_toward',
3228 ans._sign)
3229 context._raise_error(Rounded)
3230 context._raise_error(Inexact)
3231 elif ans.adjusted() < context.Emin:
3232 context._raise_error(Underflow)
3233 context._raise_error(Subnormal)
3234 context._raise_error(Rounded)
3235 context._raise_error(Inexact)
3236 # if precision == 1 then we don't raise Clamped for a
3237 # result 0E-Etiny.
3238 if not ans:
3239 context._raise_error(Clamped)
3240
3241 return ans
3242
3243 def number_class(self, context=None):
3244 """Returns an indication of the class of self.
3245
3246 The class is one of the following strings:
3247 -sNaN
3248 -NaN
3249 -Infinity
3250 -Normal
3251 -Subnormal
3252 -Zero
3253 +Zero
3254 +Subnormal
3255 +Normal
3256 +Infinity
3257 """
3258 if self.is_snan():
3259 return "sNaN"
3260 if self.is_qnan():
3261 return "NaN"
3262 inf = self._isinfinity()
3263 if inf == 1:
3264 return "+Infinity"
3265 if inf == -1:
3266 return "-Infinity"
3267 if self.is_zero():
3268 if self._sign:
3269 return "-Zero"
3270 else:
3271 return "+Zero"
3272 if context is None:
3273 context = getcontext()
3274 if self.is_subnormal(context=context):
3275 if self._sign:
3276 return "-Subnormal"
3277 else:
3278 return "+Subnormal"
3279 # just a normal, regular, boring number, :)
3280 if self._sign:
3281 return "-Normal"
3282 else:
3283 return "+Normal"
3284
3285 def radix(self):
3286 """Just returns 10, as this is Decimal, :)"""
3287 return Decimal(10)
3288
3289 def rotate(self, other, context=None):
3290 """Returns a rotated copy of self, value-of-other times."""
3291 if context is None:
3292 context = getcontext()
3293
3294 ans = self._check_nans(other, context)
3295 if ans:
3296 return ans
3297
3298 if other._exp != 0:
3299 return context._raise_error(InvalidOperation)
3300 if not (-context.prec <= int(other) <= context.prec):
3301 return context._raise_error(InvalidOperation)
3302
3303 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003304 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003305
3306 # get values, pad if necessary
3307 torot = int(other)
3308 rotdig = self._int
3309 topad = context.prec - len(rotdig)
3310 if topad:
3311 rotdig = ((0,)*topad) + rotdig
3312
3313 # let's rotate!
3314 rotated = rotdig[torot:] + rotdig[:torot]
3315
3316 # clean starting zeroes
3317 for i,d in enumerate(rotated):
3318 if d != 0:
3319 break
3320 rotated = rotated[i:]
3321
3322 return Decimal((self._sign, rotated, self._exp))
3323
3324
3325 def scaleb (self, other, context=None):
3326 """Returns self operand after adding the second value to its exp."""
3327 if context is None:
3328 context = getcontext()
3329
3330 ans = self._check_nans(other, context)
3331 if ans:
3332 return ans
3333
3334 if other._exp != 0:
3335 return context._raise_error(InvalidOperation)
3336 liminf = -2 * (context.Emax + context.prec)
3337 limsup = 2 * (context.Emax + context.prec)
3338 if not (liminf <= int(other) <= limsup):
3339 return context._raise_error(InvalidOperation)
3340
3341 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003342 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003343
3344 d = Decimal((self._sign, self._int, self._exp + int(other)))
3345 d = d._fix(context)
3346 return d
3347
3348 def shift(self, other, context=None):
3349 """Returns a shifted copy of self, value-of-other times."""
3350 if context is None:
3351 context = getcontext()
3352
3353 ans = self._check_nans(other, context)
3354 if ans:
3355 return ans
3356
3357 if other._exp != 0:
3358 return context._raise_error(InvalidOperation)
3359 if not (-context.prec <= int(other) <= context.prec):
3360 return context._raise_error(InvalidOperation)
3361
3362 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003363 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003364
3365 # get values, pad if necessary
3366 torot = int(other)
3367 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003368 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003369 rotdig = self._int
3370 topad = context.prec - len(rotdig)
3371 if topad:
3372 rotdig = ((0,)*topad) + rotdig
3373
3374 # let's shift!
3375 if torot < 0:
3376 rotated = rotdig[:torot]
3377 else:
3378 rotated = (rotdig + ((0,) * torot))
3379 rotated = rotated[-context.prec:]
3380
3381 # clean starting zeroes
3382 if rotated:
3383 for i,d in enumerate(rotated):
3384 if d != 0:
3385 break
3386 rotated = rotated[i:]
3387 else:
3388 rotated = (0,)
3389
3390 return Decimal((self._sign, rotated, self._exp))
3391
3392
Facundo Batista59c58842007-04-10 12:58:45 +00003393 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003394 def __reduce__(self):
3395 return (self.__class__, (str(self),))
3396
3397 def __copy__(self):
3398 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003399 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003400 return self.__class__(str(self))
3401
3402 def __deepcopy__(self, memo):
3403 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003404 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003405 return self.__class__(str(self))
3406
Facundo Batista59c58842007-04-10 12:58:45 +00003407##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003408
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003409
3410# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003411rounding_functions = [name for name in Decimal.__dict__.keys()
3412 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003413for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003414 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003415 globalname = name[1:].upper()
3416 val = globals()[globalname]
3417 Decimal._pick_rounding_function[val] = name
3418
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003419del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003420
Nick Coghlanced12182006-09-02 03:54:17 +00003421class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003422 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003423
Nick Coghlanced12182006-09-02 03:54:17 +00003424 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003425 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003426 """
3427 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003428 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003429 def __enter__(self):
3430 self.saved_context = getcontext()
3431 setcontext(self.new_context)
3432 return self.new_context
3433 def __exit__(self, t, v, tb):
3434 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003435
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003436class Context(object):
3437 """Contains the context for a Decimal instance.
3438
3439 Contains:
3440 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003441 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003442 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003443 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003444 raised when it is caused. Otherwise, a value is
3445 substituted in.
3446 flags - When an exception is caused, flags[exception] is incremented.
3447 (Whether or not the trap_enabler is set)
3448 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003449 Emin - Minimum exponent
3450 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003451 capitals - If 1, 1*10^1 is printed as 1E+1.
3452 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003453 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003454 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003455
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003456 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003457 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003458 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003459 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003460 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003461 _ignored_flags=None):
3462 if flags is None:
3463 flags = []
3464 if _ignored_flags is None:
3465 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003466 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003467 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003468 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003469 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003470 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003471 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003472 for name, val in locals().items():
3473 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003474 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003475 else:
3476 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003477 del self.self
3478
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003479 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003480 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003481 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003482 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3483 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3484 % vars(self))
3485 names = [f.__name__ for f, v in self.flags.items() if v]
3486 s.append('flags=[' + ', '.join(names) + ']')
3487 names = [t.__name__ for t, v in self.traps.items() if v]
3488 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003489 return ', '.join(s) + ')'
3490
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003491 def clear_flags(self):
3492 """Reset all flags to zero"""
3493 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003494 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003495
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003496 def _shallow_copy(self):
3497 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003498 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003499 self._rounding_decision, self.Emin, self.Emax,
3500 self.capitals, self._clamp, self._ignored_flags)
3501 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003502
3503 def copy(self):
3504 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003505 nc = Context(self.prec, self.rounding, self.traps.copy(),
3506 self.flags.copy(), self._rounding_decision, self.Emin,
3507 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003508 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003509 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003510
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003511 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003512 """Handles an error
3513
3514 If the flag is in _ignored_flags, returns the default response.
3515 Otherwise, it increments the flag, then, if the corresponding
3516 trap_enabler is set, it reaises the exception. Otherwise, it returns
3517 the default value after incrementing the flag.
3518 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003519 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003520 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003521 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003522 return error().handle(self, *args)
3523
3524 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003525 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003526 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003527 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003528
3529 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003530 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003531 raise error, explanation
3532
3533 def _ignore_all_flags(self):
3534 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003535 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003536
3537 def _ignore_flags(self, *flags):
3538 """Ignore the flags, if they are raised"""
3539 # Do not mutate-- This way, copies of a context leave the original
3540 # alone.
3541 self._ignored_flags = (self._ignored_flags + list(flags))
3542 return list(flags)
3543
3544 def _regard_flags(self, *flags):
3545 """Stop ignoring the flags, if they are raised"""
3546 if flags and isinstance(flags[0], (tuple,list)):
3547 flags = flags[0]
3548 for flag in flags:
3549 self._ignored_flags.remove(flag)
3550
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003551 def __hash__(self):
3552 """A Context cannot be hashed."""
3553 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003554 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003555
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003556 def Etiny(self):
3557 """Returns Etiny (= Emin - prec + 1)"""
3558 return int(self.Emin - self.prec + 1)
3559
3560 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003561 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003562 return int(self.Emax - self.prec + 1)
3563
3564 def _set_rounding_decision(self, type):
3565 """Sets the rounding decision.
3566
3567 Sets the rounding decision, and returns the current (previous)
3568 rounding decision. Often used like:
3569
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003570 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003571 # That so you don't change the calling context
3572 # if an error occurs in the middle (say DivisionImpossible is raised).
3573
3574 rounding = context._set_rounding_decision(NEVER_ROUND)
3575 instance = instance / Decimal(2)
3576 context._set_rounding_decision(rounding)
3577
3578 This will make it not round for that operation.
3579 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003580
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003581 rounding = self._rounding_decision
3582 self._rounding_decision = type
3583 return rounding
3584
3585 def _set_rounding(self, type):
3586 """Sets the rounding type.
3587
3588 Sets the rounding type, and returns the current (previous)
3589 rounding type. Often used like:
3590
3591 context = context.copy()
3592 # so you don't change the calling context
3593 # if an error occurs in the middle.
3594 rounding = context._set_rounding(ROUND_UP)
3595 val = self.__sub__(other, context=context)
3596 context._set_rounding(rounding)
3597
3598 This will make it round up for that operation.
3599 """
3600 rounding = self.rounding
3601 self.rounding= type
3602 return rounding
3603
Raymond Hettingerfed52962004-07-14 15:41:57 +00003604 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003605 """Creates a new Decimal instance but using self as context."""
3606 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003607 if d._isnan() and len(d._int) > self.prec - self._clamp:
3608 return self._raise_error(ConversionSyntax,
3609 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003610 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003611
Facundo Batista59c58842007-04-10 12:58:45 +00003612 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003613 def abs(self, a):
3614 """Returns the absolute value of the operand.
3615
3616 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003617 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003618 the plus operation on the operand.
3619
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003620 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003621 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003622 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003623 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003624 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003625 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003626 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003627 Decimal("101.5")
3628 """
3629 return a.__abs__(context=self)
3630
3631 def add(self, a, b):
3632 """Return the sum of the two operands.
3633
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003634 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003635 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003636 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003637 Decimal("1.02E+4")
3638 """
3639 return a.__add__(b, context=self)
3640
3641 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003642 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003643
Facundo Batista353750c2007-09-13 18:13:15 +00003644 def canonical(self, a):
3645 """Returns the same Decimal object.
3646
3647 As we do not have different encodings for the same number, the
3648 received object already is in its canonical form.
3649
3650 >>> ExtendedContext.canonical(Decimal('2.50'))
3651 Decimal("2.50")
3652 """
3653 return a.canonical(context=self)
3654
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003655 def compare(self, a, b):
3656 """Compares values numerically.
3657
3658 If the signs of the operands differ, a value representing each operand
3659 ('-1' if the operand is less than zero, '0' if the operand is zero or
3660 negative zero, or '1' if the operand is greater than zero) is used in
3661 place of that operand for the comparison instead of the actual
3662 operand.
3663
3664 The comparison is then effected by subtracting the second operand from
3665 the first and then returning a value according to the result of the
3666 subtraction: '-1' if the result is less than zero, '0' if the result is
3667 zero or negative zero, or '1' if the result is greater than zero.
3668
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003669 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003670 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003671 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003672 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003673 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003674 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003675 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003676 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003677 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003678 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003679 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003680 Decimal("-1")
3681 """
3682 return a.compare(b, context=self)
3683
Facundo Batista353750c2007-09-13 18:13:15 +00003684 def compare_signal(self, a, b):
3685 """Compares the values of the two operands numerically.
3686
3687 It's pretty much like compare(), but all NaNs signal, with signaling
3688 NaNs taking precedence over quiet NaNs.
3689
3690 >>> c = ExtendedContext
3691 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3692 Decimal("-1")
3693 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3694 Decimal("0")
3695 >>> c.flags[InvalidOperation] = 0
3696 >>> print c.flags[InvalidOperation]
3697 0
3698 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3699 Decimal("NaN")
3700 >>> print c.flags[InvalidOperation]
3701 1
3702 >>> c.flags[InvalidOperation] = 0
3703 >>> print c.flags[InvalidOperation]
3704 0
3705 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3706 Decimal("NaN")
3707 >>> print c.flags[InvalidOperation]
3708 1
3709 """
3710 return a.compare_signal(b, context=self)
3711
3712 def compare_total(self, a, b):
3713 """Compares two operands using their abstract representation.
3714
3715 This is not like the standard compare, which use their numerical
3716 value. Note that a total ordering is defined for all possible abstract
3717 representations.
3718
3719 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3720 Decimal("-1")
3721 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3722 Decimal("-1")
3723 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3724 Decimal("-1")
3725 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3726 Decimal("0")
3727 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3728 Decimal("1")
3729 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3730 Decimal("-1")
3731 """
3732 return a.compare_total(b)
3733
3734 def compare_total_mag(self, a, b):
3735 """Compares two operands using their abstract representation ignoring sign.
3736
3737 Like compare_total, but with operand's sign ignored and assumed to be 0.
3738 """
3739 return a.compare_total_mag(b)
3740
3741 def copy_abs(self, a):
3742 """Returns a copy of the operand with the sign set to 0.
3743
3744 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3745 Decimal("2.1")
3746 >>> ExtendedContext.copy_abs(Decimal('-100'))
3747 Decimal("100")
3748 """
3749 return a.copy_abs()
3750
3751 def copy_decimal(self, a):
3752 """Returns a copy of the decimal objet.
3753
3754 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3755 Decimal("2.1")
3756 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3757 Decimal("-1.00")
3758 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003759 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003760
3761 def copy_negate(self, a):
3762 """Returns a copy of the operand with the sign inverted.
3763
3764 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3765 Decimal("-101.5")
3766 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3767 Decimal("101.5")
3768 """
3769 return a.copy_negate()
3770
3771 def copy_sign(self, a, b):
3772 """Copies the second operand's sign to the first one.
3773
3774 In detail, it returns a copy of the first operand with the sign
3775 equal to the sign of the second operand.
3776
3777 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3778 Decimal("1.50")
3779 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3780 Decimal("1.50")
3781 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3782 Decimal("-1.50")
3783 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3784 Decimal("-1.50")
3785 """
3786 return a.copy_sign(b)
3787
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003788 def divide(self, a, b):
3789 """Decimal division in a specified context.
3790
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003791 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003792 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003793 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003794 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003795 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003796 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003797 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003798 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003799 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003800 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003801 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003802 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003803 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003804 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003805 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003806 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003807 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003808 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003809 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003810 Decimal("1.20E+6")
3811 """
3812 return a.__div__(b, context=self)
3813
3814 def divide_int(self, a, b):
3815 """Divides two numbers and returns the integer part of the result.
3816
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003817 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003818 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003819 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003820 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003821 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003822 Decimal("3")
3823 """
3824 return a.__floordiv__(b, context=self)
3825
3826 def divmod(self, a, b):
3827 return a.__divmod__(b, context=self)
3828
Facundo Batista353750c2007-09-13 18:13:15 +00003829 def exp(self, a):
3830 """Returns e ** a.
3831
3832 >>> c = ExtendedContext.copy()
3833 >>> c.Emin = -999
3834 >>> c.Emax = 999
3835 >>> c.exp(Decimal('-Infinity'))
3836 Decimal("0")
3837 >>> c.exp(Decimal('-1'))
3838 Decimal("0.367879441")
3839 >>> c.exp(Decimal('0'))
3840 Decimal("1")
3841 >>> c.exp(Decimal('1'))
3842 Decimal("2.71828183")
3843 >>> c.exp(Decimal('0.693147181'))
3844 Decimal("2.00000000")
3845 >>> c.exp(Decimal('+Infinity'))
3846 Decimal("Infinity")
3847 """
3848 return a.exp(context=self)
3849
3850 def fma(self, a, b, c):
3851 """Returns a multiplied by b, plus c.
3852
3853 The first two operands are multiplied together, using multiply,
3854 the third operand is then added to the result of that
3855 multiplication, using add, all with only one final rounding.
3856
3857 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3858 Decimal("22")
3859 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3860 Decimal("-8")
3861 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3862 Decimal("1.38435736E+12")
3863 """
3864 return a.fma(b, c, context=self)
3865
3866 def is_canonical(self, a):
3867 """Returns 1 if the operand is canonical; otherwise returns 0.
3868
3869 >>> ExtendedContext.is_canonical(Decimal('2.50'))
3870 Decimal("1")
3871 """
3872 return Dec_p1
3873
3874 def is_finite(self, a):
3875 """Returns 1 if the operand is finite, otherwise returns 0.
3876
3877 For it to be finite, it must be neither infinite nor a NaN.
3878
3879 >>> ExtendedContext.is_finite(Decimal('2.50'))
3880 Decimal("1")
3881 >>> ExtendedContext.is_finite(Decimal('-0.3'))
3882 Decimal("1")
3883 >>> ExtendedContext.is_finite(Decimal('0'))
3884 Decimal("1")
3885 >>> ExtendedContext.is_finite(Decimal('Inf'))
3886 Decimal("0")
3887 >>> ExtendedContext.is_finite(Decimal('NaN'))
3888 Decimal("0")
3889 """
3890 return a.is_finite()
3891
3892 def is_infinite(self, a):
3893 """Returns 1 if the operand is an Infinite, otherwise returns 0.
3894
3895 >>> ExtendedContext.is_infinite(Decimal('2.50'))
3896 Decimal("0")
3897 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
3898 Decimal("1")
3899 >>> ExtendedContext.is_infinite(Decimal('NaN'))
3900 Decimal("0")
3901 """
3902 return a.is_infinite()
3903
3904 def is_nan(self, a):
3905 """Returns 1 if the operand is qNaN or sNaN, otherwise returns 0.
3906
3907 >>> ExtendedContext.is_nan(Decimal('2.50'))
3908 Decimal("0")
3909 >>> ExtendedContext.is_nan(Decimal('NaN'))
3910 Decimal("1")
3911 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
3912 Decimal("1")
3913 """
3914 return a.is_nan()
3915
3916 def is_normal(self, a):
3917 """Returns 1 if the operand is a normal number, otherwise returns 0.
3918
3919 >>> c = ExtendedContext.copy()
3920 >>> c.Emin = -999
3921 >>> c.Emax = 999
3922 >>> c.is_normal(Decimal('2.50'))
3923 Decimal("1")
3924 >>> c.is_normal(Decimal('0.1E-999'))
3925 Decimal("0")
3926 >>> c.is_normal(Decimal('0.00'))
3927 Decimal("0")
3928 >>> c.is_normal(Decimal('-Inf'))
3929 Decimal("0")
3930 >>> c.is_normal(Decimal('NaN'))
3931 Decimal("0")
3932 """
3933 return a.is_normal(context=self)
3934
3935 def is_qnan(self, a):
3936 """Returns 1 if the operand is a quiet NaN, otherwise returns 0.
3937
3938 >>> ExtendedContext.is_qnan(Decimal('2.50'))
3939 Decimal("0")
3940 >>> ExtendedContext.is_qnan(Decimal('NaN'))
3941 Decimal("1")
3942 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
3943 Decimal("0")
3944 """
3945 return a.is_qnan()
3946
3947 def is_signed(self, a):
3948 """Returns 1 if the operand is negative, otherwise returns 0.
3949
3950 >>> ExtendedContext.is_signed(Decimal('2.50'))
3951 Decimal("0")
3952 >>> ExtendedContext.is_signed(Decimal('-12'))
3953 Decimal("1")
3954 >>> ExtendedContext.is_signed(Decimal('-0'))
3955 Decimal("1")
3956 """
3957 return a.is_signed()
3958
3959 def is_snan(self, a):
3960 """Returns 1 if the operand is a signaling NaN, otherwise returns 0.
3961
3962 >>> ExtendedContext.is_snan(Decimal('2.50'))
3963 Decimal("0")
3964 >>> ExtendedContext.is_snan(Decimal('NaN'))
3965 Decimal("0")
3966 >>> ExtendedContext.is_snan(Decimal('sNaN'))
3967 Decimal("1")
3968 """
3969 return a.is_snan()
3970
3971 def is_subnormal(self, a):
3972 """Returns 1 if the operand is subnormal, otherwise returns 0.
3973
3974 >>> c = ExtendedContext.copy()
3975 >>> c.Emin = -999
3976 >>> c.Emax = 999
3977 >>> c.is_subnormal(Decimal('2.50'))
3978 Decimal("0")
3979 >>> c.is_subnormal(Decimal('0.1E-999'))
3980 Decimal("1")
3981 >>> c.is_subnormal(Decimal('0.00'))
3982 Decimal("0")
3983 >>> c.is_subnormal(Decimal('-Inf'))
3984 Decimal("0")
3985 >>> c.is_subnormal(Decimal('NaN'))
3986 Decimal("0")
3987 """
3988 return a.is_subnormal(context=self)
3989
3990 def is_zero(self, a):
3991 """Returns 1 if the operand is a zero, otherwise returns 0.
3992
3993 >>> ExtendedContext.is_zero(Decimal('0'))
3994 Decimal("1")
3995 >>> ExtendedContext.is_zero(Decimal('2.50'))
3996 Decimal("0")
3997 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
3998 Decimal("1")
3999 """
4000 return a.is_zero()
4001
4002 def ln(self, a):
4003 """Returns the natural (base e) logarithm of the operand.
4004
4005 >>> c = ExtendedContext.copy()
4006 >>> c.Emin = -999
4007 >>> c.Emax = 999
4008 >>> c.ln(Decimal('0'))
4009 Decimal("-Infinity")
4010 >>> c.ln(Decimal('1.000'))
4011 Decimal("0")
4012 >>> c.ln(Decimal('2.71828183'))
4013 Decimal("1.00000000")
4014 >>> c.ln(Decimal('10'))
4015 Decimal("2.30258509")
4016 >>> c.ln(Decimal('+Infinity'))
4017 Decimal("Infinity")
4018 """
4019 return a.ln(context=self)
4020
4021 def log10(self, a):
4022 """Returns the base 10 logarithm of the operand.
4023
4024 >>> c = ExtendedContext.copy()
4025 >>> c.Emin = -999
4026 >>> c.Emax = 999
4027 >>> c.log10(Decimal('0'))
4028 Decimal("-Infinity")
4029 >>> c.log10(Decimal('0.001'))
4030 Decimal("-3")
4031 >>> c.log10(Decimal('1.000'))
4032 Decimal("0")
4033 >>> c.log10(Decimal('2'))
4034 Decimal("0.301029996")
4035 >>> c.log10(Decimal('10'))
4036 Decimal("1")
4037 >>> c.log10(Decimal('70'))
4038 Decimal("1.84509804")
4039 >>> c.log10(Decimal('+Infinity'))
4040 Decimal("Infinity")
4041 """
4042 return a.log10(context=self)
4043
4044 def logb(self, a):
4045 """ Returns the exponent of the magnitude of the operand's MSD.
4046
4047 The result is the integer which is the exponent of the magnitude
4048 of the most significant digit of the operand (as though the
4049 operand were truncated to a single digit while maintaining the
4050 value of that digit and without limiting the resulting exponent).
4051
4052 >>> ExtendedContext.logb(Decimal('250'))
4053 Decimal("2")
4054 >>> ExtendedContext.logb(Decimal('2.50'))
4055 Decimal("0")
4056 >>> ExtendedContext.logb(Decimal('0.03'))
4057 Decimal("-2")
4058 >>> ExtendedContext.logb(Decimal('0'))
4059 Decimal("-Infinity")
4060 """
4061 return a.logb(context=self)
4062
4063 def logical_and(self, a, b):
4064 """Applies the logical operation 'and' between each operand's digits.
4065
4066 The operands must be both logical numbers.
4067
4068 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4069 Decimal("0")
4070 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4071 Decimal("0")
4072 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4073 Decimal("0")
4074 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4075 Decimal("1")
4076 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4077 Decimal("1000")
4078 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4079 Decimal("10")
4080 """
4081 return a.logical_and(b, context=self)
4082
4083 def logical_invert(self, a):
4084 """Invert all the digits in the operand.
4085
4086 The operand must be a logical number.
4087
4088 >>> ExtendedContext.logical_invert(Decimal('0'))
4089 Decimal("111111111")
4090 >>> ExtendedContext.logical_invert(Decimal('1'))
4091 Decimal("111111110")
4092 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4093 Decimal("0")
4094 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4095 Decimal("10101010")
4096 """
4097 return a.logical_invert(context=self)
4098
4099 def logical_or(self, a, b):
4100 """Applies the logical operation 'or' between each operand's digits.
4101
4102 The operands must be both logical numbers.
4103
4104 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4105 Decimal("0")
4106 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4107 Decimal("1")
4108 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4109 Decimal("1")
4110 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4111 Decimal("1")
4112 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4113 Decimal("1110")
4114 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4115 Decimal("1110")
4116 """
4117 return a.logical_or(b, context=self)
4118
4119 def logical_xor(self, a, b):
4120 """Applies the logical operation 'xor' between each operand's digits.
4121
4122 The operands must be both logical numbers.
4123
4124 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4125 Decimal("0")
4126 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4127 Decimal("1")
4128 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4129 Decimal("1")
4130 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4131 Decimal("0")
4132 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4133 Decimal("110")
4134 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4135 Decimal("1101")
4136 """
4137 return a.logical_xor(b, context=self)
4138
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004139 def max(self, a,b):
4140 """max compares two values numerically and returns the maximum.
4141
4142 If either operand is a NaN then the general rules apply.
4143 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004144 operation. If they are numerically equal then the left-hand operand
4145 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004146 infinity) of the two operands is chosen as the result.
4147
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004148 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004149 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004150 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004151 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004152 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004153 Decimal("1")
4154 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4155 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004156 """
4157 return a.max(b, context=self)
4158
Facundo Batista353750c2007-09-13 18:13:15 +00004159 def max_mag(self, a, b):
4160 """Compares the values numerically with their sign ignored."""
4161 return a.max_mag(b, context=self)
4162
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004163 def min(self, a,b):
4164 """min compares two values numerically and returns the minimum.
4165
4166 If either operand is a NaN then the general rules apply.
4167 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004168 operation. If they are numerically equal then the left-hand operand
4169 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004170 infinity) of the two operands is chosen as the result.
4171
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004172 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004173 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004174 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004175 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004176 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004177 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004178 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4179 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004180 """
4181 return a.min(b, context=self)
4182
Facundo Batista353750c2007-09-13 18:13:15 +00004183 def min_mag(self, a, b):
4184 """Compares the values numerically with their sign ignored."""
4185 return a.min_mag(b, context=self)
4186
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004187 def minus(self, a):
4188 """Minus corresponds to unary prefix minus in Python.
4189
4190 The operation is evaluated using the same rules as subtract; the
4191 operation minus(a) is calculated as subtract('0', a) where the '0'
4192 has the same exponent as the operand.
4193
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004194 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004195 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004196 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004197 Decimal("1.3")
4198 """
4199 return a.__neg__(context=self)
4200
4201 def multiply(self, a, b):
4202 """multiply multiplies two operands.
4203
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004204 If either operand is a special value then the general rules apply.
4205 Otherwise, the operands are multiplied together ('long multiplication'),
4206 resulting in a number which may be as long as the sum of the lengths
4207 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004208
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004209 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004210 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004211 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004212 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004213 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004214 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004215 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004216 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004217 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004218 Decimal("4.28135971E+11")
4219 """
4220 return a.__mul__(b, context=self)
4221
Facundo Batista353750c2007-09-13 18:13:15 +00004222 def next_minus(self, a):
4223 """Returns the largest representable number smaller than a.
4224
4225 >>> c = ExtendedContext.copy()
4226 >>> c.Emin = -999
4227 >>> c.Emax = 999
4228 >>> ExtendedContext.next_minus(Decimal('1'))
4229 Decimal("0.999999999")
4230 >>> c.next_minus(Decimal('1E-1007'))
4231 Decimal("0E-1007")
4232 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4233 Decimal("-1.00000004")
4234 >>> c.next_minus(Decimal('Infinity'))
4235 Decimal("9.99999999E+999")
4236 """
4237 return a.next_minus(context=self)
4238
4239 def next_plus(self, a):
4240 """Returns the smallest representable number larger than a.
4241
4242 >>> c = ExtendedContext.copy()
4243 >>> c.Emin = -999
4244 >>> c.Emax = 999
4245 >>> ExtendedContext.next_plus(Decimal('1'))
4246 Decimal("1.00000001")
4247 >>> c.next_plus(Decimal('-1E-1007'))
4248 Decimal("-0E-1007")
4249 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4250 Decimal("-1.00000002")
4251 >>> c.next_plus(Decimal('-Infinity'))
4252 Decimal("-9.99999999E+999")
4253 """
4254 return a.next_plus(context=self)
4255
4256 def next_toward(self, a, b):
4257 """Returns the number closest to a, in direction towards b.
4258
4259 The result is the closest representable number from the first
4260 operand (but not the first operand) that is in the direction
4261 towards the second operand, unless the operands have the same
4262 value.
4263
4264 >>> c = ExtendedContext.copy()
4265 >>> c.Emin = -999
4266 >>> c.Emax = 999
4267 >>> c.next_toward(Decimal('1'), Decimal('2'))
4268 Decimal("1.00000001")
4269 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4270 Decimal("-0E-1007")
4271 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4272 Decimal("-1.00000002")
4273 >>> c.next_toward(Decimal('1'), Decimal('0'))
4274 Decimal("0.999999999")
4275 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4276 Decimal("0E-1007")
4277 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4278 Decimal("-1.00000004")
4279 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4280 Decimal("-0.00")
4281 """
4282 return a.next_toward(b, context=self)
4283
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004284 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004285 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004286
4287 Essentially a plus operation with all trailing zeros removed from the
4288 result.
4289
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004290 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004291 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004292 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004293 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004294 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004295 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004296 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004297 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004298 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004299 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004300 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004301 Decimal("0")
4302 """
4303 return a.normalize(context=self)
4304
Facundo Batista353750c2007-09-13 18:13:15 +00004305 def number_class(self, a):
4306 """Returns an indication of the class of the operand.
4307
4308 The class is one of the following strings:
4309 -sNaN
4310 -NaN
4311 -Infinity
4312 -Normal
4313 -Subnormal
4314 -Zero
4315 +Zero
4316 +Subnormal
4317 +Normal
4318 +Infinity
4319
4320 >>> c = Context(ExtendedContext)
4321 >>> c.Emin = -999
4322 >>> c.Emax = 999
4323 >>> c.number_class(Decimal('Infinity'))
4324 '+Infinity'
4325 >>> c.number_class(Decimal('1E-10'))
4326 '+Normal'
4327 >>> c.number_class(Decimal('2.50'))
4328 '+Normal'
4329 >>> c.number_class(Decimal('0.1E-999'))
4330 '+Subnormal'
4331 >>> c.number_class(Decimal('0'))
4332 '+Zero'
4333 >>> c.number_class(Decimal('-0'))
4334 '-Zero'
4335 >>> c.number_class(Decimal('-0.1E-999'))
4336 '-Subnormal'
4337 >>> c.number_class(Decimal('-1E-10'))
4338 '-Normal'
4339 >>> c.number_class(Decimal('-2.50'))
4340 '-Normal'
4341 >>> c.number_class(Decimal('-Infinity'))
4342 '-Infinity'
4343 >>> c.number_class(Decimal('NaN'))
4344 'NaN'
4345 >>> c.number_class(Decimal('-NaN'))
4346 'NaN'
4347 >>> c.number_class(Decimal('sNaN'))
4348 'sNaN'
4349 """
4350 return a.number_class(context=self)
4351
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004352 def plus(self, a):
4353 """Plus corresponds to unary prefix plus in Python.
4354
4355 The operation is evaluated using the same rules as add; the
4356 operation plus(a) is calculated as add('0', a) where the '0'
4357 has the same exponent as the operand.
4358
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004359 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004360 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004361 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004362 Decimal("-1.3")
4363 """
4364 return a.__pos__(context=self)
4365
4366 def power(self, a, b, modulo=None):
4367 """Raises a to the power of b, to modulo if given.
4368
Facundo Batista353750c2007-09-13 18:13:15 +00004369 With two arguments, compute a**b. If a is negative then b
4370 must be integral. The result will be inexact unless b is
4371 integral and the result is finite and can be expressed exactly
4372 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004373
Facundo Batista353750c2007-09-13 18:13:15 +00004374 With three arguments, compute (a**b) % modulo. For the
4375 three argument form, the following restrictions on the
4376 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004377
Facundo Batista353750c2007-09-13 18:13:15 +00004378 - all three arguments must be integral
4379 - b must be nonnegative
4380 - at least one of a or b must be nonzero
4381 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004382
Facundo Batista353750c2007-09-13 18:13:15 +00004383 The result of pow(a, b, modulo) is identical to the result
4384 that would be obtained by computing (a**b) % modulo with
4385 unbounded precision, but is computed more efficiently. It is
4386 always exact.
4387
4388 >>> c = ExtendedContext.copy()
4389 >>> c.Emin = -999
4390 >>> c.Emax = 999
4391 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004392 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004393 >>> c.power(Decimal('-2'), Decimal('3'))
4394 Decimal("-8")
4395 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004396 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004397 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004398 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004399 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4400 Decimal("2.00000000")
4401 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004402 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004403 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004404 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004405 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004406 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004407 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004408 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004409 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004410 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004411 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004412 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004413 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004414 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004415 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004416 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004417
4418 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4419 Decimal("11")
4420 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4421 Decimal("-11")
4422 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4423 Decimal("1")
4424 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4425 Decimal("11")
4426 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4427 Decimal("11729830")
4428 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4429 Decimal("-0")
4430 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4431 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004432 """
4433 return a.__pow__(b, modulo, context=self)
4434
4435 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004436 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004437
4438 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004439 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004440 exponent is being increased), multiplied by a positive power of ten (if
4441 the exponent is being decreased), or is unchanged (if the exponent is
4442 already equal to that of the right-hand operand).
4443
4444 Unlike other operations, if the length of the coefficient after the
4445 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004446 operation condition is raised. This guarantees that, unless there is
4447 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004448 equal to that of the right-hand operand.
4449
4450 Also unlike other operations, quantize will never raise Underflow, even
4451 if the result is subnormal and inexact.
4452
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004453 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004454 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004455 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004456 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004457 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004458 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004459 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004460 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004461 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004462 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004463 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004464 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004465 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004466 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004467 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004468 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004469 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004470 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004471 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004472 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004473 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004474 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004475 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004476 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004477 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004478 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004479 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004480 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004481 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004482 Decimal("2E+2")
4483 """
4484 return a.quantize(b, context=self)
4485
Facundo Batista353750c2007-09-13 18:13:15 +00004486 def radix(self):
4487 """Just returns 10, as this is Decimal, :)
4488
4489 >>> ExtendedContext.radix()
4490 Decimal("10")
4491 """
4492 return Decimal(10)
4493
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004494 def remainder(self, a, b):
4495 """Returns the remainder from integer division.
4496
4497 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004498 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004499 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004500 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004501
4502 This operation will fail under the same conditions as integer division
4503 (that is, if integer division on the same two operands would fail, the
4504 remainder cannot be calculated).
4505
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004506 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004507 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004508 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004509 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004510 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004511 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004512 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004513 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004514 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004515 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004516 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004517 Decimal("1.0")
4518 """
4519 return a.__mod__(b, context=self)
4520
4521 def remainder_near(self, a, b):
4522 """Returns to be "a - b * n", where n is the integer nearest the exact
4523 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004524 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004525 sign of a.
4526
4527 This operation will fail under the same conditions as integer division
4528 (that is, if integer division on the same two operands would fail, the
4529 remainder cannot be calculated).
4530
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004531 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004532 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004533 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004534 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004535 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004536 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004537 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004538 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004539 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004540 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004541 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004542 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004543 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004544 Decimal("-0.3")
4545 """
4546 return a.remainder_near(b, context=self)
4547
Facundo Batista353750c2007-09-13 18:13:15 +00004548 def rotate(self, a, b):
4549 """Returns a rotated copy of a, b times.
4550
4551 The coefficient of the result is a rotated copy of the digits in
4552 the coefficient of the first operand. The number of places of
4553 rotation is taken from the absolute value of the second operand,
4554 with the rotation being to the left if the second operand is
4555 positive or to the right otherwise.
4556
4557 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4558 Decimal("400000003")
4559 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4560 Decimal("12")
4561 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4562 Decimal("891234567")
4563 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4564 Decimal("123456789")
4565 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4566 Decimal("345678912")
4567 """
4568 return a.rotate(b, context=self)
4569
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004570 def same_quantum(self, a, b):
4571 """Returns True if the two operands have the same exponent.
4572
4573 The result is never affected by either the sign or the coefficient of
4574 either operand.
4575
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004576 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004577 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004578 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004579 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004580 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004581 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004582 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004583 True
4584 """
4585 return a.same_quantum(b)
4586
Facundo Batista353750c2007-09-13 18:13:15 +00004587 def scaleb (self, a, b):
4588 """Returns the first operand after adding the second value its exp.
4589
4590 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4591 Decimal("0.0750")
4592 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4593 Decimal("7.50")
4594 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4595 Decimal("7.50E+3")
4596 """
4597 return a.scaleb (b, context=self)
4598
4599 def shift(self, a, b):
4600 """Returns a shifted copy of a, b times.
4601
4602 The coefficient of the result is a shifted copy of the digits
4603 in the coefficient of the first operand. The number of places
4604 to shift is taken from the absolute value of the second operand,
4605 with the shift being to the left if the second operand is
4606 positive or to the right otherwise. Digits shifted into the
4607 coefficient are zeros.
4608
4609 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4610 Decimal("400000000")
4611 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4612 Decimal("0")
4613 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4614 Decimal("1234567")
4615 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4616 Decimal("123456789")
4617 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4618 Decimal("345678900")
4619 """
4620 return a.shift(b, context=self)
4621
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004622 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004623 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004624
4625 If the result must be inexact, it is rounded using the round-half-even
4626 algorithm.
4627
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004628 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004629 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004630 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004631 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004632 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004633 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004634 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004635 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004636 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004637 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004638 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004639 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004640 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004641 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004642 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004643 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004644 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004645 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004646 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004647 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004648 """
4649 return a.sqrt(context=self)
4650
4651 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004652 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004653
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004654 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004655 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004656 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004657 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004658 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004659 Decimal("-0.77")
4660 """
4661 return a.__sub__(b, context=self)
4662
4663 def to_eng_string(self, a):
4664 """Converts a number to a string, using scientific notation.
4665
4666 The operation is not affected by the context.
4667 """
4668 return a.to_eng_string(context=self)
4669
4670 def to_sci_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.__str__(context=self)
4676
Facundo Batista353750c2007-09-13 18:13:15 +00004677 def to_integral_exact(self, a):
4678 """Rounds to an integer.
4679
4680 When the operand has a negative exponent, the result is the same
4681 as using the quantize() operation using the given operand as the
4682 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4683 of the operand as the precision setting; Inexact and Rounded flags
4684 are allowed in this operation. The rounding mode is taken from the
4685 context.
4686
4687 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4688 Decimal("2")
4689 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4690 Decimal("100")
4691 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4692 Decimal("100")
4693 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4694 Decimal("102")
4695 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4696 Decimal("-102")
4697 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4698 Decimal("1.0E+6")
4699 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4700 Decimal("7.89E+77")
4701 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4702 Decimal("-Infinity")
4703 """
4704 return a.to_integral_exact(context=self)
4705
4706 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004707 """Rounds to an integer.
4708
4709 When the operand has a negative exponent, the result is the same
4710 as using the quantize() operation using the given operand as the
4711 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4712 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004713 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004714
Facundo Batista353750c2007-09-13 18:13:15 +00004715 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004716 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004717 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004718 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004719 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004720 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004721 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004722 Decimal("102")
Facundo Batista353750c2007-09-13 18:13:15 +00004723 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004724 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004725 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004726 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004727 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004728 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004729 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004730 Decimal("-Infinity")
4731 """
Facundo Batista353750c2007-09-13 18:13:15 +00004732 return a.to_integral_value(context=self)
4733
4734 # the method name changed, but we provide also the old one, for compatibility
4735 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004736
4737class _WorkRep(object):
4738 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004739 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004740 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004741 # exp: None, int, or string
4742
4743 def __init__(self, value=None):
4744 if value is None:
4745 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004746 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004747 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004748 elif isinstance(value, Decimal):
4749 self.sign = value._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004750 cum = 0
Raymond Hettinger17931de2004-10-27 06:21:46 +00004751 for digit in value._int:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004752 cum = cum * 10 + digit
4753 self.int = cum
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004754 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004755 else:
4756 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004757 self.sign = value[0]
4758 self.int = value[1]
4759 self.exp = value[2]
4760
4761 def __repr__(self):
4762 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4763
4764 __str__ = __repr__
4765
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004766
4767
4768def _normalize(op1, op2, shouldround = 0, prec = 0):
4769 """Normalizes op1, op2 to have the same exp and length of coefficient.
4770
4771 Done during addition.
4772 """
Facundo Batista353750c2007-09-13 18:13:15 +00004773 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004774 tmp = op2
4775 other = op1
4776 else:
4777 tmp = op1
4778 other = op2
4779
Facundo Batista353750c2007-09-13 18:13:15 +00004780 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4781 # Then adding 10**exp to tmp has the same effect (after rounding)
4782 # as adding any positive quantity smaller than 10**exp; similarly
4783 # for subtraction. So if other is smaller than 10**exp we replace
4784 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4785 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004786 tmp_len = len(str(tmp.int))
4787 other_len = len(str(other.int))
Facundo Batista353750c2007-09-13 18:13:15 +00004788 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4789 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004790 other.int = 1
Facundo Batista353750c2007-09-13 18:13:15 +00004791 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004792
Facundo Batista353750c2007-09-13 18:13:15 +00004793 tmp.int *= 10 ** (tmp.exp - other.exp)
4794 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004795 return op1, op2
4796
Facundo Batista353750c2007-09-13 18:13:15 +00004797##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4798
4799# This function from Tim Peters was taken from here:
4800# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4801# The correction being in the function definition is for speed, and
4802# the whole function is not resolved with math.log because of avoiding
4803# the use of floats.
4804def _nbits(n, correction = {
4805 '0': 4, '1': 3, '2': 2, '3': 2,
4806 '4': 1, '5': 1, '6': 1, '7': 1,
4807 '8': 0, '9': 0, 'a': 0, 'b': 0,
4808 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4809 """Number of bits in binary representation of the positive integer n,
4810 or 0 if n == 0.
4811 """
4812 if n < 0:
4813 raise ValueError("The argument to _nbits should be nonnegative.")
4814 hex_n = "%x" % n
4815 return 4*len(hex_n) - correction[hex_n[0]]
4816
4817def _sqrt_nearest(n, a):
4818 """Closest integer to the square root of the positive integer n. a is
4819 an initial approximation to the square root. Any positive integer
4820 will do for a, but the closer a is to the square root of n the
4821 faster convergence will be.
4822
4823 """
4824 if n <= 0 or a <= 0:
4825 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4826
4827 b=0
4828 while a != b:
4829 b, a = a, a--n//a>>1
4830 return a
4831
4832def _rshift_nearest(x, shift):
4833 """Given an integer x and a nonnegative integer shift, return closest
4834 integer to x / 2**shift; use round-to-even in case of a tie.
4835
4836 """
4837 b, q = 1L << shift, x >> shift
4838 return q + (2*(x & (b-1)) + (q&1) > b)
4839
4840def _div_nearest(a, b):
4841 """Closest integer to a/b, a and b positive integers; rounds to even
4842 in the case of a tie.
4843
4844 """
4845 q, r = divmod(a, b)
4846 return q + (2*r + (q&1) > b)
4847
4848def _ilog(x, M, L = 8):
4849 """Integer approximation to M*log(x/M), with absolute error boundable
4850 in terms only of x/M.
4851
4852 Given positive integers x and M, return an integer approximation to
4853 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4854 between the approximation and the exact result is at most 22. For
4855 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4856 both cases these are upper bounds on the error; it will usually be
4857 much smaller."""
4858
4859 # The basic algorithm is the following: let log1p be the function
4860 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4861 # the reduction
4862 #
4863 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4864 #
4865 # repeatedly until the argument to log1p is small (< 2**-L in
4866 # absolute value). For small y we can use the Taylor series
4867 # expansion
4868 #
4869 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4870 #
4871 # truncating at T such that y**T is small enough. The whole
4872 # computation is carried out in a form of fixed-point arithmetic,
4873 # with a real number z being represented by an integer
4874 # approximation to z*M. To avoid loss of precision, the y below
4875 # is actually an integer approximation to 2**R*y*M, where R is the
4876 # number of reductions performed so far.
4877
4878 y = x-M
4879 # argument reduction; R = number of reductions performed
4880 R = 0
4881 while (R <= L and long(abs(y)) << L-R >= M or
4882 R > L and abs(y) >> R-L >= M):
4883 y = _div_nearest(long(M*y) << 1,
4884 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4885 R += 1
4886
4887 # Taylor series with T terms
4888 T = -int(-10*len(str(M))//(3*L))
4889 yshift = _rshift_nearest(y, R)
4890 w = _div_nearest(M, T)
4891 for k in xrange(T-1, 0, -1):
4892 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4893
4894 return _div_nearest(w*y, M)
4895
4896def _dlog10(c, e, p):
4897 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4898 approximation to 10**p * log10(c*10**e), with an absolute error of
4899 at most 1. Assumes that c*10**e is not exactly 1."""
4900
4901 # increase precision by 2; compensate for this by dividing
4902 # final result by 100
4903 p += 2
4904
4905 # write c*10**e as d*10**f with either:
4906 # f >= 0 and 1 <= d <= 10, or
4907 # f <= 0 and 0.1 <= d <= 1.
4908 # Thus for c*10**e close to 1, f = 0
4909 l = len(str(c))
4910 f = e+l - (e+l >= 1)
4911
4912 if p > 0:
4913 M = 10**p
4914 k = e+p-f
4915 if k >= 0:
4916 c *= 10**k
4917 else:
4918 c = _div_nearest(c, 10**-k)
4919
4920 log_d = _ilog(c, M) # error < 5 + 22 = 27
4921 log_10 = _ilog(10*M, M) # error < 15
4922 log_d = _div_nearest(log_d*M, log_10)
4923 log_tenpower = f*M # exact
4924 else:
4925 log_d = 0 # error < 2.31
4926 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4927
4928 return _div_nearest(log_tenpower+log_d, 100)
4929
4930def _dlog(c, e, p):
4931 """Given integers c, e and p with c > 0, compute an integer
4932 approximation to 10**p * log(c*10**e), with an absolute error of
4933 at most 1. Assumes that c*10**e is not exactly 1."""
4934
4935 # Increase precision by 2. The precision increase is compensated
4936 # for at the end with a division by 100.
4937 p += 2
4938
4939 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4940 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4941 # as 10**p * log(d) + 10**p*f * log(10).
4942 l = len(str(c))
4943 f = e+l - (e+l >= 1)
4944
4945 # compute approximation to 10**p*log(d), with error < 27
4946 if p > 0:
4947 k = e+p-f
4948 if k >= 0:
4949 c *= 10**k
4950 else:
4951 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4952
4953 # _ilog magnifies existing error in c by a factor of at most 10
4954 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4955 else:
4956 # p <= 0: just approximate the whole thing by 0; error < 2.31
4957 log_d = 0
4958
4959 # compute approximation to 10**p*f*log(10), with error < 17
4960 if f:
4961 sign_f = [-1, 1][f > 0]
4962 if p >= 0:
4963 M = 10**p * abs(f)
4964 else:
4965 M = _div_nearest(abs(f), 10**-p) # M = 10**p*|f|, error <= 0.5
4966
4967 if M:
4968 f_log_ten = sign_f*_ilog(10*M, M) # M*log(10), error <= 1.2 + 15 < 17
4969 else:
4970 f_log_ten = 0
4971 else:
4972 f_log_ten = 0
4973
4974 # error in sum < 17+27 = 44; error after division < 0.44 + 0.5 < 1
4975 return _div_nearest(f_log_ten + log_d, 100)
4976
4977def _iexp(x, M, L=8):
4978 """Given integers x and M, M > 0, such that x/M is small in absolute
4979 value, compute an integer approximation to M*exp(x/M). For 0 <=
4980 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4981 is usually much smaller)."""
4982
4983 # Algorithm: to compute exp(z) for a real number z, first divide z
4984 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4985 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4986 # series
4987 #
4988 # expm1(x) = x + x**2/2! + x**3/3! + ...
4989 #
4990 # Now use the identity
4991 #
4992 # expm1(2x) = expm1(x)*(expm1(x)+2)
4993 #
4994 # R times to compute the sequence expm1(z/2**R),
4995 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
4996
4997 # Find R such that x/2**R/M <= 2**-L
4998 R = _nbits((long(x)<<L)//M)
4999
5000 # Taylor series. (2**L)**T > M
5001 T = -int(-10*len(str(M))//(3*L))
5002 y = _div_nearest(x, T)
5003 Mshift = long(M)<<R
5004 for i in xrange(T-1, 0, -1):
5005 y = _div_nearest(x*(Mshift + y), Mshift * i)
5006
5007 # Expansion
5008 for k in xrange(R-1, -1, -1):
5009 Mshift = long(M)<<(k+2)
5010 y = _div_nearest(y*(y+Mshift), Mshift)
5011
5012 return M+y
5013
5014def _dexp(c, e, p):
5015 """Compute an approximation to exp(c*10**e), with p decimal places of
5016 precision.
5017
5018 Returns d, f such that:
5019
5020 10**(p-1) <= d <= 10**p, and
5021 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5022
5023 In other words, d*10**f is an approximation to exp(c*10**e) with p
5024 digits of precision, and with an error in d of at most 1. This is
5025 almost, but not quite, the same as the error being < 1ulp: when d
5026 = 10**(p-1) the error could be up to 10 ulp."""
5027
5028 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5029 p += 2
5030
5031 # compute log10 with extra precision = adjusted exponent of c*10**e
5032 extra = max(0, e + len(str(c)) - 1)
5033 q = p + extra
5034 log10 = _dlog(10, 0, q) # error <= 1
5035
5036 # compute quotient c*10**e/(log10/10**q) = c*10**(e+q)/log10,
5037 # rounding down
5038 shift = e+q
5039 if shift >= 0:
5040 cshift = c*10**shift
5041 else:
5042 cshift = c//10**-shift
5043 quot, rem = divmod(cshift, log10)
5044
5045 # reduce remainder back to original precision
5046 rem = _div_nearest(rem, 10**extra)
5047
5048 # error in result of _iexp < 120; error after division < 0.62
5049 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5050
5051def _dpower(xc, xe, yc, ye, p):
5052 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5053 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5054
5055 10**(p-1) <= c <= 10**p, and
5056 (c-1)*10**e < x**y < (c+1)*10**e
5057
5058 in other words, c*10**e is an approximation to x**y with p digits
5059 of precision, and with an error in c of at most 1. (This is
5060 almost, but not quite, the same as the error being < 1ulp: when c
5061 == 10**(p-1) we can only guarantee error < 10ulp.)
5062
5063 We assume that: x is positive and not equal to 1, and y is nonzero.
5064 """
5065
5066 # Find b such that 10**(b-1) <= |y| <= 10**b
5067 b = len(str(abs(yc))) + ye
5068
5069 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5070 lxc = _dlog(xc, xe, p+b+1)
5071
5072 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5073 shift = ye-b
5074 if shift >= 0:
5075 pc = lxc*yc*10**shift
5076 else:
5077 pc = _div_nearest(lxc*yc, 10**-shift)
5078
5079 if pc == 0:
5080 # we prefer a result that isn't exactly 1; this makes it
5081 # easier to compute a correctly rounded result in __pow__
5082 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5083 coeff, exp = 10**(p-1)+1, 1-p
5084 else:
5085 coeff, exp = 10**p-1, -p
5086 else:
5087 coeff, exp = _dexp(pc, -(p+1), p+1)
5088 coeff = _div_nearest(coeff, 10)
5089 exp += 1
5090
5091 return coeff, exp
5092
5093def _log10_lb(c, correction = {
5094 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5095 '6': 23, '7': 16, '8': 10, '9': 5}):
5096 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5097 if c <= 0:
5098 raise ValueError("The argument to _log10_lb should be nonnegative.")
5099 str_c = str(c)
5100 return 100*len(str_c) - correction[str_c[0]]
5101
Facundo Batista59c58842007-04-10 12:58:45 +00005102##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005103
Facundo Batista353750c2007-09-13 18:13:15 +00005104def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005105 """Convert other to Decimal.
5106
5107 Verifies that it's ok to use in an implicit construction.
5108 """
5109 if isinstance(other, Decimal):
5110 return other
5111 if isinstance(other, (int, long)):
5112 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005113 if raiseit:
5114 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005115 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005116
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005117_infinity_map = {
5118 'inf' : 1,
5119 'infinity' : 1,
5120 '+inf' : 1,
5121 '+infinity' : 1,
5122 '-inf' : -1,
5123 '-infinity' : -1
5124}
5125
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005126def _isinfinity(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005127 """Determines whether a string or float is infinity.
5128
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005129 +1 for negative infinity; 0 for finite ; +1 for positive infinity
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005130 """
5131 num = str(num).lower()
5132 return _infinity_map.get(num, 0)
5133
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005134def _isnan(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005135 """Determines whether a string or float is NaN
5136
5137 (1, sign, diagnostic info as string) => NaN
5138 (2, sign, diagnostic info as string) => sNaN
5139 0 => not a NaN
5140 """
5141 num = str(num).lower()
5142 if not num:
5143 return 0
5144
Facundo Batista59c58842007-04-10 12:58:45 +00005145 # Get the sign, get rid of trailing [+-]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005146 sign = 0
5147 if num[0] == '+':
5148 num = num[1:]
Facundo Batista59c58842007-04-10 12:58:45 +00005149 elif num[0] == '-': # elif avoids '+-nan'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005150 num = num[1:]
5151 sign = 1
5152
5153 if num.startswith('nan'):
Facundo Batista59c58842007-04-10 12:58:45 +00005154 if len(num) > 3 and not num[3:].isdigit(): # diagnostic info
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005155 return 0
5156 return (1, sign, num[3:].lstrip('0'))
5157 if num.startswith('snan'):
5158 if len(num) > 4 and not num[4:].isdigit():
5159 return 0
5160 return (2, sign, num[4:].lstrip('0'))
5161 return 0
5162
5163
Facundo Batista59c58842007-04-10 12:58:45 +00005164##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005165
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005166# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005167# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005168
5169DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005170 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005171 traps=[DivisionByZero, Overflow, InvalidOperation],
5172 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005173 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005174 Emax=999999999,
5175 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005176 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005177)
5178
5179# Pre-made alternate contexts offered by the specification
5180# Don't change these; the user should be able to select these
5181# contexts and be able to reproduce results from other implementations
5182# of the spec.
5183
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005184BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005185 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005186 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5187 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005188)
5189
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005190ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005191 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005192 traps=[],
5193 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005194)
5195
5196
Facundo Batista59c58842007-04-10 12:58:45 +00005197##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005198
Facundo Batista59c58842007-04-10 12:58:45 +00005199# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005200Inf = Decimal('Inf')
5201negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005202NaN = Decimal('NaN')
5203Dec_0 = Decimal(0)
5204Dec_p1 = Decimal(1)
5205Dec_n1 = Decimal(-1)
5206Dec_p2 = Decimal(2)
5207Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005208
Facundo Batista59c58842007-04-10 12:58:45 +00005209# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005210Infsign = (Inf, negInf)
5211
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005212
Facundo Batista59c58842007-04-10 12:58:45 +00005213##### crud for parsing strings #############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005214import re
5215
5216# There's an optional sign at the start, and an optional exponent
5217# at the end. The exponent has an optional sign and at least one
5218# digit. In between, must have either at least one digit followed
5219# by an optional fraction, or a decimal point followed by at least
5220# one digit. Yuck.
5221
5222_parser = re.compile(r"""
5223# \s*
5224 (?P<sign>[-+])?
5225 (
5226 (?P<int>\d+) (\. (?P<frac>\d*))?
5227 |
5228 \. (?P<onlyfrac>\d+)
5229 )
5230 ([eE](?P<exp>[-+]? \d+))?
5231# \s*
5232 $
Facundo Batista59c58842007-04-10 12:58:45 +00005233""", re.VERBOSE).match # Uncomment the \s* to allow leading or trailing spaces.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005234
5235del re
5236
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005237def _string2exact(s):
Facundo Batista59c58842007-04-10 12:58:45 +00005238 """Return sign, n, p s.t.
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00005239
Facundo Batista59c58842007-04-10 12:58:45 +00005240 Float string value == -1**sign * n * 10**p exactly
5241 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005242 m = _parser(s)
5243 if m is None:
5244 raise ValueError("invalid literal for Decimal: %r" % s)
5245
5246 if m.group('sign') == "-":
5247 sign = 1
5248 else:
5249 sign = 0
5250
5251 exp = m.group('exp')
5252 if exp is None:
5253 exp = 0
5254 else:
5255 exp = int(exp)
5256
5257 intpart = m.group('int')
5258 if intpart is None:
5259 intpart = ""
5260 fracpart = m.group('onlyfrac')
5261 else:
5262 fracpart = m.group('frac')
5263 if fracpart is None:
5264 fracpart = ""
5265
5266 exp -= len(fracpart)
5267
5268 mantissa = intpart + fracpart
5269 tmp = map(int, mantissa)
5270 backup = tmp
5271 while tmp and tmp[0] == 0:
5272 del tmp[0]
5273
5274 # It's a zero
5275 if not tmp:
5276 if backup:
5277 return (sign, tuple(backup), exp)
5278 return (sign, (0,), exp)
5279 mantissa = tuple(tmp)
5280
5281 return (sign, mantissa, exp)
5282
5283
5284if __name__ == '__main__':
5285 import doctest, sys
5286 doctest.testmod(sys.modules[__name__])