blob: fa41722c240427f2230c3aee972d9f59145d5035 [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):
Facundo Batista1a191df2007-10-02 17:01:24 +0000682 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000683
Facundo Batista1a191df2007-10-02 17:01:24 +0000684 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000685 """
Facundo Batista1a191df2007-10-02 17:01:24 +0000686 return self._is_special or self._int[0] != 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000687
Facundo Batista353750c2007-09-13 18:13:15 +0000688 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000689 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000690 if other is NotImplemented:
Facundo Batista353750c2007-09-13 18:13:15 +0000691 # Never return NotImplemented
692 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000693
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000694 if self._is_special or other._is_special:
Facundo Batista353750c2007-09-13 18:13:15 +0000695 # check for nans, without raising on a signaling nan
696 if self._isnan() or other._isnan():
Facundo Batista59c58842007-04-10 12:58:45 +0000697 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000698
699 # INF = INF
700 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000701
Facundo Batista353750c2007-09-13 18:13:15 +0000702 # check for zeros; note that cmp(0, -0) should return 0
703 if not self:
704 if not other:
705 return 0
706 else:
707 return -((-1)**other._sign)
708 if not other:
709 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000710
Facundo Batista59c58842007-04-10 12:58:45 +0000711 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000712 if other._sign < self._sign:
713 return -1
714 if self._sign < other._sign:
715 return 1
716
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000717 self_adjusted = self.adjusted()
718 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000719 if self_adjusted == other_adjusted:
720 self_padded = self._int + (0,)*(self._exp - other._exp)
721 other_padded = other._int + (0,)*(other._exp - self._exp)
722 return cmp(self_padded, other_padded) * (-1)**self._sign
723 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000724 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000725 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000726 return -((-1)**self._sign)
727
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000728 def __eq__(self, other):
729 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000730 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000731 return self.__cmp__(other) == 0
732
733 def __ne__(self, other):
734 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000735 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000736 return self.__cmp__(other) != 0
737
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000738 def compare(self, other, context=None):
739 """Compares one to another.
740
741 -1 => a < b
742 0 => a = b
743 1 => a > b
744 NaN => one is NaN
745 Like __cmp__, but returns Decimal instances.
746 """
Facundo Batista353750c2007-09-13 18:13:15 +0000747 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000748
Facundo Batista59c58842007-04-10 12:58:45 +0000749 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000750 if (self._is_special or other and other._is_special):
751 ans = self._check_nans(other, context)
752 if ans:
753 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000754
Facundo Batista353750c2007-09-13 18:13:15 +0000755 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000756
757 def __hash__(self):
758 """x.__hash__() <==> hash(x)"""
759 # Decimal integers must hash the same as the ints
760 # Non-integer decimals are normalized and hashed as strings
Georg Brandl1fb9f522006-05-11 19:57:09 +0000761 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000762 if self._is_special:
763 if self._isnan():
764 raise TypeError('Cannot hash a NaN value.')
765 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000766 if not self:
767 return 0
768 if self._isinteger():
769 op = _WorkRep(self.to_integral_value())
770 # to make computation feasible for Decimals with large
771 # exponent, we use the fact that hash(n) == hash(m) for
772 # any two nonzero integers n and m such that (i) n and m
773 # have the same sign, and (ii) n is congruent to m modulo
774 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
775 # hash((-1)**s*c*pow(10, e, 2**64-1).
776 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000777 return hash(str(self.normalize()))
778
779 def as_tuple(self):
780 """Represents the number as a triple tuple.
781
782 To show the internals exactly as they are.
783 """
784 return (self._sign, self._int, self._exp)
785
786 def __repr__(self):
787 """Represents the number as an instance of Decimal."""
788 # Invariant: eval(repr(d)) == d
789 return 'Decimal("%s")' % str(self)
790
Facundo Batista353750c2007-09-13 18:13:15 +0000791 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000792 """Return string representation of the number in scientific notation.
793
794 Captures all of the information in the underlying representation.
795 """
796
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000797 if self._is_special:
798 if self._isnan():
799 minus = '-'*self._sign
800 if self._int == (0,):
801 info = ''
802 else:
803 info = ''.join(map(str, self._int))
804 if self._isnan() == 2:
805 return minus + 'sNaN' + info
806 return minus + 'NaN' + info
807 if self._isinfinity():
808 minus = '-'*self._sign
809 return minus + 'Infinity'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000810
811 if context is None:
812 context = getcontext()
813
814 tmp = map(str, self._int)
815 numdigits = len(self._int)
816 leftdigits = self._exp + numdigits
Facundo Batista59c58842007-04-10 12:58:45 +0000817 if eng and not self: # self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
818 if self._exp < 0 and self._exp >= -6: # short, no need for e/E
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000819 s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
820 return s
Facundo Batista59c58842007-04-10 12:58:45 +0000821 # exp is closest mult. of 3 >= self._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000822 exp = ((self._exp - 1)// 3 + 1) * 3
823 if exp != self._exp:
824 s = '0.'+'0'*(exp - self._exp)
825 else:
826 s = '0'
827 if exp != 0:
828 if context.capitals:
829 s += 'E'
830 else:
831 s += 'e'
832 if exp > 0:
Facundo Batista59c58842007-04-10 12:58:45 +0000833 s += '+' # 0.0e+3, not 0.0e3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000834 s += str(exp)
835 s = '-'*self._sign + s
836 return s
837 if eng:
838 dotplace = (leftdigits-1)%3+1
839 adjexp = leftdigits -1 - (leftdigits-1)%3
840 else:
841 adjexp = leftdigits-1
842 dotplace = 1
843 if self._exp == 0:
844 pass
845 elif self._exp < 0 and adjexp >= 0:
846 tmp.insert(leftdigits, '.')
847 elif self._exp < 0 and adjexp >= -6:
848 tmp[0:0] = ['0'] * int(-leftdigits)
849 tmp.insert(0, '0.')
850 else:
851 if numdigits > dotplace:
852 tmp.insert(dotplace, '.')
853 elif numdigits < dotplace:
854 tmp.extend(['0']*(dotplace-numdigits))
855 if adjexp:
856 if not context.capitals:
857 tmp.append('e')
858 else:
859 tmp.append('E')
860 if adjexp > 0:
861 tmp.append('+')
862 tmp.append(str(adjexp))
863 if eng:
864 while tmp[0:1] == ['0']:
865 tmp[0:1] = []
866 if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
867 tmp[0:0] = ['0']
868 if self._sign:
869 tmp.insert(0, '-')
870
871 return ''.join(tmp)
872
873 def to_eng_string(self, context=None):
874 """Convert to engineering-type string.
875
876 Engineering notation has an exponent which is a multiple of 3, so there
877 are up to 3 digits left of the decimal place.
878
879 Same rules for when in exponential and when as a value as in __str__.
880 """
Facundo Batista353750c2007-09-13 18:13:15 +0000881 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000882
883 def __neg__(self, context=None):
884 """Returns a copy with the sign switched.
885
886 Rounds, if it has reason.
887 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000888 if self._is_special:
889 ans = self._check_nans(context=context)
890 if ans:
891 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000892
893 if not self:
894 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +0000895 ans = self.copy_sign(Dec_0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000896 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000897 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000898
899 if context is None:
900 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000901 if context._rounding_decision == ALWAYS_ROUND:
Facundo Batista353750c2007-09-13 18:13:15 +0000902 return ans._fix(context)
903 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000904
905 def __pos__(self, context=None):
906 """Returns a copy, unless it is a sNaN.
907
908 Rounds the number (if more then precision digits)
909 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000910 if self._is_special:
911 ans = self._check_nans(context=context)
912 if ans:
913 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000914
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000915 if not self:
916 # + (-0) = 0
Facundo Batista353750c2007-09-13 18:13:15 +0000917 ans = self.copy_sign(Dec_0)
918 else:
919 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000920
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000921 if context is None:
922 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000923 if context._rounding_decision == ALWAYS_ROUND:
Facundo Batista353750c2007-09-13 18:13:15 +0000924 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000925 return ans
926
927 def __abs__(self, round=1, context=None):
928 """Returns the absolute value of self.
929
930 If the second argument is 0, do not round.
931 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000932 if self._is_special:
933 ans = self._check_nans(context=context)
934 if ans:
935 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000936
937 if not round:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000938 if context is None:
939 context = getcontext()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000940 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000941 context._set_rounding_decision(NEVER_ROUND)
942
943 if self._sign:
944 ans = self.__neg__(context=context)
945 else:
946 ans = self.__pos__(context=context)
947
948 return ans
949
950 def __add__(self, other, context=None):
951 """Returns self + other.
952
953 -INF + INF (or the reverse) cause InvalidOperation errors.
954 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000955 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000956 if other is NotImplemented:
957 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000958
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000959 if context is None:
960 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000961
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000962 if self._is_special or other._is_special:
963 ans = self._check_nans(other, context)
964 if ans:
965 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000966
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000967 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000968 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000969 if self._sign != other._sign and other._isinfinity():
970 return context._raise_error(InvalidOperation, '-INF + INF')
971 return Decimal(self)
972 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000973 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000974
975 shouldround = context._rounding_decision == ALWAYS_ROUND
976
977 exp = min(self._exp, other._exp)
978 negativezero = 0
979 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +0000980 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000981 negativezero = 1
982
983 if not self and not other:
984 sign = min(self._sign, other._sign)
985 if negativezero:
986 sign = 1
Facundo Batista353750c2007-09-13 18:13:15 +0000987 ans = Decimal( (sign, (0,), exp))
988 if shouldround:
989 ans = ans._fix(context)
990 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000991 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +0000992 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +0000993 ans = other._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000994 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000995 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000996 return ans
997 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +0000998 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +0000999 ans = self._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001001 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001002 return ans
1003
1004 op1 = _WorkRep(self)
1005 op2 = _WorkRep(other)
1006 op1, op2 = _normalize(op1, op2, shouldround, context.prec)
1007
1008 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001010 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001011 if op1.int == op2.int:
Facundo Batista353750c2007-09-13 18:13:15 +00001012 ans = Decimal((negativezero, (0,), exp))
1013 if shouldround:
1014 ans = ans._fix(context)
1015 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001016 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001017 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001018 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001019 if op1.sign == 1:
1020 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001021 op1.sign, op2.sign = op2.sign, op1.sign
1022 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001023 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001024 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001025 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001026 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001027 op1.sign, op2.sign = (0, 0)
1028 else:
1029 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001030 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001031
Raymond Hettinger17931de2004-10-27 06:21:46 +00001032 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001033 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001034 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001035 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001036
1037 result.exp = op1.exp
1038 ans = Decimal(result)
1039 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001040 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001041 return ans
1042
1043 __radd__ = __add__
1044
1045 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001046 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001047 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001048 if other is NotImplemented:
1049 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001050
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001051 if self._is_special or other._is_special:
1052 ans = self._check_nans(other, context=context)
1053 if ans:
1054 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055
Facundo Batista353750c2007-09-13 18:13:15 +00001056 # self - other is computed as self + other.copy_negate()
1057 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001058
1059 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001060 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001061 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001062 if other is NotImplemented:
1063 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001064
Facundo Batista353750c2007-09-13 18:13:15 +00001065 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001066
Facundo Batista353750c2007-09-13 18:13:15 +00001067 def _increment(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001068 """Special case of add, adding 1eExponent
1069
1070 Since it is common, (rounding, for example) this adds
1071 (sign)*one E self._exp to the number more efficiently than add.
1072
Facundo Batista353750c2007-09-13 18:13:15 +00001073 Assumes that self is nonspecial.
1074
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001075 For example:
1076 Decimal('5.624e10')._increment() == Decimal('5.625e10')
1077 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001078 L = list(self._int)
1079 L[-1] += 1
1080 spot = len(L)-1
1081 while L[spot] == 10:
1082 L[spot] = 0
1083 if spot == 0:
1084 L[0:0] = [1]
1085 break
1086 L[spot-1] += 1
1087 spot -= 1
Facundo Batista353750c2007-09-13 18:13:15 +00001088 return Decimal((self._sign, L, self._exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001089
1090 def __mul__(self, other, context=None):
1091 """Return self * other.
1092
1093 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1094 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001095 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001096 if other is NotImplemented:
1097 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001098
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001099 if context is None:
1100 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001101
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001102 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001103
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001104 if self._is_special or other._is_special:
1105 ans = self._check_nans(other, context)
1106 if ans:
1107 return ans
1108
1109 if self._isinfinity():
1110 if not other:
1111 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1112 return Infsign[resultsign]
1113
1114 if other._isinfinity():
1115 if not self:
1116 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1117 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001118
1119 resultexp = self._exp + other._exp
1120 shouldround = context._rounding_decision == ALWAYS_ROUND
1121
1122 # Special case for multiplying by zero
1123 if not self or not other:
1124 ans = Decimal((resultsign, (0,), resultexp))
1125 if shouldround:
Facundo Batista59c58842007-04-10 12:58:45 +00001126 # Fixing in case the exponent is out of bounds
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001127 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001128 return ans
1129
1130 # Special case for multiplying by power of 10
1131 if self._int == (1,):
1132 ans = Decimal((resultsign, other._int, resultexp))
1133 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001134 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001135 return ans
1136 if other._int == (1,):
1137 ans = Decimal((resultsign, self._int, resultexp))
1138 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001139 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001140 return ans
1141
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001142 op1 = _WorkRep(self)
1143 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001144
Facundo Batista59c58842007-04-10 12:58:45 +00001145 ans = Decimal((resultsign, map(int, str(op1.int * op2.int)), resultexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001146 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001147 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001148
1149 return ans
1150 __rmul__ = __mul__
1151
1152 def __div__(self, other, context=None):
1153 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001154 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001155 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001156 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001157
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001158 if context is None:
1159 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001160
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001161 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001162
1163 if self._is_special or other._is_special:
1164 ans = self._check_nans(other, context)
1165 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001166 return ans
1167
1168 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001169 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001170
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001171 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001172 return Infsign[sign]
1173
1174 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001175 context._raise_error(Clamped, 'Division by infinity')
1176 return Decimal((sign, (0,), context.Etiny()))
1177
1178 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001179 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001180 if not self:
1181 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001182 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001183
Facundo Batistacce8df22007-09-18 16:53:18 +00001184 if not self:
1185 exp = self._exp - other._exp
1186 coeff = 0
1187 else:
1188 # OK, so neither = 0, INF or NaN
1189 shift = len(other._int) - len(self._int) + context.prec + 1
1190 exp = self._exp - other._exp - shift
1191 op1 = _WorkRep(self)
1192 op2 = _WorkRep(other)
1193 if shift >= 0:
1194 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1195 else:
1196 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1197 if remainder:
1198 # result is not exact; adjust to ensure correct rounding
1199 if coeff % 5 == 0:
1200 coeff += 1
1201 else:
1202 # result is exact; get as close to ideal exponent as possible
1203 ideal_exp = self._exp - other._exp
1204 while exp < ideal_exp and coeff % 10 == 0:
1205 coeff //= 10
1206 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001207
Facundo Batistacce8df22007-09-18 16:53:18 +00001208 ans = Decimal((sign, map(int, str(coeff)), exp))
1209 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001210
Facundo Batistacce8df22007-09-18 16:53:18 +00001211 __truediv__ = __div__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001212
Facundo Batistacce8df22007-09-18 16:53:18 +00001213 def _divide(self, other, context):
1214 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001215
Facundo Batistacce8df22007-09-18 16:53:18 +00001216 Assumes that neither self nor other is a NaN, that self is not
1217 infinite and that other is nonzero.
1218 """
1219 sign = self._sign ^ other._sign
1220 if other._isinfinity():
1221 ideal_exp = self._exp
1222 else:
1223 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001224
Facundo Batistacce8df22007-09-18 16:53:18 +00001225 expdiff = self.adjusted() - other.adjusted()
1226 if not self or other._isinfinity() or expdiff <= -2:
1227 return (Decimal((sign, (0,), 0)),
1228 self._rescale(ideal_exp, context.rounding))
1229 if expdiff <= context.prec:
1230 op1 = _WorkRep(self)
1231 op2 = _WorkRep(other)
1232 if op1.exp >= op2.exp:
1233 op1.int *= 10**(op1.exp - op2.exp)
1234 else:
1235 op2.int *= 10**(op2.exp - op1.exp)
1236 q, r = divmod(op1.int, op2.int)
1237 if q < 10**context.prec:
1238 return (Decimal((sign, map(int, str(q)), 0)),
1239 Decimal((self._sign, map(int, str(r)), ideal_exp)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001240
Facundo Batistacce8df22007-09-18 16:53:18 +00001241 # Here the quotient is too large to be representable
1242 ans = context._raise_error(DivisionImpossible,
1243 'quotient too large in //, % or divmod')
1244 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001245
1246 def __rdiv__(self, other, context=None):
1247 """Swaps self/other and returns __div__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001248 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001249 if other is NotImplemented:
1250 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001251 return other.__div__(self, context=context)
1252 __rtruediv__ = __rdiv__
1253
1254 def __divmod__(self, other, context=None):
1255 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001256 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001257 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001258 other = _convert_other(other)
1259 if other is NotImplemented:
1260 return other
1261
1262 if context is None:
1263 context = getcontext()
1264
1265 ans = self._check_nans(other, context)
1266 if ans:
1267 return (ans, ans)
1268
1269 sign = self._sign ^ other._sign
1270 if self._isinfinity():
1271 if other._isinfinity():
1272 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1273 return ans, ans
1274 else:
1275 return (Infsign[sign],
1276 context._raise_error(InvalidOperation, 'INF % x'))
1277
1278 if not other:
1279 if not self:
1280 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1281 return ans, ans
1282 else:
1283 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1284 context._raise_error(InvalidOperation, 'x % 0'))
1285
1286 quotient, remainder = self._divide(other, context)
1287 if context._rounding_decision == ALWAYS_ROUND:
1288 remainder = remainder._fix(context)
1289 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001290
1291 def __rdivmod__(self, other, context=None):
1292 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001293 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001294 if other is NotImplemented:
1295 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001296 return other.__divmod__(self, context=context)
1297
1298 def __mod__(self, other, context=None):
1299 """
1300 self % other
1301 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001302 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001303 if other is NotImplemented:
1304 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001305
Facundo Batistacce8df22007-09-18 16:53:18 +00001306 if context is None:
1307 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001308
Facundo Batistacce8df22007-09-18 16:53:18 +00001309 ans = self._check_nans(other, context)
1310 if ans:
1311 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001312
Facundo Batistacce8df22007-09-18 16:53:18 +00001313 if self._isinfinity():
1314 return context._raise_error(InvalidOperation, 'INF % x')
1315 elif not other:
1316 if self:
1317 return context._raise_error(InvalidOperation, 'x % 0')
1318 else:
1319 return context._raise_error(DivisionUndefined, '0 % 0')
1320
1321 remainder = self._divide(other, context)[1]
1322 if context._rounding_decision == ALWAYS_ROUND:
1323 remainder = remainder._fix(context)
1324 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001325
1326 def __rmod__(self, other, context=None):
1327 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001328 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001329 if other is NotImplemented:
1330 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001331 return other.__mod__(self, context=context)
1332
1333 def remainder_near(self, other, context=None):
1334 """
1335 Remainder nearest to 0- abs(remainder-near) <= other/2
1336 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001337 if context is None:
1338 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001339
Facundo Batista353750c2007-09-13 18:13:15 +00001340 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001341
Facundo Batista353750c2007-09-13 18:13:15 +00001342 ans = self._check_nans(other, context)
1343 if ans:
1344 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001345
Facundo Batista353750c2007-09-13 18:13:15 +00001346 # self == +/-infinity -> InvalidOperation
1347 if self._isinfinity():
1348 return context._raise_error(InvalidOperation,
1349 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001350
Facundo Batista353750c2007-09-13 18:13:15 +00001351 # other == 0 -> either InvalidOperation or DivisionUndefined
1352 if not other:
1353 if self:
1354 return context._raise_error(InvalidOperation,
1355 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001356 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001357 return context._raise_error(DivisionUndefined,
1358 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001359
Facundo Batista353750c2007-09-13 18:13:15 +00001360 # other = +/-infinity -> remainder = self
1361 if other._isinfinity():
1362 ans = Decimal(self)
1363 return ans._fix(context)
1364
1365 # self = 0 -> remainder = self, with ideal exponent
1366 ideal_exponent = min(self._exp, other._exp)
1367 if not self:
1368 ans = Decimal((self._sign, (0,), ideal_exponent))
1369 return ans._fix(context)
1370
1371 # catch most cases of large or small quotient
1372 expdiff = self.adjusted() - other.adjusted()
1373 if expdiff >= context.prec + 1:
1374 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001375 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001376 if expdiff <= -2:
1377 # expdiff <= -2 => abs(self/other) < 0.1
1378 ans = self._rescale(ideal_exponent, context.rounding)
1379 return ans._fix(context)
1380
1381 # adjust both arguments to have the same exponent, then divide
1382 op1 = _WorkRep(self)
1383 op2 = _WorkRep(other)
1384 if op1.exp >= op2.exp:
1385 op1.int *= 10**(op1.exp - op2.exp)
1386 else:
1387 op2.int *= 10**(op2.exp - op1.exp)
1388 q, r = divmod(op1.int, op2.int)
1389 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1390 # 10**ideal_exponent. Apply correction to ensure that
1391 # abs(remainder) <= abs(other)/2
1392 if 2*r + (q&1) > op2.int:
1393 r -= op2.int
1394 q += 1
1395
1396 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001397 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001398
1399 # result has same sign as self unless r is negative
1400 sign = self._sign
1401 if r < 0:
1402 sign = 1-sign
1403 r = -r
1404
1405 ans = Decimal((sign, map(int, str(r)), ideal_exponent))
1406 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001407
1408 def __floordiv__(self, other, context=None):
1409 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001410 other = _convert_other(other)
1411 if other is NotImplemented:
1412 return other
1413
1414 if context is None:
1415 context = getcontext()
1416
1417 ans = self._check_nans(other, context)
1418 if ans:
1419 return ans
1420
1421 if self._isinfinity():
1422 if other._isinfinity():
1423 return context._raise_error(InvalidOperation, 'INF // INF')
1424 else:
1425 return Infsign[self._sign ^ other._sign]
1426
1427 if not other:
1428 if self:
1429 return context._raise_error(DivisionByZero, 'x // 0',
1430 self._sign ^ other._sign)
1431 else:
1432 return context._raise_error(DivisionUndefined, '0 // 0')
1433
1434 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001435
1436 def __rfloordiv__(self, other, context=None):
1437 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001438 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001439 if other is NotImplemented:
1440 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001441 return other.__floordiv__(self, context=context)
1442
1443 def __float__(self):
1444 """Float representation."""
1445 return float(str(self))
1446
1447 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001448 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001449 if self._is_special:
1450 if self._isnan():
1451 context = getcontext()
1452 return context._raise_error(InvalidContext)
1453 elif self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001454 raise OverflowError("Cannot convert infinity to long")
Facundo Batista353750c2007-09-13 18:13:15 +00001455 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001456 if self._exp >= 0:
Facundo Batista353750c2007-09-13 18:13:15 +00001457 return s*int(''.join(map(str, self._int)))*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001458 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001459 return s*int(''.join(map(str, self._int))[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001460
1461 def __long__(self):
1462 """Converts to a long.
1463
1464 Equivalent to long(int(self))
1465 """
1466 return long(self.__int__())
1467
Facundo Batista353750c2007-09-13 18:13:15 +00001468 def _fix_nan(self, context):
1469 """Decapitate the payload of a NaN to fit the context"""
1470 payload = self._int
1471
1472 # maximum length of payload is precision if _clamp=0,
1473 # precision-1 if _clamp=1.
1474 max_payload_len = context.prec - context._clamp
1475 if len(payload) > max_payload_len:
1476 pos = len(payload)-max_payload_len
1477 while pos < len(payload) and payload[pos] == 0:
1478 pos += 1
1479 payload = payload[pos:]
1480 return Decimal((self._sign, payload, self._exp))
Facundo Batista6c398da2007-09-17 17:30:13 +00001481 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001482
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001483 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001484 """Round if it is necessary to keep self within prec precision.
1485
1486 Rounds and fixes the exponent. Does not raise on a sNaN.
1487
1488 Arguments:
1489 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001490 context - context used.
1491 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001492
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001493 if context is None:
1494 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001495
Facundo Batista353750c2007-09-13 18:13:15 +00001496 if self._is_special:
1497 if self._isnan():
1498 # decapitate payload if necessary
1499 return self._fix_nan(context)
1500 else:
1501 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001502 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001503
Facundo Batista353750c2007-09-13 18:13:15 +00001504 # if self is zero then exponent should be between Etiny and
1505 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1506 Etiny = context.Etiny()
1507 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001508 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001509 exp_max = [context.Emax, Etop][context._clamp]
1510 new_exp = min(max(self._exp, Etiny), exp_max)
1511 if new_exp != self._exp:
1512 context._raise_error(Clamped)
1513 return Decimal((self._sign, (0,), new_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001514 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001515 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001516
1517 # exp_min is the smallest allowable exponent of the result,
1518 # equal to max(self.adjusted()-context.prec+1, Etiny)
1519 exp_min = len(self._int) + self._exp - context.prec
1520 if exp_min > Etop:
1521 # overflow: exp_min > Etop iff self.adjusted() > Emax
1522 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001523 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001524 return context._raise_error(Overflow, 'above Emax', self._sign)
1525 self_is_subnormal = exp_min < Etiny
1526 if self_is_subnormal:
1527 context._raise_error(Subnormal)
1528 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001529
Facundo Batista353750c2007-09-13 18:13:15 +00001530 # round if self has too many digits
1531 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001532 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001533 ans = self._rescale(exp_min, context.rounding)
1534 if ans != self:
1535 context._raise_error(Inexact)
1536 if self_is_subnormal:
1537 context._raise_error(Underflow)
1538 if not ans:
1539 # raise Clamped on underflow to 0
1540 context._raise_error(Clamped)
1541 elif len(ans._int) == context.prec+1:
1542 # we get here only if rescaling rounds the
1543 # cofficient up to exactly 10**context.prec
1544 if ans._exp < Etop:
1545 ans = Decimal((ans._sign, ans._int[:-1], ans._exp+1))
1546 else:
1547 # Inexact and Rounded have already been raised
1548 ans = context._raise_error(Overflow, 'above Emax',
1549 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001550 return ans
1551
Facundo Batista353750c2007-09-13 18:13:15 +00001552 # fold down if _clamp == 1 and self has too few digits
1553 if context._clamp == 1 and self._exp > Etop:
1554 context._raise_error(Clamped)
1555 self_padded = self._int + (0,)*(self._exp - Etop)
1556 return Decimal((self._sign, self_padded, Etop))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001557
Facundo Batista353750c2007-09-13 18:13:15 +00001558 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001559 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001560
1561 _pick_rounding_function = {}
1562
Facundo Batista353750c2007-09-13 18:13:15 +00001563 # for each of the rounding functions below:
1564 # self is a finite, nonzero Decimal
1565 # prec is an integer satisfying 0 <= prec < len(self._int)
1566 # the rounded result will have exponent self._exp + len(self._int) - prec;
1567
1568 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001569 """Also known as round-towards-0, truncate."""
Facundo Batista353750c2007-09-13 18:13:15 +00001570 newexp = self._exp + len(self._int) - prec
1571 return Decimal((self._sign, self._int[:prec] or (0,), newexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001572
Facundo Batista353750c2007-09-13 18:13:15 +00001573 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001574 """Rounds away from 0."""
Facundo Batista353750c2007-09-13 18:13:15 +00001575 newexp = self._exp + len(self._int) - prec
1576 tmp = Decimal((self._sign, self._int[:prec] or (0,), newexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001577 for digit in self._int[prec:]:
1578 if digit != 0:
Facundo Batista353750c2007-09-13 18:13:15 +00001579 return tmp._increment()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001580 return tmp
1581
Facundo Batista353750c2007-09-13 18:13:15 +00001582 def _round_half_up(self, prec):
1583 """Rounds 5 up (away from 0)"""
1584 if self._int[prec] >= 5:
1585 return self._round_up(prec)
1586 else:
1587 return self._round_down(prec)
1588
1589 def _round_half_down(self, prec):
1590 """Round 5 down"""
1591 if self._int[prec] == 5:
1592 for digit in self._int[prec+1:]:
1593 if digit != 0:
1594 break
1595 else:
1596 return self._round_down(prec)
1597 return self._round_half_up(prec)
1598
1599 def _round_half_even(self, prec):
1600 """Round 5 to even, rest to nearest."""
1601 if prec and self._int[prec-1] & 1:
1602 return self._round_half_up(prec)
1603 else:
1604 return self._round_half_down(prec)
1605
1606 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001607 """Rounds up (not away from 0 if negative.)"""
1608 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001609 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001610 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001611 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001612
Facundo Batista353750c2007-09-13 18:13:15 +00001613 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001614 """Rounds down (not towards 0 if negative)"""
1615 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001616 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001617 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001618 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001619
Facundo Batista353750c2007-09-13 18:13:15 +00001620 def _round_05up(self, prec):
1621 """Round down unless digit prec-1 is 0 or 5."""
1622 if prec == 0 or self._int[prec-1] in (0, 5):
1623 return self._round_up(prec)
1624 else:
1625 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001626
Facundo Batista353750c2007-09-13 18:13:15 +00001627 def fma(self, other, third, context=None):
1628 """Fused multiply-add.
1629
1630 Returns self*other+third with no rounding of the intermediate
1631 product self*other.
1632
1633 self and other are multiplied together, with no rounding of
1634 the result. The third operand is then added to the result,
1635 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001636 """
Facundo Batista353750c2007-09-13 18:13:15 +00001637
1638 other = _convert_other(other, raiseit=True)
1639 third = _convert_other(third, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001640
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001641 if context is None:
1642 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001643
Facundo Batista353750c2007-09-13 18:13:15 +00001644 # do self*other in fresh context with no traps and no rounding
1645 mul_context = Context(traps=[], flags=[],
1646 _rounding_decision=NEVER_ROUND)
1647 product = self.__mul__(other, mul_context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001648
Facundo Batista353750c2007-09-13 18:13:15 +00001649 if mul_context.flags[InvalidOperation]:
1650 # reraise in current context
1651 return context._raise_error(InvalidOperation,
1652 'invalid multiplication in fma',
1653 1, product)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001654
Facundo Batista353750c2007-09-13 18:13:15 +00001655 ans = product.__add__(third, context)
1656 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001657
Facundo Batista353750c2007-09-13 18:13:15 +00001658 def _power_modulo(self, other, modulo, context=None):
1659 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001660
Facundo Batista353750c2007-09-13 18:13:15 +00001661 # if can't convert other and modulo to Decimal, raise
1662 # TypeError; there's no point returning NotImplemented (no
1663 # equivalent of __rpow__ for three argument pow)
1664 other = _convert_other(other, raiseit=True)
1665 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001666
Facundo Batista353750c2007-09-13 18:13:15 +00001667 if context is None:
1668 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001669
Facundo Batista353750c2007-09-13 18:13:15 +00001670 # deal with NaNs: if there are any sNaNs then first one wins,
1671 # (i.e. behaviour for NaNs is identical to that of fma)
1672 self_is_nan = self._isnan()
1673 other_is_nan = other._isnan()
1674 modulo_is_nan = modulo._isnan()
1675 if self_is_nan or other_is_nan or modulo_is_nan:
1676 if self_is_nan == 2:
1677 return context._raise_error(InvalidOperation, 'sNaN',
1678 1, self)
1679 if other_is_nan == 2:
1680 return context._raise_error(InvalidOperation, 'sNaN',
1681 1, other)
1682 if modulo_is_nan == 2:
1683 return context._raise_error(InvalidOperation, 'sNaN',
1684 1, modulo)
1685 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001686 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001687 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001688 return other._fix_nan(context)
1689 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001690
Facundo Batista353750c2007-09-13 18:13:15 +00001691 # check inputs: we apply same restrictions as Python's pow()
1692 if not (self._isinteger() and
1693 other._isinteger() and
1694 modulo._isinteger()):
1695 return context._raise_error(InvalidOperation,
1696 'pow() 3rd argument not allowed '
1697 'unless all arguments are integers')
1698 if other < 0:
1699 return context._raise_error(InvalidOperation,
1700 'pow() 2nd argument cannot be '
1701 'negative when 3rd argument specified')
1702 if not modulo:
1703 return context._raise_error(InvalidOperation,
1704 'pow() 3rd argument cannot be 0')
1705
1706 # additional restriction for decimal: the modulus must be less
1707 # than 10**prec in absolute value
1708 if modulo.adjusted() >= context.prec:
1709 return context._raise_error(InvalidOperation,
1710 'insufficient precision: pow() 3rd '
1711 'argument must not have more than '
1712 'precision digits')
1713
1714 # define 0**0 == NaN, for consistency with two-argument pow
1715 # (even though it hurts!)
1716 if not other and not self:
1717 return context._raise_error(InvalidOperation,
1718 'at least one of pow() 1st argument '
1719 'and 2nd argument must be nonzero ;'
1720 '0**0 is not defined')
1721
1722 # compute sign of result
1723 if other._iseven():
1724 sign = 0
1725 else:
1726 sign = self._sign
1727
1728 # convert modulo to a Python integer, and self and other to
1729 # Decimal integers (i.e. force their exponents to be >= 0)
1730 modulo = abs(int(modulo))
1731 base = _WorkRep(self.to_integral_value())
1732 exponent = _WorkRep(other.to_integral_value())
1733
1734 # compute result using integer pow()
1735 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1736 for i in xrange(exponent.exp):
1737 base = pow(base, 10, modulo)
1738 base = pow(base, exponent.int, modulo)
1739
1740 return Decimal((sign, map(int, str(base)), 0))
1741
1742 def _power_exact(self, other, p):
1743 """Attempt to compute self**other exactly.
1744
1745 Given Decimals self and other and an integer p, attempt to
1746 compute an exact result for the power self**other, with p
1747 digits of precision. Return None if self**other is not
1748 exactly representable in p digits.
1749
1750 Assumes that elimination of special cases has already been
1751 performed: self and other must both be nonspecial; self must
1752 be positive and not numerically equal to 1; other must be
1753 nonzero. For efficiency, other._exp should not be too large,
1754 so that 10**abs(other._exp) is a feasible calculation."""
1755
1756 # In the comments below, we write x for the value of self and
1757 # y for the value of other. Write x = xc*10**xe and y =
1758 # yc*10**ye.
1759
1760 # The main purpose of this method is to identify the *failure*
1761 # of x**y to be exactly representable with as little effort as
1762 # possible. So we look for cheap and easy tests that
1763 # eliminate the possibility of x**y being exact. Only if all
1764 # these tests are passed do we go on to actually compute x**y.
1765
1766 # Here's the main idea. First normalize both x and y. We
1767 # express y as a rational m/n, with m and n relatively prime
1768 # and n>0. Then for x**y to be exactly representable (at
1769 # *any* precision), xc must be the nth power of a positive
1770 # integer and xe must be divisible by n. If m is negative
1771 # then additionally xc must be a power of either 2 or 5, hence
1772 # a power of 2**n or 5**n.
1773 #
1774 # There's a limit to how small |y| can be: if y=m/n as above
1775 # then:
1776 #
1777 # (1) if xc != 1 then for the result to be representable we
1778 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1779 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1780 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1781 # representable.
1782 #
1783 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1784 # |y| < 1/|xe| then the result is not representable.
1785 #
1786 # Note that since x is not equal to 1, at least one of (1) and
1787 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1788 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1789 #
1790 # There's also a limit to how large y can be, at least if it's
1791 # positive: the normalized result will have coefficient xc**y,
1792 # so if it's representable then xc**y < 10**p, and y <
1793 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1794 # not exactly representable.
1795
1796 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1797 # so |y| < 1/xe and the result is not representable.
1798 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1799 # < 1/nbits(xc).
1800
1801 x = _WorkRep(self)
1802 xc, xe = x.int, x.exp
1803 while xc % 10 == 0:
1804 xc //= 10
1805 xe += 1
1806
1807 y = _WorkRep(other)
1808 yc, ye = y.int, y.exp
1809 while yc % 10 == 0:
1810 yc //= 10
1811 ye += 1
1812
1813 # case where xc == 1: result is 10**(xe*y), with xe*y
1814 # required to be an integer
1815 if xc == 1:
1816 if ye >= 0:
1817 exponent = xe*yc*10**ye
1818 else:
1819 exponent, remainder = divmod(xe*yc, 10**-ye)
1820 if remainder:
1821 return None
1822 if y.sign == 1:
1823 exponent = -exponent
1824 # if other is a nonnegative integer, use ideal exponent
1825 if other._isinteger() and other._sign == 0:
1826 ideal_exponent = self._exp*int(other)
1827 zeros = min(exponent-ideal_exponent, p-1)
1828 else:
1829 zeros = 0
1830 return Decimal((0, (1,) + (0,)*zeros, exponent-zeros))
1831
1832 # case where y is negative: xc must be either a power
1833 # of 2 or a power of 5.
1834 if y.sign == 1:
1835 last_digit = xc % 10
1836 if last_digit in (2,4,6,8):
1837 # quick test for power of 2
1838 if xc & -xc != xc:
1839 return None
1840 # now xc is a power of 2; e is its exponent
1841 e = _nbits(xc)-1
1842 # find e*y and xe*y; both must be integers
1843 if ye >= 0:
1844 y_as_int = yc*10**ye
1845 e = e*y_as_int
1846 xe = xe*y_as_int
1847 else:
1848 ten_pow = 10**-ye
1849 e, remainder = divmod(e*yc, ten_pow)
1850 if remainder:
1851 return None
1852 xe, remainder = divmod(xe*yc, ten_pow)
1853 if remainder:
1854 return None
1855
1856 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1857 return None
1858 xc = 5**e
1859
1860 elif last_digit == 5:
1861 # e >= log_5(xc) if xc is a power of 5; we have
1862 # equality all the way up to xc=5**2658
1863 e = _nbits(xc)*28//65
1864 xc, remainder = divmod(5**e, xc)
1865 if remainder:
1866 return None
1867 while xc % 5 == 0:
1868 xc //= 5
1869 e -= 1
1870 if ye >= 0:
1871 y_as_integer = yc*10**ye
1872 e = e*y_as_integer
1873 xe = xe*y_as_integer
1874 else:
1875 ten_pow = 10**-ye
1876 e, remainder = divmod(e*yc, ten_pow)
1877 if remainder:
1878 return None
1879 xe, remainder = divmod(xe*yc, ten_pow)
1880 if remainder:
1881 return None
1882 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1883 return None
1884 xc = 2**e
1885 else:
1886 return None
1887
1888 if xc >= 10**p:
1889 return None
1890 xe = -e-xe
1891 return Decimal((0, map(int, str(xc)), xe))
1892
1893 # now y is positive; find m and n such that y = m/n
1894 if ye >= 0:
1895 m, n = yc*10**ye, 1
1896 else:
1897 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1898 return None
1899 xc_bits = _nbits(xc)
1900 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1901 return None
1902 m, n = yc, 10**(-ye)
1903 while m % 2 == n % 2 == 0:
1904 m //= 2
1905 n //= 2
1906 while m % 5 == n % 5 == 0:
1907 m //= 5
1908 n //= 5
1909
1910 # compute nth root of xc*10**xe
1911 if n > 1:
1912 # if 1 < xc < 2**n then xc isn't an nth power
1913 if xc != 1 and xc_bits <= n:
1914 return None
1915
1916 xe, rem = divmod(xe, n)
1917 if rem != 0:
1918 return None
1919
1920 # compute nth root of xc using Newton's method
1921 a = 1L << -(-_nbits(xc)//n) # initial estimate
1922 while True:
1923 q, r = divmod(xc, a**(n-1))
1924 if a <= q:
1925 break
1926 else:
1927 a = (a*(n-1) + q)//n
1928 if not (a == q and r == 0):
1929 return None
1930 xc = a
1931
1932 # now xc*10**xe is the nth root of the original xc*10**xe
1933 # compute mth power of xc*10**xe
1934
1935 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1936 # 10**p and the result is not representable.
1937 if xc > 1 and m > p*100//_log10_lb(xc):
1938 return None
1939 xc = xc**m
1940 xe *= m
1941 if xc > 10**p:
1942 return None
1943
1944 # by this point the result *is* exactly representable
1945 # adjust the exponent to get as close as possible to the ideal
1946 # exponent, if necessary
1947 str_xc = str(xc)
1948 if other._isinteger() and other._sign == 0:
1949 ideal_exponent = self._exp*int(other)
1950 zeros = min(xe-ideal_exponent, p-len(str_xc))
1951 else:
1952 zeros = 0
1953 return Decimal((0, map(int, str_xc)+[0,]*zeros, xe-zeros))
1954
1955 def __pow__(self, other, modulo=None, context=None):
1956 """Return self ** other [ % modulo].
1957
1958 With two arguments, compute self**other.
1959
1960 With three arguments, compute (self**other) % modulo. For the
1961 three argument form, the following restrictions on the
1962 arguments hold:
1963
1964 - all three arguments must be integral
1965 - other must be nonnegative
1966 - either self or other (or both) must be nonzero
1967 - modulo must be nonzero and must have at most p digits,
1968 where p is the context precision.
1969
1970 If any of these restrictions is violated the InvalidOperation
1971 flag is raised.
1972
1973 The result of pow(self, other, modulo) is identical to the
1974 result that would be obtained by computing (self**other) %
1975 modulo with unbounded precision, but is computed more
1976 efficiently. It is always exact.
1977 """
1978
1979 if modulo is not None:
1980 return self._power_modulo(other, modulo, context)
1981
1982 other = _convert_other(other)
1983 if other is NotImplemented:
1984 return other
1985
1986 if context is None:
1987 context = getcontext()
1988
1989 # either argument is a NaN => result is NaN
1990 ans = self._check_nans(other, context)
1991 if ans:
1992 return ans
1993
1994 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1995 if not other:
1996 if not self:
1997 return context._raise_error(InvalidOperation, '0 ** 0')
1998 else:
1999 return Dec_p1
2000
2001 # result has sign 1 iff self._sign is 1 and other is an odd integer
2002 result_sign = 0
2003 if self._sign == 1:
2004 if other._isinteger():
2005 if not other._iseven():
2006 result_sign = 1
2007 else:
2008 # -ve**noninteger = NaN
2009 # (-0)**noninteger = 0**noninteger
2010 if self:
2011 return context._raise_error(InvalidOperation,
2012 'x ** y with x negative and y not an integer')
2013 # negate self, without doing any unwanted rounding
2014 self = Decimal((0, self._int, self._exp))
2015
2016 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2017 if not self:
2018 if other._sign == 0:
2019 return Decimal((result_sign, (0,), 0))
2020 else:
2021 return Infsign[result_sign]
2022
2023 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002024 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002025 if other._sign == 0:
2026 return Infsign[result_sign]
2027 else:
2028 return Decimal((result_sign, (0,), 0))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002029
Facundo Batista353750c2007-09-13 18:13:15 +00002030 # 1**other = 1, but the choice of exponent and the flags
2031 # depend on the exponent of self, and on whether other is a
2032 # positive integer, a negative integer, or neither
2033 if self == Dec_p1:
2034 if other._isinteger():
2035 # exp = max(self._exp*max(int(other), 0),
2036 # 1-context.prec) but evaluating int(other) directly
2037 # is dangerous until we know other is small (other
2038 # could be 1e999999999)
2039 if other._sign == 1:
2040 multiplier = 0
2041 elif other > context.prec:
2042 multiplier = context.prec
2043 else:
2044 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002045
Facundo Batista353750c2007-09-13 18:13:15 +00002046 exp = self._exp * multiplier
2047 if exp < 1-context.prec:
2048 exp = 1-context.prec
2049 context._raise_error(Rounded)
2050 else:
2051 context._raise_error(Inexact)
2052 context._raise_error(Rounded)
2053 exp = 1-context.prec
2054
2055 return Decimal((result_sign, (1,)+(0,)*-exp, exp))
2056
2057 # compute adjusted exponent of self
2058 self_adj = self.adjusted()
2059
2060 # self ** infinity is infinity if self > 1, 0 if self < 1
2061 # self ** -infinity is infinity if self < 1, 0 if self > 1
2062 if other._isinfinity():
2063 if (other._sign == 0) == (self_adj < 0):
2064 return Decimal((result_sign, (0,), 0))
2065 else:
2066 return Infsign[result_sign]
2067
2068 # from here on, the result always goes through the call
2069 # to _fix at the end of this function.
2070 ans = None
2071
2072 # crude test to catch cases of extreme overflow/underflow. If
2073 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2074 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2075 # self**other >= 10**(Emax+1), so overflow occurs. The test
2076 # for underflow is similar.
2077 bound = self._log10_exp_bound() + other.adjusted()
2078 if (self_adj >= 0) == (other._sign == 0):
2079 # self > 1 and other +ve, or self < 1 and other -ve
2080 # possibility of overflow
2081 if bound >= len(str(context.Emax)):
2082 ans = Decimal((result_sign, (1,), context.Emax+1))
2083 else:
2084 # self > 1 and other -ve, or self < 1 and other +ve
2085 # possibility of underflow to 0
2086 Etiny = context.Etiny()
2087 if bound >= len(str(-Etiny)):
2088 ans = Decimal((result_sign, (1,), Etiny-1))
2089
2090 # try for an exact result with precision +1
2091 if ans is None:
2092 ans = self._power_exact(other, context.prec + 1)
2093 if ans is not None and result_sign == 1:
2094 ans = Decimal((1, ans._int, ans._exp))
2095
2096 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2097 if ans is None:
2098 p = context.prec
2099 x = _WorkRep(self)
2100 xc, xe = x.int, x.exp
2101 y = _WorkRep(other)
2102 yc, ye = y.int, y.exp
2103 if y.sign == 1:
2104 yc = -yc
2105
2106 # compute correctly rounded result: start with precision +3,
2107 # then increase precision until result is unambiguously roundable
2108 extra = 3
2109 while True:
2110 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2111 if coeff % (5*10**(len(str(coeff))-p-1)):
2112 break
2113 extra += 3
2114
2115 ans = Decimal((result_sign, map(int, str(coeff)), exp))
2116
2117 # the specification says that for non-integer other we need to
2118 # raise Inexact, even when the result is actually exact. In
2119 # the same way, we need to raise Underflow here if the result
2120 # is subnormal. (The call to _fix will take care of raising
2121 # Rounded and Subnormal, as usual.)
2122 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002123 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002124 # pad with zeros up to length context.prec+1 if necessary
2125 if len(ans._int) <= context.prec:
2126 expdiff = context.prec+1 - len(ans._int)
2127 ans = Decimal((ans._sign, ans._int+(0,)*expdiff, ans._exp-expdiff))
2128 if ans.adjusted() < context.Emin:
2129 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002130
Facundo Batista353750c2007-09-13 18:13:15 +00002131 # unlike exp, ln and log10, the power function respects the
2132 # rounding mode; no need to use ROUND_HALF_EVEN here
2133 ans = ans._fix(context)
2134 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002135
2136 def __rpow__(self, other, context=None):
2137 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002138 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002139 if other is NotImplemented:
2140 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002141 return other.__pow__(self, context=context)
2142
2143 def normalize(self, context=None):
2144 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002145
Facundo Batista353750c2007-09-13 18:13:15 +00002146 if context is None:
2147 context = getcontext()
2148
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002149 if self._is_special:
2150 ans = self._check_nans(context=context)
2151 if ans:
2152 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002153
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002154 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002155 if dup._isinfinity():
2156 return dup
2157
2158 if not dup:
2159 return Decimal( (dup._sign, (0,), 0) )
Facundo Batista353750c2007-09-13 18:13:15 +00002160 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002161 end = len(dup._int)
2162 exp = dup._exp
Facundo Batista353750c2007-09-13 18:13:15 +00002163 while dup._int[end-1] == 0 and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002164 exp += 1
2165 end -= 1
2166 return Decimal( (dup._sign, dup._int[:end], exp) )
2167
Facundo Batistabd2fe832007-09-13 18:42:09 +00002168 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002169 """Quantize self so its exponent is the same as that of exp.
2170
2171 Similar to self._rescale(exp._exp) but with error checking.
2172 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002173 exp = _convert_other(exp, raiseit=True)
2174
Facundo Batista353750c2007-09-13 18:13:15 +00002175 if context is None:
2176 context = getcontext()
2177 if rounding is None:
2178 rounding = context.rounding
2179
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002180 if self._is_special or exp._is_special:
2181 ans = self._check_nans(exp, context)
2182 if ans:
2183 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002184
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002185 if exp._isinfinity() or self._isinfinity():
2186 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002187 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002188 return context._raise_error(InvalidOperation,
2189 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002190
Facundo Batistabd2fe832007-09-13 18:42:09 +00002191 # if we're not watching exponents, do a simple rescale
2192 if not watchexp:
2193 ans = self._rescale(exp._exp, rounding)
2194 # raise Inexact and Rounded where appropriate
2195 if ans._exp > self._exp:
2196 context._raise_error(Rounded)
2197 if ans != self:
2198 context._raise_error(Inexact)
2199 return ans
2200
Facundo Batista353750c2007-09-13 18:13:15 +00002201 # exp._exp should be between Etiny and Emax
2202 if not (context.Etiny() <= exp._exp <= context.Emax):
2203 return context._raise_error(InvalidOperation,
2204 'target exponent out of bounds in quantize')
2205
2206 if not self:
2207 ans = Decimal((self._sign, (0,), exp._exp))
2208 return ans._fix(context)
2209
2210 self_adjusted = self.adjusted()
2211 if self_adjusted > context.Emax:
2212 return context._raise_error(InvalidOperation,
2213 'exponent of quantize result too large for current context')
2214 if self_adjusted - exp._exp + 1 > context.prec:
2215 return context._raise_error(InvalidOperation,
2216 'quantize result has too many digits for current context')
2217
2218 ans = self._rescale(exp._exp, rounding)
2219 if ans.adjusted() > context.Emax:
2220 return context._raise_error(InvalidOperation,
2221 'exponent of quantize result too large for current context')
2222 if len(ans._int) > context.prec:
2223 return context._raise_error(InvalidOperation,
2224 'quantize result has too many digits for current context')
2225
2226 # raise appropriate flags
2227 if ans._exp > self._exp:
2228 context._raise_error(Rounded)
2229 if ans != self:
2230 context._raise_error(Inexact)
2231 if ans and ans.adjusted() < context.Emin:
2232 context._raise_error(Subnormal)
2233
2234 # call to fix takes care of any necessary folddown
2235 ans = ans._fix(context)
2236 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002237
2238 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002239 """Return True if self and other have the same exponent; otherwise
2240 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002241
Facundo Batista1a191df2007-10-02 17:01:24 +00002242 If either operand is a special value, the following rules are used:
2243 * return True if both operands are infinities
2244 * return True if both operands are NaNs
2245 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002246 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002247 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002248 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002249 return (self.is_nan() and other.is_nan() or
2250 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002251 return self._exp == other._exp
2252
Facundo Batista353750c2007-09-13 18:13:15 +00002253 def _rescale(self, exp, rounding):
2254 """Rescale self so that the exponent is exp, either by padding with zeros
2255 or by truncating digits, using the given rounding mode.
2256
2257 Specials are returned without change. This operation is
2258 quiet: it raises no flags, and uses no information from the
2259 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002260
2261 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002262 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002263 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002264 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002265 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002266 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002267 return Decimal((self._sign, (0,), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002268
Facundo Batista353750c2007-09-13 18:13:15 +00002269 if self._exp >= exp:
2270 # pad answer with zeros if necessary
2271 return Decimal((self._sign, self._int + (0,)*(self._exp - exp), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002272
Facundo Batista353750c2007-09-13 18:13:15 +00002273 # too many digits; round and lose data. If self.adjusted() <
2274 # exp-1, replace self by 10**(exp-1) before rounding
2275 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002276 if digits < 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002277 self = Decimal((self._sign, (1,), exp-1))
2278 digits = 0
2279 this_function = getattr(self, self._pick_rounding_function[rounding])
2280 return this_function(digits)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002281
Facundo Batista353750c2007-09-13 18:13:15 +00002282 def to_integral_exact(self, rounding=None, context=None):
2283 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002284
Facundo Batista353750c2007-09-13 18:13:15 +00002285 If no rounding mode is specified, take the rounding mode from
2286 the context. This method raises the Rounded and Inexact flags
2287 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002288
Facundo Batista353750c2007-09-13 18:13:15 +00002289 See also: to_integral_value, which does exactly the same as
2290 this method except that it doesn't raise Inexact or Rounded.
2291 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002292 if self._is_special:
2293 ans = self._check_nans(context=context)
2294 if ans:
2295 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002296 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002297 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002298 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002299 if not self:
2300 return Decimal((self._sign, (0,), 0))
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002301 if context is None:
2302 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002303 if rounding is None:
2304 rounding = context.rounding
2305 context._raise_error(Rounded)
2306 ans = self._rescale(0, rounding)
2307 if ans != self:
2308 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002309 return ans
2310
Facundo Batista353750c2007-09-13 18:13:15 +00002311 def to_integral_value(self, rounding=None, context=None):
2312 """Rounds to the nearest integer, without raising inexact, rounded."""
2313 if context is None:
2314 context = getcontext()
2315 if rounding is None:
2316 rounding = context.rounding
2317 if self._is_special:
2318 ans = self._check_nans(context=context)
2319 if ans:
2320 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002321 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002322 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002323 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002324 else:
2325 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002326
Facundo Batista353750c2007-09-13 18:13:15 +00002327 # the method name changed, but we provide also the old one, for compatibility
2328 to_integral = to_integral_value
2329
2330 def sqrt(self, context=None):
2331 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002332 if self._is_special:
2333 ans = self._check_nans(context=context)
2334 if ans:
2335 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002336
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002337 if self._isinfinity() and self._sign == 0:
2338 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002339
2340 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002341 # exponent = self._exp // 2. sqrt(-0) = -0
2342 ans = Decimal((self._sign, (0,), self._exp // 2))
2343 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002344
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002345 if context is None:
2346 context = getcontext()
2347
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002348 if self._sign == 1:
2349 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2350
Facundo Batista353750c2007-09-13 18:13:15 +00002351 # At this point self represents a positive number. Let p be
2352 # the desired precision and express self in the form c*100**e
2353 # with c a positive real number and e an integer, c and e
2354 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2355 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2356 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2357 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2358 # the closest integer to sqrt(c) with the even integer chosen
2359 # in the case of a tie.
2360 #
2361 # To ensure correct rounding in all cases, we use the
2362 # following trick: we compute the square root to an extra
2363 # place (precision p+1 instead of precision p), rounding down.
2364 # Then, if the result is inexact and its last digit is 0 or 5,
2365 # we increase the last digit to 1 or 6 respectively; if it's
2366 # exact we leave the last digit alone. Now the final round to
2367 # p places (or fewer in the case of underflow) will round
2368 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002369
Facundo Batista353750c2007-09-13 18:13:15 +00002370 # use an extra digit of precision
2371 prec = context.prec+1
2372
2373 # write argument in the form c*100**e where e = self._exp//2
2374 # is the 'ideal' exponent, to be used if the square root is
2375 # exactly representable. l is the number of 'digits' of c in
2376 # base 100, so that 100**(l-1) <= c < 100**l.
2377 op = _WorkRep(self)
2378 e = op.exp >> 1
2379 if op.exp & 1:
2380 c = op.int * 10
2381 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002382 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002383 c = op.int
2384 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002385
Facundo Batista353750c2007-09-13 18:13:15 +00002386 # rescale so that c has exactly prec base 100 'digits'
2387 shift = prec-l
2388 if shift >= 0:
2389 c *= 100**shift
2390 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002391 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002392 c, remainder = divmod(c, 100**-shift)
2393 exact = not remainder
2394 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002395
Facundo Batista353750c2007-09-13 18:13:15 +00002396 # find n = floor(sqrt(c)) using Newton's method
2397 n = 10**prec
2398 while True:
2399 q = c//n
2400 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002401 break
Facundo Batista353750c2007-09-13 18:13:15 +00002402 else:
2403 n = n + q >> 1
2404 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002405
Facundo Batista353750c2007-09-13 18:13:15 +00002406 if exact:
2407 # result is exact; rescale to use ideal exponent e
2408 if shift >= 0:
2409 # assert n % 10**shift == 0
2410 n //= 10**shift
2411 else:
2412 n *= 10**-shift
2413 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002414 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002415 # result is not exact; fix last digit as described above
2416 if n % 5 == 0:
2417 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002418
Facundo Batista353750c2007-09-13 18:13:15 +00002419 ans = Decimal((0, map(int, str(n)), e))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002420
Facundo Batista353750c2007-09-13 18:13:15 +00002421 # round, and fit to current context
2422 context = context._shallow_copy()
2423 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002424 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002425 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002426
Facundo Batista353750c2007-09-13 18:13:15 +00002427 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002428
2429 def max(self, other, context=None):
2430 """Returns the larger value.
2431
Facundo Batista353750c2007-09-13 18:13:15 +00002432 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002433 NaN (and signals if one is sNaN). Also rounds.
2434 """
Facundo Batista353750c2007-09-13 18:13:15 +00002435 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002436
Facundo Batista6c398da2007-09-17 17:30:13 +00002437 if context is None:
2438 context = getcontext()
2439
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002440 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002441 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002442 # number is always returned
2443 sn = self._isnan()
2444 on = other._isnan()
2445 if sn or on:
2446 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002447 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002448 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002449 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002450 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002451
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002452 c = self.__cmp__(other)
2453 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002454 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002455 # then an ordering is applied:
2456 #
Facundo Batista59c58842007-04-10 12:58:45 +00002457 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002458 # positive sign and min returns the operand with the negative sign
2459 #
Facundo Batista59c58842007-04-10 12:58:45 +00002460 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002461 # the result. This is exactly the ordering used in compare_total.
2462 c = self.compare_total(other)
2463
2464 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002465 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002466 else:
2467 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002468
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002469 if context._rounding_decision == ALWAYS_ROUND:
2470 return ans._fix(context)
2471 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002472
2473 def min(self, other, context=None):
2474 """Returns the smaller value.
2475
Facundo Batista59c58842007-04-10 12:58:45 +00002476 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002477 NaN (and signals if one is sNaN). Also rounds.
2478 """
Facundo Batista353750c2007-09-13 18:13:15 +00002479 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002480
Facundo Batista6c398da2007-09-17 17:30:13 +00002481 if context is None:
2482 context = getcontext()
2483
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002484 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002485 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002486 # number is always returned
2487 sn = self._isnan()
2488 on = other._isnan()
2489 if sn or on:
2490 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002491 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002492 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002493 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002494 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002495
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002496 c = self.__cmp__(other)
2497 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002498 c = self.compare_total(other)
2499
2500 if c == -1:
2501 ans = self
2502 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002503 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002504
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002505 if context._rounding_decision == ALWAYS_ROUND:
2506 return ans._fix(context)
2507 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002508
2509 def _isinteger(self):
2510 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002511 if self._is_special:
2512 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002513 if self._exp >= 0:
2514 return True
2515 rest = self._int[self._exp:]
2516 return rest == (0,)*len(rest)
2517
2518 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002519 """Returns True if self is even. Assumes self is an integer."""
2520 if not self or self._exp > 0:
2521 return True
Raymond Hettinger61992ef2004-08-06 23:42:16 +00002522 return self._int[-1+self._exp] & 1 == 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002523
2524 def adjusted(self):
2525 """Return the adjusted exponent of self"""
2526 try:
2527 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002528 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002529 except TypeError:
2530 return 0
2531
Facundo Batista353750c2007-09-13 18:13:15 +00002532 def canonical(self, context=None):
2533 """Returns the same Decimal object.
2534
2535 As we do not have different encodings for the same number, the
2536 received object already is in its canonical form.
2537 """
2538 return self
2539
2540 def compare_signal(self, other, context=None):
2541 """Compares self to the other operand numerically.
2542
2543 It's pretty much like compare(), but all NaNs signal, with signaling
2544 NaNs taking precedence over quiet NaNs.
2545 """
2546 if context is None:
2547 context = getcontext()
2548
2549 self_is_nan = self._isnan()
2550 other_is_nan = other._isnan()
2551 if self_is_nan == 2:
2552 return context._raise_error(InvalidOperation, 'sNaN',
2553 1, self)
2554 if other_is_nan == 2:
2555 return context._raise_error(InvalidOperation, 'sNaN',
2556 1, other)
2557 if self_is_nan:
2558 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2559 1, self)
2560 if other_is_nan:
2561 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2562 1, other)
2563 return self.compare(other, context=context)
2564
2565 def compare_total(self, other):
2566 """Compares self to other using the abstract representations.
2567
2568 This is not like the standard compare, which use their numerical
2569 value. Note that a total ordering is defined for all possible abstract
2570 representations.
2571 """
2572 # if one is negative and the other is positive, it's easy
2573 if self._sign and not other._sign:
2574 return Dec_n1
2575 if not self._sign and other._sign:
2576 return Dec_p1
2577 sign = self._sign
2578
2579 # let's handle both NaN types
2580 self_nan = self._isnan()
2581 other_nan = other._isnan()
2582 if self_nan or other_nan:
2583 if self_nan == other_nan:
2584 if self._int < other._int:
2585 if sign:
2586 return Dec_p1
2587 else:
2588 return Dec_n1
2589 if self._int > other._int:
2590 if sign:
2591 return Dec_n1
2592 else:
2593 return Dec_p1
2594 return Dec_0
2595
2596 if sign:
2597 if self_nan == 1:
2598 return Dec_n1
2599 if other_nan == 1:
2600 return Dec_p1
2601 if self_nan == 2:
2602 return Dec_n1
2603 if other_nan == 2:
2604 return Dec_p1
2605 else:
2606 if self_nan == 1:
2607 return Dec_p1
2608 if other_nan == 1:
2609 return Dec_n1
2610 if self_nan == 2:
2611 return Dec_p1
2612 if other_nan == 2:
2613 return Dec_n1
2614
2615 if self < other:
2616 return Dec_n1
2617 if self > other:
2618 return Dec_p1
2619
2620 if self._exp < other._exp:
2621 if sign:
2622 return Dec_p1
2623 else:
2624 return Dec_n1
2625 if self._exp > other._exp:
2626 if sign:
2627 return Dec_n1
2628 else:
2629 return Dec_p1
2630 return Dec_0
2631
2632
2633 def compare_total_mag(self, other):
2634 """Compares self to other using abstract repr., ignoring sign.
2635
2636 Like compare_total, but with operand's sign ignored and assumed to be 0.
2637 """
2638 s = self.copy_abs()
2639 o = other.copy_abs()
2640 return s.compare_total(o)
2641
2642 def copy_abs(self):
2643 """Returns a copy with the sign set to 0. """
2644 return Decimal((0, self._int, self._exp))
2645
2646 def copy_negate(self):
2647 """Returns a copy with the sign inverted."""
2648 if self._sign:
2649 return Decimal((0, self._int, self._exp))
2650 else:
2651 return Decimal((1, self._int, self._exp))
2652
2653 def copy_sign(self, other):
2654 """Returns self with the sign of other."""
2655 return Decimal((other._sign, self._int, self._exp))
2656
2657 def exp(self, context=None):
2658 """Returns e ** self."""
2659
2660 if context is None:
2661 context = getcontext()
2662
2663 # exp(NaN) = NaN
2664 ans = self._check_nans(context=context)
2665 if ans:
2666 return ans
2667
2668 # exp(-Infinity) = 0
2669 if self._isinfinity() == -1:
2670 return Dec_0
2671
2672 # exp(0) = 1
2673 if not self:
2674 return Dec_p1
2675
2676 # exp(Infinity) = Infinity
2677 if self._isinfinity() == 1:
2678 return Decimal(self)
2679
2680 # the result is now guaranteed to be inexact (the true
2681 # mathematical result is transcendental). There's no need to
2682 # raise Rounded and Inexact here---they'll always be raised as
2683 # a result of the call to _fix.
2684 p = context.prec
2685 adj = self.adjusted()
2686
2687 # we only need to do any computation for quite a small range
2688 # of adjusted exponents---for example, -29 <= adj <= 10 for
2689 # the default context. For smaller exponent the result is
2690 # indistinguishable from 1 at the given precision, while for
2691 # larger exponent the result either overflows or underflows.
2692 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2693 # overflow
2694 ans = Decimal((0, (1,), context.Emax+1))
2695 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2696 # underflow to 0
2697 ans = Decimal((0, (1,), context.Etiny()-1))
2698 elif self._sign == 0 and adj < -p:
2699 # p+1 digits; final round will raise correct flags
2700 ans = Decimal((0, (1,) + (0,)*(p-1) + (1,), -p))
2701 elif self._sign == 1 and adj < -p-1:
2702 # p+1 digits; final round will raise correct flags
2703 ans = Decimal((0, (9,)*(p+1), -p-1))
2704 # general case
2705 else:
2706 op = _WorkRep(self)
2707 c, e = op.int, op.exp
2708 if op.sign == 1:
2709 c = -c
2710
2711 # compute correctly rounded result: increase precision by
2712 # 3 digits at a time until we get an unambiguously
2713 # roundable result
2714 extra = 3
2715 while True:
2716 coeff, exp = _dexp(c, e, p+extra)
2717 if coeff % (5*10**(len(str(coeff))-p-1)):
2718 break
2719 extra += 3
2720
2721 ans = Decimal((0, map(int, str(coeff)), exp))
2722
2723 # at this stage, ans should round correctly with *any*
2724 # rounding mode, not just with ROUND_HALF_EVEN
2725 context = context._shallow_copy()
2726 rounding = context._set_rounding(ROUND_HALF_EVEN)
2727 ans = ans._fix(context)
2728 context.rounding = rounding
2729
2730 return ans
2731
2732 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002733 """Return True if self is canonical; otherwise return False.
2734
2735 Currently, the encoding of a Decimal instance is always
2736 canonical, so this method returns True for any Decimal.
2737 """
2738 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002739
2740 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002741 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002742
Facundo Batista1a191df2007-10-02 17:01:24 +00002743 A Decimal instance is considered finite if it is neither
2744 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002745 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002746 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002747
2748 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002749 """Return True if self is infinite; otherwise return False."""
2750 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002751
2752 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002753 """Return True if self is a qNaN or sNaN; otherwise return False."""
2754 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002755
2756 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002757 """Return True if self is a normal number; otherwise return False."""
2758 if self._is_special or not self:
2759 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002760 if context is None:
2761 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002762 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002763
2764 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002765 """Return True if self is a quiet NaN; otherwise return False."""
2766 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002767
2768 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002769 """Return True if self is negative; otherwise return False."""
2770 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002771
2772 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002773 """Return True if self is a signaling NaN; otherwise return False."""
2774 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002775
2776 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002777 """Return True if self is subnormal; otherwise return False."""
2778 if self._is_special or not self:
2779 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002780 if context is None:
2781 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002782 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002783
2784 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002785 """Return True if self is a zero; otherwise return False."""
2786 return not self._is_special and self._int[0] == 0
Facundo Batista353750c2007-09-13 18:13:15 +00002787
2788 def _ln_exp_bound(self):
2789 """Compute a lower bound for the adjusted exponent of self.ln().
2790 In other words, compute r such that self.ln() >= 10**r. Assumes
2791 that self is finite and positive and that self != 1.
2792 """
2793
2794 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2795 adj = self._exp + len(self._int) - 1
2796 if adj >= 1:
2797 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2798 return len(str(adj*23//10)) - 1
2799 if adj <= -2:
2800 # argument <= 0.1
2801 return len(str((-1-adj)*23//10)) - 1
2802 op = _WorkRep(self)
2803 c, e = op.int, op.exp
2804 if adj == 0:
2805 # 1 < self < 10
2806 num = str(c-10**-e)
2807 den = str(c)
2808 return len(num) - len(den) - (num < den)
2809 # adj == -1, 0.1 <= self < 1
2810 return e + len(str(10**-e - c)) - 1
2811
2812
2813 def ln(self, context=None):
2814 """Returns the natural (base e) logarithm of self."""
2815
2816 if context is None:
2817 context = getcontext()
2818
2819 # ln(NaN) = NaN
2820 ans = self._check_nans(context=context)
2821 if ans:
2822 return ans
2823
2824 # ln(0.0) == -Infinity
2825 if not self:
2826 return negInf
2827
2828 # ln(Infinity) = Infinity
2829 if self._isinfinity() == 1:
2830 return Inf
2831
2832 # ln(1.0) == 0.0
2833 if self == Dec_p1:
2834 return Dec_0
2835
2836 # ln(negative) raises InvalidOperation
2837 if self._sign == 1:
2838 return context._raise_error(InvalidOperation,
2839 'ln of a negative value')
2840
2841 # result is irrational, so necessarily inexact
2842 op = _WorkRep(self)
2843 c, e = op.int, op.exp
2844 p = context.prec
2845
2846 # correctly rounded result: repeatedly increase precision by 3
2847 # until we get an unambiguously roundable result
2848 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2849 while True:
2850 coeff = _dlog(c, e, places)
2851 # assert len(str(abs(coeff)))-p >= 1
2852 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2853 break
2854 places += 3
2855 ans = Decimal((int(coeff<0), map(int, str(abs(coeff))), -places))
2856
2857 context = context._shallow_copy()
2858 rounding = context._set_rounding(ROUND_HALF_EVEN)
2859 ans = ans._fix(context)
2860 context.rounding = rounding
2861 return ans
2862
2863 def _log10_exp_bound(self):
2864 """Compute a lower bound for the adjusted exponent of self.log10().
2865 In other words, find r such that self.log10() >= 10**r.
2866 Assumes that self is finite and positive and that self != 1.
2867 """
2868
2869 # For x >= 10 or x < 0.1 we only need a bound on the integer
2870 # part of log10(self), and this comes directly from the
2871 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2872 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2873 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2874
2875 adj = self._exp + len(self._int) - 1
2876 if adj >= 1:
2877 # self >= 10
2878 return len(str(adj))-1
2879 if adj <= -2:
2880 # self < 0.1
2881 return len(str(-1-adj))-1
2882 op = _WorkRep(self)
2883 c, e = op.int, op.exp
2884 if adj == 0:
2885 # 1 < self < 10
2886 num = str(c-10**-e)
2887 den = str(231*c)
2888 return len(num) - len(den) - (num < den) + 2
2889 # adj == -1, 0.1 <= self < 1
2890 num = str(10**-e-c)
2891 return len(num) + e - (num < "231") - 1
2892
2893 def log10(self, context=None):
2894 """Returns the base 10 logarithm of self."""
2895
2896 if context is None:
2897 context = getcontext()
2898
2899 # log10(NaN) = NaN
2900 ans = self._check_nans(context=context)
2901 if ans:
2902 return ans
2903
2904 # log10(0.0) == -Infinity
2905 if not self:
2906 return negInf
2907
2908 # log10(Infinity) = Infinity
2909 if self._isinfinity() == 1:
2910 return Inf
2911
2912 # log10(negative or -Infinity) raises InvalidOperation
2913 if self._sign == 1:
2914 return context._raise_error(InvalidOperation,
2915 'log10 of a negative value')
2916
2917 # log10(10**n) = n
2918 if self._int[0] == 1 and self._int[1:] == (0,)*(len(self._int) - 1):
2919 # answer may need rounding
2920 ans = Decimal(self._exp + len(self._int) - 1)
2921 else:
2922 # result is irrational, so necessarily inexact
2923 op = _WorkRep(self)
2924 c, e = op.int, op.exp
2925 p = context.prec
2926
2927 # correctly rounded result: repeatedly increase precision
2928 # until result is unambiguously roundable
2929 places = p-self._log10_exp_bound()+2
2930 while True:
2931 coeff = _dlog10(c, e, places)
2932 # assert len(str(abs(coeff)))-p >= 1
2933 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2934 break
2935 places += 3
2936 ans = Decimal((int(coeff<0), map(int, str(abs(coeff))), -places))
2937
2938 context = context._shallow_copy()
2939 rounding = context._set_rounding(ROUND_HALF_EVEN)
2940 ans = ans._fix(context)
2941 context.rounding = rounding
2942 return ans
2943
2944 def logb(self, context=None):
2945 """ Returns the exponent of the magnitude of self's MSD.
2946
2947 The result is the integer which is the exponent of the magnitude
2948 of the most significant digit of self (as though it were truncated
2949 to a single digit while maintaining the value of that digit and
2950 without limiting the resulting exponent).
2951 """
2952 # logb(NaN) = NaN
2953 ans = self._check_nans(context=context)
2954 if ans:
2955 return ans
2956
2957 if context is None:
2958 context = getcontext()
2959
2960 # logb(+/-Inf) = +Inf
2961 if self._isinfinity():
2962 return Inf
2963
2964 # logb(0) = -Inf, DivisionByZero
2965 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00002966 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00002967
2968 # otherwise, simply return the adjusted exponent of self, as a
2969 # Decimal. Note that no attempt is made to fit the result
2970 # into the current context.
2971 return Decimal(self.adjusted())
2972
2973 def _islogical(self):
2974 """Return True if self is a logical operand.
2975
2976 For being logical, it must be a finite numbers with a sign of 0,
2977 an exponent of 0, and a coefficient whose digits must all be
2978 either 0 or 1.
2979 """
2980 if self._sign != 0 or self._exp != 0:
2981 return False
2982 for dig in self._int:
2983 if dig not in (0, 1):
2984 return False
2985 return True
2986
2987 def _fill_logical(self, context, opa, opb):
2988 dif = context.prec - len(opa)
2989 if dif > 0:
2990 opa = (0,)*dif + opa
2991 elif dif < 0:
2992 opa = opa[-context.prec:]
2993 dif = context.prec - len(opb)
2994 if dif > 0:
2995 opb = (0,)*dif + opb
2996 elif dif < 0:
2997 opb = opb[-context.prec:]
2998 return opa, opb
2999
3000 def logical_and(self, other, context=None):
3001 """Applies an 'and' operation between self and other's digits."""
3002 if context is None:
3003 context = getcontext()
3004 if not self._islogical() or not other._islogical():
3005 return context._raise_error(InvalidOperation)
3006
3007 # fill to context.prec
3008 (opa, opb) = self._fill_logical(context, self._int, other._int)
3009
3010 # make the operation, and clean starting zeroes
3011 result = [a&b for a,b in zip(opa,opb)]
3012 for i,d in enumerate(result):
3013 if d == 1:
3014 break
3015 result = tuple(result[i:])
3016
3017 # if empty, we must have at least a zero
3018 if not result:
3019 result = (0,)
3020 return Decimal((0, result, 0))
3021
3022 def logical_invert(self, context=None):
3023 """Invert all its digits."""
3024 if context is None:
3025 context = getcontext()
3026 return self.logical_xor(Decimal((0,(1,)*context.prec,0)), context)
3027
3028 def logical_or(self, other, context=None):
3029 """Applies an 'or' operation between self and other's digits."""
3030 if context is None:
3031 context = getcontext()
3032 if not self._islogical() or not other._islogical():
3033 return context._raise_error(InvalidOperation)
3034
3035 # fill to context.prec
3036 (opa, opb) = self._fill_logical(context, self._int, other._int)
3037
3038 # make the operation, and clean starting zeroes
3039 result = [a|b for a,b in zip(opa,opb)]
3040 for i,d in enumerate(result):
3041 if d == 1:
3042 break
3043 result = tuple(result[i:])
3044
3045 # if empty, we must have at least a zero
3046 if not result:
3047 result = (0,)
3048 return Decimal((0, result, 0))
3049
3050 def logical_xor(self, other, context=None):
3051 """Applies an 'xor' operation between self and other's digits."""
3052 if context is None:
3053 context = getcontext()
3054 if not self._islogical() or not other._islogical():
3055 return context._raise_error(InvalidOperation)
3056
3057 # fill to context.prec
3058 (opa, opb) = self._fill_logical(context, self._int, other._int)
3059
3060 # make the operation, and clean starting zeroes
3061 result = [a^b for a,b in zip(opa,opb)]
3062 for i,d in enumerate(result):
3063 if d == 1:
3064 break
3065 result = tuple(result[i:])
3066
3067 # if empty, we must have at least a zero
3068 if not result:
3069 result = (0,)
3070 return Decimal((0, result, 0))
3071
3072 def max_mag(self, other, context=None):
3073 """Compares the values numerically with their sign ignored."""
3074 other = _convert_other(other, raiseit=True)
3075
Facundo Batista6c398da2007-09-17 17:30:13 +00003076 if context is None:
3077 context = getcontext()
3078
Facundo Batista353750c2007-09-13 18:13:15 +00003079 if self._is_special or other._is_special:
3080 # If one operand is a quiet NaN and the other is number, then the
3081 # number is always returned
3082 sn = self._isnan()
3083 on = other._isnan()
3084 if sn or on:
3085 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003086 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003087 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003088 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003089 return self._check_nans(other, context)
3090
3091 c = self.copy_abs().__cmp__(other.copy_abs())
3092 if c == 0:
3093 c = self.compare_total(other)
3094
3095 if c == -1:
3096 ans = other
3097 else:
3098 ans = self
3099
Facundo Batista353750c2007-09-13 18:13:15 +00003100 if context._rounding_decision == ALWAYS_ROUND:
3101 return ans._fix(context)
3102 return ans
3103
3104 def min_mag(self, other, context=None):
3105 """Compares the values numerically with their sign ignored."""
3106 other = _convert_other(other, raiseit=True)
3107
Facundo Batista6c398da2007-09-17 17:30:13 +00003108 if context is None:
3109 context = getcontext()
3110
Facundo Batista353750c2007-09-13 18:13:15 +00003111 if self._is_special or other._is_special:
3112 # If one operand is a quiet NaN and the other is number, then the
3113 # number is always returned
3114 sn = self._isnan()
3115 on = other._isnan()
3116 if sn or on:
3117 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003118 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003119 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003120 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003121 return self._check_nans(other, context)
3122
3123 c = self.copy_abs().__cmp__(other.copy_abs())
3124 if c == 0:
3125 c = self.compare_total(other)
3126
3127 if c == -1:
3128 ans = self
3129 else:
3130 ans = other
3131
Facundo Batista353750c2007-09-13 18:13:15 +00003132 if context._rounding_decision == ALWAYS_ROUND:
3133 return ans._fix(context)
3134 return ans
3135
3136 def next_minus(self, context=None):
3137 """Returns the largest representable number smaller than itself."""
3138 if context is None:
3139 context = getcontext()
3140
3141 ans = self._check_nans(context=context)
3142 if ans:
3143 return ans
3144
3145 if self._isinfinity() == -1:
3146 return negInf
3147 if self._isinfinity() == 1:
3148 return Decimal((0, (9,)*context.prec, context.Etop()))
3149
3150 context = context.copy()
3151 context._set_rounding(ROUND_FLOOR)
3152 context._ignore_all_flags()
3153 new_self = self._fix(context)
3154 if new_self != self:
3155 return new_self
3156 return self.__sub__(Decimal((0, (1,), context.Etiny()-1)), context)
3157
3158 def next_plus(self, context=None):
3159 """Returns the smallest representable number larger than itself."""
3160 if context is None:
3161 context = getcontext()
3162
3163 ans = self._check_nans(context=context)
3164 if ans:
3165 return ans
3166
3167 if self._isinfinity() == 1:
3168 return Inf
3169 if self._isinfinity() == -1:
3170 return Decimal((1, (9,)*context.prec, context.Etop()))
3171
3172 context = context.copy()
3173 context._set_rounding(ROUND_CEILING)
3174 context._ignore_all_flags()
3175 new_self = self._fix(context)
3176 if new_self != self:
3177 return new_self
3178 return self.__add__(Decimal((0, (1,), context.Etiny()-1)), context)
3179
3180 def next_toward(self, other, context=None):
3181 """Returns the number closest to self, in the direction towards other.
3182
3183 The result is the closest representable number to self
3184 (excluding self) that is in the direction towards other,
3185 unless both have the same value. If the two operands are
3186 numerically equal, then the result is a copy of self with the
3187 sign set to be the same as the sign of other.
3188 """
3189 other = _convert_other(other, raiseit=True)
3190
3191 if context is None:
3192 context = getcontext()
3193
3194 ans = self._check_nans(other, context)
3195 if ans:
3196 return ans
3197
3198 comparison = self.__cmp__(other)
3199 if comparison == 0:
3200 return Decimal((other._sign, self._int, self._exp))
3201
3202 if comparison == -1:
3203 ans = self.next_plus(context)
3204 else: # comparison == 1
3205 ans = self.next_minus(context)
3206
3207 # decide which flags to raise using value of ans
3208 if ans._isinfinity():
3209 context._raise_error(Overflow,
3210 'Infinite result from next_toward',
3211 ans._sign)
3212 context._raise_error(Rounded)
3213 context._raise_error(Inexact)
3214 elif ans.adjusted() < context.Emin:
3215 context._raise_error(Underflow)
3216 context._raise_error(Subnormal)
3217 context._raise_error(Rounded)
3218 context._raise_error(Inexact)
3219 # if precision == 1 then we don't raise Clamped for a
3220 # result 0E-Etiny.
3221 if not ans:
3222 context._raise_error(Clamped)
3223
3224 return ans
3225
3226 def number_class(self, context=None):
3227 """Returns an indication of the class of self.
3228
3229 The class is one of the following strings:
3230 -sNaN
3231 -NaN
3232 -Infinity
3233 -Normal
3234 -Subnormal
3235 -Zero
3236 +Zero
3237 +Subnormal
3238 +Normal
3239 +Infinity
3240 """
3241 if self.is_snan():
3242 return "sNaN"
3243 if self.is_qnan():
3244 return "NaN"
3245 inf = self._isinfinity()
3246 if inf == 1:
3247 return "+Infinity"
3248 if inf == -1:
3249 return "-Infinity"
3250 if self.is_zero():
3251 if self._sign:
3252 return "-Zero"
3253 else:
3254 return "+Zero"
3255 if context is None:
3256 context = getcontext()
3257 if self.is_subnormal(context=context):
3258 if self._sign:
3259 return "-Subnormal"
3260 else:
3261 return "+Subnormal"
3262 # just a normal, regular, boring number, :)
3263 if self._sign:
3264 return "-Normal"
3265 else:
3266 return "+Normal"
3267
3268 def radix(self):
3269 """Just returns 10, as this is Decimal, :)"""
3270 return Decimal(10)
3271
3272 def rotate(self, other, context=None):
3273 """Returns a rotated copy of self, value-of-other times."""
3274 if context is None:
3275 context = getcontext()
3276
3277 ans = self._check_nans(other, context)
3278 if ans:
3279 return ans
3280
3281 if other._exp != 0:
3282 return context._raise_error(InvalidOperation)
3283 if not (-context.prec <= int(other) <= context.prec):
3284 return context._raise_error(InvalidOperation)
3285
3286 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003287 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003288
3289 # get values, pad if necessary
3290 torot = int(other)
3291 rotdig = self._int
3292 topad = context.prec - len(rotdig)
3293 if topad:
3294 rotdig = ((0,)*topad) + rotdig
3295
3296 # let's rotate!
3297 rotated = rotdig[torot:] + rotdig[:torot]
3298
3299 # clean starting zeroes
3300 for i,d in enumerate(rotated):
3301 if d != 0:
3302 break
3303 rotated = rotated[i:]
3304
3305 return Decimal((self._sign, rotated, self._exp))
3306
3307
3308 def scaleb (self, other, context=None):
3309 """Returns self operand after adding the second value to its exp."""
3310 if context is None:
3311 context = getcontext()
3312
3313 ans = self._check_nans(other, context)
3314 if ans:
3315 return ans
3316
3317 if other._exp != 0:
3318 return context._raise_error(InvalidOperation)
3319 liminf = -2 * (context.Emax + context.prec)
3320 limsup = 2 * (context.Emax + context.prec)
3321 if not (liminf <= int(other) <= limsup):
3322 return context._raise_error(InvalidOperation)
3323
3324 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003325 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003326
3327 d = Decimal((self._sign, self._int, self._exp + int(other)))
3328 d = d._fix(context)
3329 return d
3330
3331 def shift(self, other, context=None):
3332 """Returns a shifted copy of self, value-of-other times."""
3333 if context is None:
3334 context = getcontext()
3335
3336 ans = self._check_nans(other, context)
3337 if ans:
3338 return ans
3339
3340 if other._exp != 0:
3341 return context._raise_error(InvalidOperation)
3342 if not (-context.prec <= int(other) <= context.prec):
3343 return context._raise_error(InvalidOperation)
3344
3345 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003346 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003347
3348 # get values, pad if necessary
3349 torot = int(other)
3350 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003351 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003352 rotdig = self._int
3353 topad = context.prec - len(rotdig)
3354 if topad:
3355 rotdig = ((0,)*topad) + rotdig
3356
3357 # let's shift!
3358 if torot < 0:
3359 rotated = rotdig[:torot]
3360 else:
3361 rotated = (rotdig + ((0,) * torot))
3362 rotated = rotated[-context.prec:]
3363
3364 # clean starting zeroes
3365 if rotated:
3366 for i,d in enumerate(rotated):
3367 if d != 0:
3368 break
3369 rotated = rotated[i:]
3370 else:
3371 rotated = (0,)
3372
3373 return Decimal((self._sign, rotated, self._exp))
3374
3375
Facundo Batista59c58842007-04-10 12:58:45 +00003376 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003377 def __reduce__(self):
3378 return (self.__class__, (str(self),))
3379
3380 def __copy__(self):
3381 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003382 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003383 return self.__class__(str(self))
3384
3385 def __deepcopy__(self, memo):
3386 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003387 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003388 return self.__class__(str(self))
3389
Facundo Batista59c58842007-04-10 12:58:45 +00003390##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003391
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003392
3393# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003394rounding_functions = [name for name in Decimal.__dict__.keys()
3395 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003396for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003397 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003398 globalname = name[1:].upper()
3399 val = globals()[globalname]
3400 Decimal._pick_rounding_function[val] = name
3401
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003402del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003403
Nick Coghlanced12182006-09-02 03:54:17 +00003404class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003405 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003406
Nick Coghlanced12182006-09-02 03:54:17 +00003407 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003408 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003409 """
3410 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003411 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003412 def __enter__(self):
3413 self.saved_context = getcontext()
3414 setcontext(self.new_context)
3415 return self.new_context
3416 def __exit__(self, t, v, tb):
3417 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003418
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003419class Context(object):
3420 """Contains the context for a Decimal instance.
3421
3422 Contains:
3423 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003424 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003425 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003426 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003427 raised when it is caused. Otherwise, a value is
3428 substituted in.
3429 flags - When an exception is caused, flags[exception] is incremented.
3430 (Whether or not the trap_enabler is set)
3431 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003432 Emin - Minimum exponent
3433 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003434 capitals - If 1, 1*10^1 is printed as 1E+1.
3435 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003436 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003437 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003438
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003439 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003440 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003441 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003442 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003443 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003444 _ignored_flags=None):
3445 if flags is None:
3446 flags = []
3447 if _ignored_flags is None:
3448 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003449 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003450 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003451 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003452 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003453 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003454 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003455 for name, val in locals().items():
3456 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003457 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003458 else:
3459 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003460 del self.self
3461
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003462 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003463 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003464 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003465 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3466 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3467 % vars(self))
3468 names = [f.__name__ for f, v in self.flags.items() if v]
3469 s.append('flags=[' + ', '.join(names) + ']')
3470 names = [t.__name__ for t, v in self.traps.items() if v]
3471 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003472 return ', '.join(s) + ')'
3473
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003474 def clear_flags(self):
3475 """Reset all flags to zero"""
3476 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003477 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003478
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003479 def _shallow_copy(self):
3480 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003481 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003482 self._rounding_decision, self.Emin, self.Emax,
3483 self.capitals, self._clamp, self._ignored_flags)
3484 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003485
3486 def copy(self):
3487 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003488 nc = Context(self.prec, self.rounding, self.traps.copy(),
3489 self.flags.copy(), self._rounding_decision, self.Emin,
3490 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003491 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003492 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003493
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003494 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003495 """Handles an error
3496
3497 If the flag is in _ignored_flags, returns the default response.
3498 Otherwise, it increments the flag, then, if the corresponding
3499 trap_enabler is set, it reaises the exception. Otherwise, it returns
3500 the default value after incrementing the flag.
3501 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003502 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003503 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003504 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003505 return error().handle(self, *args)
3506
3507 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003508 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003509 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003510 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003511
3512 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003513 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003514 raise error, explanation
3515
3516 def _ignore_all_flags(self):
3517 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003518 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003519
3520 def _ignore_flags(self, *flags):
3521 """Ignore the flags, if they are raised"""
3522 # Do not mutate-- This way, copies of a context leave the original
3523 # alone.
3524 self._ignored_flags = (self._ignored_flags + list(flags))
3525 return list(flags)
3526
3527 def _regard_flags(self, *flags):
3528 """Stop ignoring the flags, if they are raised"""
3529 if flags and isinstance(flags[0], (tuple,list)):
3530 flags = flags[0]
3531 for flag in flags:
3532 self._ignored_flags.remove(flag)
3533
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003534 def __hash__(self):
3535 """A Context cannot be hashed."""
3536 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003537 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003538
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003539 def Etiny(self):
3540 """Returns Etiny (= Emin - prec + 1)"""
3541 return int(self.Emin - self.prec + 1)
3542
3543 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003544 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003545 return int(self.Emax - self.prec + 1)
3546
3547 def _set_rounding_decision(self, type):
3548 """Sets the rounding decision.
3549
3550 Sets the rounding decision, and returns the current (previous)
3551 rounding decision. Often used like:
3552
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003553 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003554 # That so you don't change the calling context
3555 # if an error occurs in the middle (say DivisionImpossible is raised).
3556
3557 rounding = context._set_rounding_decision(NEVER_ROUND)
3558 instance = instance / Decimal(2)
3559 context._set_rounding_decision(rounding)
3560
3561 This will make it not round for that operation.
3562 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003563
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003564 rounding = self._rounding_decision
3565 self._rounding_decision = type
3566 return rounding
3567
3568 def _set_rounding(self, type):
3569 """Sets the rounding type.
3570
3571 Sets the rounding type, and returns the current (previous)
3572 rounding type. Often used like:
3573
3574 context = context.copy()
3575 # so you don't change the calling context
3576 # if an error occurs in the middle.
3577 rounding = context._set_rounding(ROUND_UP)
3578 val = self.__sub__(other, context=context)
3579 context._set_rounding(rounding)
3580
3581 This will make it round up for that operation.
3582 """
3583 rounding = self.rounding
3584 self.rounding= type
3585 return rounding
3586
Raymond Hettingerfed52962004-07-14 15:41:57 +00003587 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003588 """Creates a new Decimal instance but using self as context."""
3589 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003590 if d._isnan() and len(d._int) > self.prec - self._clamp:
3591 return self._raise_error(ConversionSyntax,
3592 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003593 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003594
Facundo Batista59c58842007-04-10 12:58:45 +00003595 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003596 def abs(self, a):
3597 """Returns the absolute value of the operand.
3598
3599 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003600 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003601 the plus operation on the operand.
3602
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003603 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003604 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003605 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003606 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003607 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003608 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003609 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003610 Decimal("101.5")
3611 """
3612 return a.__abs__(context=self)
3613
3614 def add(self, a, b):
3615 """Return the sum of the two operands.
3616
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003617 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003618 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003619 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003620 Decimal("1.02E+4")
3621 """
3622 return a.__add__(b, context=self)
3623
3624 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003625 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003626
Facundo Batista353750c2007-09-13 18:13:15 +00003627 def canonical(self, a):
3628 """Returns the same Decimal object.
3629
3630 As we do not have different encodings for the same number, the
3631 received object already is in its canonical form.
3632
3633 >>> ExtendedContext.canonical(Decimal('2.50'))
3634 Decimal("2.50")
3635 """
3636 return a.canonical(context=self)
3637
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003638 def compare(self, a, b):
3639 """Compares values numerically.
3640
3641 If the signs of the operands differ, a value representing each operand
3642 ('-1' if the operand is less than zero, '0' if the operand is zero or
3643 negative zero, or '1' if the operand is greater than zero) is used in
3644 place of that operand for the comparison instead of the actual
3645 operand.
3646
3647 The comparison is then effected by subtracting the second operand from
3648 the first and then returning a value according to the result of the
3649 subtraction: '-1' if the result is less than zero, '0' if the result is
3650 zero or negative zero, or '1' if the result is greater than zero.
3651
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003652 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003653 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003654 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003655 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003656 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003657 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003658 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003659 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003660 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003661 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003662 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003663 Decimal("-1")
3664 """
3665 return a.compare(b, context=self)
3666
Facundo Batista353750c2007-09-13 18:13:15 +00003667 def compare_signal(self, a, b):
3668 """Compares the values of the two operands numerically.
3669
3670 It's pretty much like compare(), but all NaNs signal, with signaling
3671 NaNs taking precedence over quiet NaNs.
3672
3673 >>> c = ExtendedContext
3674 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3675 Decimal("-1")
3676 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3677 Decimal("0")
3678 >>> c.flags[InvalidOperation] = 0
3679 >>> print c.flags[InvalidOperation]
3680 0
3681 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3682 Decimal("NaN")
3683 >>> print c.flags[InvalidOperation]
3684 1
3685 >>> c.flags[InvalidOperation] = 0
3686 >>> print c.flags[InvalidOperation]
3687 0
3688 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3689 Decimal("NaN")
3690 >>> print c.flags[InvalidOperation]
3691 1
3692 """
3693 return a.compare_signal(b, context=self)
3694
3695 def compare_total(self, a, b):
3696 """Compares two operands using their abstract representation.
3697
3698 This is not like the standard compare, which use their numerical
3699 value. Note that a total ordering is defined for all possible abstract
3700 representations.
3701
3702 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3703 Decimal("-1")
3704 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3705 Decimal("-1")
3706 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3707 Decimal("-1")
3708 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3709 Decimal("0")
3710 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3711 Decimal("1")
3712 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3713 Decimal("-1")
3714 """
3715 return a.compare_total(b)
3716
3717 def compare_total_mag(self, a, b):
3718 """Compares two operands using their abstract representation ignoring sign.
3719
3720 Like compare_total, but with operand's sign ignored and assumed to be 0.
3721 """
3722 return a.compare_total_mag(b)
3723
3724 def copy_abs(self, a):
3725 """Returns a copy of the operand with the sign set to 0.
3726
3727 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3728 Decimal("2.1")
3729 >>> ExtendedContext.copy_abs(Decimal('-100'))
3730 Decimal("100")
3731 """
3732 return a.copy_abs()
3733
3734 def copy_decimal(self, a):
3735 """Returns a copy of the decimal objet.
3736
3737 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3738 Decimal("2.1")
3739 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3740 Decimal("-1.00")
3741 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003742 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003743
3744 def copy_negate(self, a):
3745 """Returns a copy of the operand with the sign inverted.
3746
3747 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3748 Decimal("-101.5")
3749 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3750 Decimal("101.5")
3751 """
3752 return a.copy_negate()
3753
3754 def copy_sign(self, a, b):
3755 """Copies the second operand's sign to the first one.
3756
3757 In detail, it returns a copy of the first operand with the sign
3758 equal to the sign of the second operand.
3759
3760 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3761 Decimal("1.50")
3762 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3763 Decimal("1.50")
3764 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3765 Decimal("-1.50")
3766 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3767 Decimal("-1.50")
3768 """
3769 return a.copy_sign(b)
3770
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003771 def divide(self, a, b):
3772 """Decimal division in a specified context.
3773
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003774 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003775 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003776 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003777 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003778 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003779 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003780 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003781 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003782 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003783 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003784 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003785 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003786 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003787 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003788 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003789 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003790 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003791 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003792 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003793 Decimal("1.20E+6")
3794 """
3795 return a.__div__(b, context=self)
3796
3797 def divide_int(self, a, b):
3798 """Divides two numbers and returns the integer part of the result.
3799
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003800 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003801 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003802 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003803 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003804 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003805 Decimal("3")
3806 """
3807 return a.__floordiv__(b, context=self)
3808
3809 def divmod(self, a, b):
3810 return a.__divmod__(b, context=self)
3811
Facundo Batista353750c2007-09-13 18:13:15 +00003812 def exp(self, a):
3813 """Returns e ** a.
3814
3815 >>> c = ExtendedContext.copy()
3816 >>> c.Emin = -999
3817 >>> c.Emax = 999
3818 >>> c.exp(Decimal('-Infinity'))
3819 Decimal("0")
3820 >>> c.exp(Decimal('-1'))
3821 Decimal("0.367879441")
3822 >>> c.exp(Decimal('0'))
3823 Decimal("1")
3824 >>> c.exp(Decimal('1'))
3825 Decimal("2.71828183")
3826 >>> c.exp(Decimal('0.693147181'))
3827 Decimal("2.00000000")
3828 >>> c.exp(Decimal('+Infinity'))
3829 Decimal("Infinity")
3830 """
3831 return a.exp(context=self)
3832
3833 def fma(self, a, b, c):
3834 """Returns a multiplied by b, plus c.
3835
3836 The first two operands are multiplied together, using multiply,
3837 the third operand is then added to the result of that
3838 multiplication, using add, all with only one final rounding.
3839
3840 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3841 Decimal("22")
3842 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3843 Decimal("-8")
3844 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3845 Decimal("1.38435736E+12")
3846 """
3847 return a.fma(b, c, context=self)
3848
3849 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003850 """Return True if the operand is canonical; otherwise return False.
3851
3852 Currently, the encoding of a Decimal instance is always
3853 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00003854
3855 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003856 True
Facundo Batista353750c2007-09-13 18:13:15 +00003857 """
Facundo Batista1a191df2007-10-02 17:01:24 +00003858 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00003859
3860 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003861 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003862
Facundo Batista1a191df2007-10-02 17:01:24 +00003863 A Decimal instance is considered finite if it is neither
3864 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00003865
3866 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003867 True
Facundo Batista353750c2007-09-13 18:13:15 +00003868 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003869 True
Facundo Batista353750c2007-09-13 18:13:15 +00003870 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003871 True
Facundo Batista353750c2007-09-13 18:13:15 +00003872 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003873 False
Facundo Batista353750c2007-09-13 18:13:15 +00003874 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003875 False
Facundo Batista353750c2007-09-13 18:13:15 +00003876 """
3877 return a.is_finite()
3878
3879 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003880 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003881
3882 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003883 False
Facundo Batista353750c2007-09-13 18:13:15 +00003884 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003885 True
Facundo Batista353750c2007-09-13 18:13:15 +00003886 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003887 False
Facundo Batista353750c2007-09-13 18:13:15 +00003888 """
3889 return a.is_infinite()
3890
3891 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003892 """Return True if the operand is a qNaN or sNaN;
3893 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003894
3895 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003896 False
Facundo Batista353750c2007-09-13 18:13:15 +00003897 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003898 True
Facundo Batista353750c2007-09-13 18:13:15 +00003899 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003900 True
Facundo Batista353750c2007-09-13 18:13:15 +00003901 """
3902 return a.is_nan()
3903
3904 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003905 """Return True if the operand is a normal number;
3906 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003907
3908 >>> c = ExtendedContext.copy()
3909 >>> c.Emin = -999
3910 >>> c.Emax = 999
3911 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003912 True
Facundo Batista353750c2007-09-13 18:13:15 +00003913 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003914 False
Facundo Batista353750c2007-09-13 18:13:15 +00003915 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003916 False
Facundo Batista353750c2007-09-13 18:13:15 +00003917 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003918 False
Facundo Batista353750c2007-09-13 18:13:15 +00003919 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003920 False
Facundo Batista353750c2007-09-13 18:13:15 +00003921 """
3922 return a.is_normal(context=self)
3923
3924 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003925 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003926
3927 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003928 False
Facundo Batista353750c2007-09-13 18:13:15 +00003929 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003930 True
Facundo Batista353750c2007-09-13 18:13:15 +00003931 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003932 False
Facundo Batista353750c2007-09-13 18:13:15 +00003933 """
3934 return a.is_qnan()
3935
3936 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003937 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003938
3939 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003940 False
Facundo Batista353750c2007-09-13 18:13:15 +00003941 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003942 True
Facundo Batista353750c2007-09-13 18:13:15 +00003943 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003944 True
Facundo Batista353750c2007-09-13 18:13:15 +00003945 """
3946 return a.is_signed()
3947
3948 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003949 """Return True if the operand is a signaling NaN;
3950 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003951
3952 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003953 False
Facundo Batista353750c2007-09-13 18:13:15 +00003954 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003955 False
Facundo Batista353750c2007-09-13 18:13:15 +00003956 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003957 True
Facundo Batista353750c2007-09-13 18:13:15 +00003958 """
3959 return a.is_snan()
3960
3961 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003962 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003963
3964 >>> c = ExtendedContext.copy()
3965 >>> c.Emin = -999
3966 >>> c.Emax = 999
3967 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003968 False
Facundo Batista353750c2007-09-13 18:13:15 +00003969 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003970 True
Facundo Batista353750c2007-09-13 18:13:15 +00003971 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003972 False
Facundo Batista353750c2007-09-13 18:13:15 +00003973 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003974 False
Facundo Batista353750c2007-09-13 18:13:15 +00003975 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003976 False
Facundo Batista353750c2007-09-13 18:13:15 +00003977 """
3978 return a.is_subnormal(context=self)
3979
3980 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003981 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003982
3983 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003984 True
Facundo Batista353750c2007-09-13 18:13:15 +00003985 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003986 False
Facundo Batista353750c2007-09-13 18:13:15 +00003987 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003988 True
Facundo Batista353750c2007-09-13 18:13:15 +00003989 """
3990 return a.is_zero()
3991
3992 def ln(self, a):
3993 """Returns the natural (base e) logarithm of the operand.
3994
3995 >>> c = ExtendedContext.copy()
3996 >>> c.Emin = -999
3997 >>> c.Emax = 999
3998 >>> c.ln(Decimal('0'))
3999 Decimal("-Infinity")
4000 >>> c.ln(Decimal('1.000'))
4001 Decimal("0")
4002 >>> c.ln(Decimal('2.71828183'))
4003 Decimal("1.00000000")
4004 >>> c.ln(Decimal('10'))
4005 Decimal("2.30258509")
4006 >>> c.ln(Decimal('+Infinity'))
4007 Decimal("Infinity")
4008 """
4009 return a.ln(context=self)
4010
4011 def log10(self, a):
4012 """Returns the base 10 logarithm of the operand.
4013
4014 >>> c = ExtendedContext.copy()
4015 >>> c.Emin = -999
4016 >>> c.Emax = 999
4017 >>> c.log10(Decimal('0'))
4018 Decimal("-Infinity")
4019 >>> c.log10(Decimal('0.001'))
4020 Decimal("-3")
4021 >>> c.log10(Decimal('1.000'))
4022 Decimal("0")
4023 >>> c.log10(Decimal('2'))
4024 Decimal("0.301029996")
4025 >>> c.log10(Decimal('10'))
4026 Decimal("1")
4027 >>> c.log10(Decimal('70'))
4028 Decimal("1.84509804")
4029 >>> c.log10(Decimal('+Infinity'))
4030 Decimal("Infinity")
4031 """
4032 return a.log10(context=self)
4033
4034 def logb(self, a):
4035 """ Returns the exponent of the magnitude of the operand's MSD.
4036
4037 The result is the integer which is the exponent of the magnitude
4038 of the most significant digit of the operand (as though the
4039 operand were truncated to a single digit while maintaining the
4040 value of that digit and without limiting the resulting exponent).
4041
4042 >>> ExtendedContext.logb(Decimal('250'))
4043 Decimal("2")
4044 >>> ExtendedContext.logb(Decimal('2.50'))
4045 Decimal("0")
4046 >>> ExtendedContext.logb(Decimal('0.03'))
4047 Decimal("-2")
4048 >>> ExtendedContext.logb(Decimal('0'))
4049 Decimal("-Infinity")
4050 """
4051 return a.logb(context=self)
4052
4053 def logical_and(self, a, b):
4054 """Applies the logical operation 'and' between each operand's digits.
4055
4056 The operands must be both logical numbers.
4057
4058 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4059 Decimal("0")
4060 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4061 Decimal("0")
4062 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4063 Decimal("0")
4064 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4065 Decimal("1")
4066 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4067 Decimal("1000")
4068 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4069 Decimal("10")
4070 """
4071 return a.logical_and(b, context=self)
4072
4073 def logical_invert(self, a):
4074 """Invert all the digits in the operand.
4075
4076 The operand must be a logical number.
4077
4078 >>> ExtendedContext.logical_invert(Decimal('0'))
4079 Decimal("111111111")
4080 >>> ExtendedContext.logical_invert(Decimal('1'))
4081 Decimal("111111110")
4082 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4083 Decimal("0")
4084 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4085 Decimal("10101010")
4086 """
4087 return a.logical_invert(context=self)
4088
4089 def logical_or(self, a, b):
4090 """Applies the logical operation 'or' between each operand's digits.
4091
4092 The operands must be both logical numbers.
4093
4094 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4095 Decimal("0")
4096 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4097 Decimal("1")
4098 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4099 Decimal("1")
4100 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4101 Decimal("1")
4102 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4103 Decimal("1110")
4104 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4105 Decimal("1110")
4106 """
4107 return a.logical_or(b, context=self)
4108
4109 def logical_xor(self, a, b):
4110 """Applies the logical operation 'xor' between each operand's digits.
4111
4112 The operands must be both logical numbers.
4113
4114 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4115 Decimal("0")
4116 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4117 Decimal("1")
4118 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4119 Decimal("1")
4120 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4121 Decimal("0")
4122 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4123 Decimal("110")
4124 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4125 Decimal("1101")
4126 """
4127 return a.logical_xor(b, context=self)
4128
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004129 def max(self, a,b):
4130 """max compares two values numerically and returns the maximum.
4131
4132 If either operand is a NaN then the general rules apply.
4133 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004134 operation. If they are numerically equal then the left-hand operand
4135 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004136 infinity) of the two operands is chosen as the result.
4137
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004138 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004139 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004140 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004141 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004142 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004143 Decimal("1")
4144 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4145 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004146 """
4147 return a.max(b, context=self)
4148
Facundo Batista353750c2007-09-13 18:13:15 +00004149 def max_mag(self, a, b):
4150 """Compares the values numerically with their sign ignored."""
4151 return a.max_mag(b, context=self)
4152
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004153 def min(self, a,b):
4154 """min compares two values numerically and returns the minimum.
4155
4156 If either operand is a NaN then the general rules apply.
4157 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004158 operation. If they are numerically equal then the left-hand operand
4159 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004160 infinity) of the two operands is chosen as the result.
4161
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004162 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004163 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004164 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004165 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004166 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004167 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004168 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4169 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004170 """
4171 return a.min(b, context=self)
4172
Facundo Batista353750c2007-09-13 18:13:15 +00004173 def min_mag(self, a, b):
4174 """Compares the values numerically with their sign ignored."""
4175 return a.min_mag(b, context=self)
4176
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004177 def minus(self, a):
4178 """Minus corresponds to unary prefix minus in Python.
4179
4180 The operation is evaluated using the same rules as subtract; the
4181 operation minus(a) is calculated as subtract('0', a) where the '0'
4182 has the same exponent as the operand.
4183
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004184 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004185 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004186 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004187 Decimal("1.3")
4188 """
4189 return a.__neg__(context=self)
4190
4191 def multiply(self, a, b):
4192 """multiply multiplies two operands.
4193
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004194 If either operand is a special value then the general rules apply.
4195 Otherwise, the operands are multiplied together ('long multiplication'),
4196 resulting in a number which may be as long as the sum of the lengths
4197 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004198
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004199 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004200 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004201 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004202 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004203 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004204 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004205 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004206 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004207 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004208 Decimal("4.28135971E+11")
4209 """
4210 return a.__mul__(b, context=self)
4211
Facundo Batista353750c2007-09-13 18:13:15 +00004212 def next_minus(self, a):
4213 """Returns the largest representable number smaller than a.
4214
4215 >>> c = ExtendedContext.copy()
4216 >>> c.Emin = -999
4217 >>> c.Emax = 999
4218 >>> ExtendedContext.next_minus(Decimal('1'))
4219 Decimal("0.999999999")
4220 >>> c.next_minus(Decimal('1E-1007'))
4221 Decimal("0E-1007")
4222 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4223 Decimal("-1.00000004")
4224 >>> c.next_minus(Decimal('Infinity'))
4225 Decimal("9.99999999E+999")
4226 """
4227 return a.next_minus(context=self)
4228
4229 def next_plus(self, a):
4230 """Returns the smallest representable number larger than a.
4231
4232 >>> c = ExtendedContext.copy()
4233 >>> c.Emin = -999
4234 >>> c.Emax = 999
4235 >>> ExtendedContext.next_plus(Decimal('1'))
4236 Decimal("1.00000001")
4237 >>> c.next_plus(Decimal('-1E-1007'))
4238 Decimal("-0E-1007")
4239 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4240 Decimal("-1.00000002")
4241 >>> c.next_plus(Decimal('-Infinity'))
4242 Decimal("-9.99999999E+999")
4243 """
4244 return a.next_plus(context=self)
4245
4246 def next_toward(self, a, b):
4247 """Returns the number closest to a, in direction towards b.
4248
4249 The result is the closest representable number from the first
4250 operand (but not the first operand) that is in the direction
4251 towards the second operand, unless the operands have the same
4252 value.
4253
4254 >>> c = ExtendedContext.copy()
4255 >>> c.Emin = -999
4256 >>> c.Emax = 999
4257 >>> c.next_toward(Decimal('1'), Decimal('2'))
4258 Decimal("1.00000001")
4259 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4260 Decimal("-0E-1007")
4261 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4262 Decimal("-1.00000002")
4263 >>> c.next_toward(Decimal('1'), Decimal('0'))
4264 Decimal("0.999999999")
4265 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4266 Decimal("0E-1007")
4267 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4268 Decimal("-1.00000004")
4269 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4270 Decimal("-0.00")
4271 """
4272 return a.next_toward(b, context=self)
4273
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004274 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004275 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004276
4277 Essentially a plus operation with all trailing zeros removed from the
4278 result.
4279
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004280 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004281 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004282 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004283 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004284 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004285 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004286 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004287 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004288 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004289 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004290 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004291 Decimal("0")
4292 """
4293 return a.normalize(context=self)
4294
Facundo Batista353750c2007-09-13 18:13:15 +00004295 def number_class(self, a):
4296 """Returns an indication of the class of the operand.
4297
4298 The class is one of the following strings:
4299 -sNaN
4300 -NaN
4301 -Infinity
4302 -Normal
4303 -Subnormal
4304 -Zero
4305 +Zero
4306 +Subnormal
4307 +Normal
4308 +Infinity
4309
4310 >>> c = Context(ExtendedContext)
4311 >>> c.Emin = -999
4312 >>> c.Emax = 999
4313 >>> c.number_class(Decimal('Infinity'))
4314 '+Infinity'
4315 >>> c.number_class(Decimal('1E-10'))
4316 '+Normal'
4317 >>> c.number_class(Decimal('2.50'))
4318 '+Normal'
4319 >>> c.number_class(Decimal('0.1E-999'))
4320 '+Subnormal'
4321 >>> c.number_class(Decimal('0'))
4322 '+Zero'
4323 >>> c.number_class(Decimal('-0'))
4324 '-Zero'
4325 >>> c.number_class(Decimal('-0.1E-999'))
4326 '-Subnormal'
4327 >>> c.number_class(Decimal('-1E-10'))
4328 '-Normal'
4329 >>> c.number_class(Decimal('-2.50'))
4330 '-Normal'
4331 >>> c.number_class(Decimal('-Infinity'))
4332 '-Infinity'
4333 >>> c.number_class(Decimal('NaN'))
4334 'NaN'
4335 >>> c.number_class(Decimal('-NaN'))
4336 'NaN'
4337 >>> c.number_class(Decimal('sNaN'))
4338 'sNaN'
4339 """
4340 return a.number_class(context=self)
4341
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004342 def plus(self, a):
4343 """Plus corresponds to unary prefix plus in Python.
4344
4345 The operation is evaluated using the same rules as add; the
4346 operation plus(a) is calculated as add('0', a) where the '0'
4347 has the same exponent as the operand.
4348
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004349 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004350 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004351 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004352 Decimal("-1.3")
4353 """
4354 return a.__pos__(context=self)
4355
4356 def power(self, a, b, modulo=None):
4357 """Raises a to the power of b, to modulo if given.
4358
Facundo Batista353750c2007-09-13 18:13:15 +00004359 With two arguments, compute a**b. If a is negative then b
4360 must be integral. The result will be inexact unless b is
4361 integral and the result is finite and can be expressed exactly
4362 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004363
Facundo Batista353750c2007-09-13 18:13:15 +00004364 With three arguments, compute (a**b) % modulo. For the
4365 three argument form, the following restrictions on the
4366 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004367
Facundo Batista353750c2007-09-13 18:13:15 +00004368 - all three arguments must be integral
4369 - b must be nonnegative
4370 - at least one of a or b must be nonzero
4371 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004372
Facundo Batista353750c2007-09-13 18:13:15 +00004373 The result of pow(a, b, modulo) is identical to the result
4374 that would be obtained by computing (a**b) % modulo with
4375 unbounded precision, but is computed more efficiently. It is
4376 always exact.
4377
4378 >>> c = ExtendedContext.copy()
4379 >>> c.Emin = -999
4380 >>> c.Emax = 999
4381 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004382 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004383 >>> c.power(Decimal('-2'), Decimal('3'))
4384 Decimal("-8")
4385 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004386 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004387 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004388 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004389 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4390 Decimal("2.00000000")
4391 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004392 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004393 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004394 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004395 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004396 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004397 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004398 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004399 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004400 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004401 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004402 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004403 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004404 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004405 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004406 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004407
4408 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4409 Decimal("11")
4410 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4411 Decimal("-11")
4412 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4413 Decimal("1")
4414 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4415 Decimal("11")
4416 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4417 Decimal("11729830")
4418 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4419 Decimal("-0")
4420 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4421 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004422 """
4423 return a.__pow__(b, modulo, context=self)
4424
4425 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004426 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004427
4428 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004429 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004430 exponent is being increased), multiplied by a positive power of ten (if
4431 the exponent is being decreased), or is unchanged (if the exponent is
4432 already equal to that of the right-hand operand).
4433
4434 Unlike other operations, if the length of the coefficient after the
4435 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004436 operation condition is raised. This guarantees that, unless there is
4437 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004438 equal to that of the right-hand operand.
4439
4440 Also unlike other operations, quantize will never raise Underflow, even
4441 if the result is subnormal and inexact.
4442
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004443 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004444 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004445 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004446 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004447 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004448 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004449 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004450 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004451 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004452 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004453 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004454 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004455 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004456 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004457 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004458 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004459 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004460 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004461 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004462 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004463 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004464 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004465 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004466 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004467 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004468 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004469 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004470 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004471 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004472 Decimal("2E+2")
4473 """
4474 return a.quantize(b, context=self)
4475
Facundo Batista353750c2007-09-13 18:13:15 +00004476 def radix(self):
4477 """Just returns 10, as this is Decimal, :)
4478
4479 >>> ExtendedContext.radix()
4480 Decimal("10")
4481 """
4482 return Decimal(10)
4483
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004484 def remainder(self, a, b):
4485 """Returns the remainder from integer division.
4486
4487 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004488 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004489 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004490 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004491
4492 This operation will fail under the same conditions as integer division
4493 (that is, if integer division on the same two operands would fail, the
4494 remainder cannot be calculated).
4495
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004496 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004497 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004498 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004499 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004500 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004501 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004502 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004503 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004504 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004505 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004506 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004507 Decimal("1.0")
4508 """
4509 return a.__mod__(b, context=self)
4510
4511 def remainder_near(self, a, b):
4512 """Returns to be "a - b * n", where n is the integer nearest the exact
4513 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004514 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004515 sign of a.
4516
4517 This operation will fail under the same conditions as integer division
4518 (that is, if integer division on the same two operands would fail, the
4519 remainder cannot be calculated).
4520
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004521 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004522 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004523 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004524 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004525 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004526 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004527 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004528 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004529 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004530 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004531 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004532 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004533 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004534 Decimal("-0.3")
4535 """
4536 return a.remainder_near(b, context=self)
4537
Facundo Batista353750c2007-09-13 18:13:15 +00004538 def rotate(self, a, b):
4539 """Returns a rotated copy of a, b times.
4540
4541 The coefficient of the result is a rotated copy of the digits in
4542 the coefficient of the first operand. The number of places of
4543 rotation is taken from the absolute value of the second operand,
4544 with the rotation being to the left if the second operand is
4545 positive or to the right otherwise.
4546
4547 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4548 Decimal("400000003")
4549 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4550 Decimal("12")
4551 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4552 Decimal("891234567")
4553 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4554 Decimal("123456789")
4555 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4556 Decimal("345678912")
4557 """
4558 return a.rotate(b, context=self)
4559
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004560 def same_quantum(self, a, b):
4561 """Returns True if the two operands have the same exponent.
4562
4563 The result is never affected by either the sign or the coefficient of
4564 either operand.
4565
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004566 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004567 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004568 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004569 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004570 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004571 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004572 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004573 True
4574 """
4575 return a.same_quantum(b)
4576
Facundo Batista353750c2007-09-13 18:13:15 +00004577 def scaleb (self, a, b):
4578 """Returns the first operand after adding the second value its exp.
4579
4580 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4581 Decimal("0.0750")
4582 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4583 Decimal("7.50")
4584 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4585 Decimal("7.50E+3")
4586 """
4587 return a.scaleb (b, context=self)
4588
4589 def shift(self, a, b):
4590 """Returns a shifted copy of a, b times.
4591
4592 The coefficient of the result is a shifted copy of the digits
4593 in the coefficient of the first operand. The number of places
4594 to shift is taken from the absolute value of the second operand,
4595 with the shift being to the left if the second operand is
4596 positive or to the right otherwise. Digits shifted into the
4597 coefficient are zeros.
4598
4599 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4600 Decimal("400000000")
4601 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4602 Decimal("0")
4603 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4604 Decimal("1234567")
4605 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4606 Decimal("123456789")
4607 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4608 Decimal("345678900")
4609 """
4610 return a.shift(b, context=self)
4611
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004612 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004613 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004614
4615 If the result must be inexact, it is rounded using the round-half-even
4616 algorithm.
4617
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004618 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004619 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004620 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004621 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004622 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004623 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004624 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004625 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004626 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004627 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004628 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004629 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004630 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004631 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004632 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004633 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004634 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004635 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004636 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004637 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004638 """
4639 return a.sqrt(context=self)
4640
4641 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004642 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004643
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004644 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004645 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004646 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004647 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004648 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004649 Decimal("-0.77")
4650 """
4651 return a.__sub__(b, context=self)
4652
4653 def to_eng_string(self, a):
4654 """Converts a number to a string, using scientific notation.
4655
4656 The operation is not affected by the context.
4657 """
4658 return a.to_eng_string(context=self)
4659
4660 def to_sci_string(self, a):
4661 """Converts a number to a string, using scientific notation.
4662
4663 The operation is not affected by the context.
4664 """
4665 return a.__str__(context=self)
4666
Facundo Batista353750c2007-09-13 18:13:15 +00004667 def to_integral_exact(self, a):
4668 """Rounds to an integer.
4669
4670 When the operand has a negative exponent, the result is the same
4671 as using the quantize() operation using the given operand as the
4672 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4673 of the operand as the precision setting; Inexact and Rounded flags
4674 are allowed in this operation. The rounding mode is taken from the
4675 context.
4676
4677 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4678 Decimal("2")
4679 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4680 Decimal("100")
4681 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4682 Decimal("100")
4683 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4684 Decimal("102")
4685 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4686 Decimal("-102")
4687 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4688 Decimal("1.0E+6")
4689 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4690 Decimal("7.89E+77")
4691 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4692 Decimal("-Infinity")
4693 """
4694 return a.to_integral_exact(context=self)
4695
4696 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004697 """Rounds to an integer.
4698
4699 When the operand has a negative exponent, the result is the same
4700 as using the quantize() operation using the given operand as the
4701 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4702 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004703 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004704
Facundo Batista353750c2007-09-13 18:13:15 +00004705 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004706 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004707 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004708 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004709 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004710 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004711 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004712 Decimal("102")
Facundo Batista353750c2007-09-13 18:13:15 +00004713 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004714 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004715 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004716 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004717 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004718 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004719 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004720 Decimal("-Infinity")
4721 """
Facundo Batista353750c2007-09-13 18:13:15 +00004722 return a.to_integral_value(context=self)
4723
4724 # the method name changed, but we provide also the old one, for compatibility
4725 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004726
4727class _WorkRep(object):
4728 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004729 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004730 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004731 # exp: None, int, or string
4732
4733 def __init__(self, value=None):
4734 if value is None:
4735 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004736 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004737 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004738 elif isinstance(value, Decimal):
4739 self.sign = value._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004740 cum = 0
Raymond Hettinger17931de2004-10-27 06:21:46 +00004741 for digit in value._int:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004742 cum = cum * 10 + digit
4743 self.int = cum
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004744 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004745 else:
4746 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004747 self.sign = value[0]
4748 self.int = value[1]
4749 self.exp = value[2]
4750
4751 def __repr__(self):
4752 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4753
4754 __str__ = __repr__
4755
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004756
4757
4758def _normalize(op1, op2, shouldround = 0, prec = 0):
4759 """Normalizes op1, op2 to have the same exp and length of coefficient.
4760
4761 Done during addition.
4762 """
Facundo Batista353750c2007-09-13 18:13:15 +00004763 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004764 tmp = op2
4765 other = op1
4766 else:
4767 tmp = op1
4768 other = op2
4769
Facundo Batista353750c2007-09-13 18:13:15 +00004770 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4771 # Then adding 10**exp to tmp has the same effect (after rounding)
4772 # as adding any positive quantity smaller than 10**exp; similarly
4773 # for subtraction. So if other is smaller than 10**exp we replace
4774 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4775 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004776 tmp_len = len(str(tmp.int))
4777 other_len = len(str(other.int))
Facundo Batista353750c2007-09-13 18:13:15 +00004778 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4779 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004780 other.int = 1
Facundo Batista353750c2007-09-13 18:13:15 +00004781 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004782
Facundo Batista353750c2007-09-13 18:13:15 +00004783 tmp.int *= 10 ** (tmp.exp - other.exp)
4784 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004785 return op1, op2
4786
Facundo Batista353750c2007-09-13 18:13:15 +00004787##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4788
4789# This function from Tim Peters was taken from here:
4790# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4791# The correction being in the function definition is for speed, and
4792# the whole function is not resolved with math.log because of avoiding
4793# the use of floats.
4794def _nbits(n, correction = {
4795 '0': 4, '1': 3, '2': 2, '3': 2,
4796 '4': 1, '5': 1, '6': 1, '7': 1,
4797 '8': 0, '9': 0, 'a': 0, 'b': 0,
4798 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4799 """Number of bits in binary representation of the positive integer n,
4800 or 0 if n == 0.
4801 """
4802 if n < 0:
4803 raise ValueError("The argument to _nbits should be nonnegative.")
4804 hex_n = "%x" % n
4805 return 4*len(hex_n) - correction[hex_n[0]]
4806
4807def _sqrt_nearest(n, a):
4808 """Closest integer to the square root of the positive integer n. a is
4809 an initial approximation to the square root. Any positive integer
4810 will do for a, but the closer a is to the square root of n the
4811 faster convergence will be.
4812
4813 """
4814 if n <= 0 or a <= 0:
4815 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4816
4817 b=0
4818 while a != b:
4819 b, a = a, a--n//a>>1
4820 return a
4821
4822def _rshift_nearest(x, shift):
4823 """Given an integer x and a nonnegative integer shift, return closest
4824 integer to x / 2**shift; use round-to-even in case of a tie.
4825
4826 """
4827 b, q = 1L << shift, x >> shift
4828 return q + (2*(x & (b-1)) + (q&1) > b)
4829
4830def _div_nearest(a, b):
4831 """Closest integer to a/b, a and b positive integers; rounds to even
4832 in the case of a tie.
4833
4834 """
4835 q, r = divmod(a, b)
4836 return q + (2*r + (q&1) > b)
4837
4838def _ilog(x, M, L = 8):
4839 """Integer approximation to M*log(x/M), with absolute error boundable
4840 in terms only of x/M.
4841
4842 Given positive integers x and M, return an integer approximation to
4843 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4844 between the approximation and the exact result is at most 22. For
4845 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4846 both cases these are upper bounds on the error; it will usually be
4847 much smaller."""
4848
4849 # The basic algorithm is the following: let log1p be the function
4850 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4851 # the reduction
4852 #
4853 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4854 #
4855 # repeatedly until the argument to log1p is small (< 2**-L in
4856 # absolute value). For small y we can use the Taylor series
4857 # expansion
4858 #
4859 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4860 #
4861 # truncating at T such that y**T is small enough. The whole
4862 # computation is carried out in a form of fixed-point arithmetic,
4863 # with a real number z being represented by an integer
4864 # approximation to z*M. To avoid loss of precision, the y below
4865 # is actually an integer approximation to 2**R*y*M, where R is the
4866 # number of reductions performed so far.
4867
4868 y = x-M
4869 # argument reduction; R = number of reductions performed
4870 R = 0
4871 while (R <= L and long(abs(y)) << L-R >= M or
4872 R > L and abs(y) >> R-L >= M):
4873 y = _div_nearest(long(M*y) << 1,
4874 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4875 R += 1
4876
4877 # Taylor series with T terms
4878 T = -int(-10*len(str(M))//(3*L))
4879 yshift = _rshift_nearest(y, R)
4880 w = _div_nearest(M, T)
4881 for k in xrange(T-1, 0, -1):
4882 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4883
4884 return _div_nearest(w*y, M)
4885
4886def _dlog10(c, e, p):
4887 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4888 approximation to 10**p * log10(c*10**e), with an absolute error of
4889 at most 1. Assumes that c*10**e is not exactly 1."""
4890
4891 # increase precision by 2; compensate for this by dividing
4892 # final result by 100
4893 p += 2
4894
4895 # write c*10**e as d*10**f with either:
4896 # f >= 0 and 1 <= d <= 10, or
4897 # f <= 0 and 0.1 <= d <= 1.
4898 # Thus for c*10**e close to 1, f = 0
4899 l = len(str(c))
4900 f = e+l - (e+l >= 1)
4901
4902 if p > 0:
4903 M = 10**p
4904 k = e+p-f
4905 if k >= 0:
4906 c *= 10**k
4907 else:
4908 c = _div_nearest(c, 10**-k)
4909
4910 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004911 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004912 log_d = _div_nearest(log_d*M, log_10)
4913 log_tenpower = f*M # exact
4914 else:
4915 log_d = 0 # error < 2.31
4916 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4917
4918 return _div_nearest(log_tenpower+log_d, 100)
4919
4920def _dlog(c, e, p):
4921 """Given integers c, e and p with c > 0, compute an integer
4922 approximation to 10**p * log(c*10**e), with an absolute error of
4923 at most 1. Assumes that c*10**e is not exactly 1."""
4924
4925 # Increase precision by 2. The precision increase is compensated
4926 # for at the end with a division by 100.
4927 p += 2
4928
4929 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4930 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4931 # as 10**p * log(d) + 10**p*f * log(10).
4932 l = len(str(c))
4933 f = e+l - (e+l >= 1)
4934
4935 # compute approximation to 10**p*log(d), with error < 27
4936 if p > 0:
4937 k = e+p-f
4938 if k >= 0:
4939 c *= 10**k
4940 else:
4941 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4942
4943 # _ilog magnifies existing error in c by a factor of at most 10
4944 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4945 else:
4946 # p <= 0: just approximate the whole thing by 0; error < 2.31
4947 log_d = 0
4948
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004949 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00004950 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004951 extra = len(str(abs(f)))-1
4952 if p + extra >= 0:
4953 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4954 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4955 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00004956 else:
4957 f_log_ten = 0
4958 else:
4959 f_log_ten = 0
4960
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004961 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004962 return _div_nearest(f_log_ten + log_d, 100)
4963
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004964class _Log10Memoize(object):
4965 """Class to compute, store, and allow retrieval of, digits of the
4966 constant log(10) = 2.302585.... This constant is needed by
4967 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4968 def __init__(self):
4969 self.digits = "23025850929940456840179914546843642076011014886"
4970
4971 def getdigits(self, p):
4972 """Given an integer p >= 0, return floor(10**p)*log(10).
4973
4974 For example, self.getdigits(3) returns 2302.
4975 """
4976 # digits are stored as a string, for quick conversion to
4977 # integer in the case that we've already computed enough
4978 # digits; the stored digits should always be correct
4979 # (truncated, not rounded to nearest).
4980 if p < 0:
4981 raise ValueError("p should be nonnegative")
4982
4983 if p >= len(self.digits):
4984 # compute p+3, p+6, p+9, ... digits; continue until at
4985 # least one of the extra digits is nonzero
4986 extra = 3
4987 while True:
4988 # compute p+extra digits, correct to within 1ulp
4989 M = 10**(p+extra+2)
4990 digits = str(_div_nearest(_ilog(10*M, M), 100))
4991 if digits[-extra:] != '0'*extra:
4992 break
4993 extra += 3
4994 # keep all reliable digits so far; remove trailing zeros
4995 # and next nonzero digit
4996 self.digits = digits.rstrip('0')[:-1]
4997 return int(self.digits[:p+1])
4998
4999_log10_digits = _Log10Memoize().getdigits
5000
Facundo Batista353750c2007-09-13 18:13:15 +00005001def _iexp(x, M, L=8):
5002 """Given integers x and M, M > 0, such that x/M is small in absolute
5003 value, compute an integer approximation to M*exp(x/M). For 0 <=
5004 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5005 is usually much smaller)."""
5006
5007 # Algorithm: to compute exp(z) for a real number z, first divide z
5008 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5009 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5010 # series
5011 #
5012 # expm1(x) = x + x**2/2! + x**3/3! + ...
5013 #
5014 # Now use the identity
5015 #
5016 # expm1(2x) = expm1(x)*(expm1(x)+2)
5017 #
5018 # R times to compute the sequence expm1(z/2**R),
5019 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5020
5021 # Find R such that x/2**R/M <= 2**-L
5022 R = _nbits((long(x)<<L)//M)
5023
5024 # Taylor series. (2**L)**T > M
5025 T = -int(-10*len(str(M))//(3*L))
5026 y = _div_nearest(x, T)
5027 Mshift = long(M)<<R
5028 for i in xrange(T-1, 0, -1):
5029 y = _div_nearest(x*(Mshift + y), Mshift * i)
5030
5031 # Expansion
5032 for k in xrange(R-1, -1, -1):
5033 Mshift = long(M)<<(k+2)
5034 y = _div_nearest(y*(y+Mshift), Mshift)
5035
5036 return M+y
5037
5038def _dexp(c, e, p):
5039 """Compute an approximation to exp(c*10**e), with p decimal places of
5040 precision.
5041
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005042 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005043
5044 10**(p-1) <= d <= 10**p, and
5045 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5046
5047 In other words, d*10**f is an approximation to exp(c*10**e) with p
5048 digits of precision, and with an error in d of at most 1. This is
5049 almost, but not quite, the same as the error being < 1ulp: when d
5050 = 10**(p-1) the error could be up to 10 ulp."""
5051
5052 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5053 p += 2
5054
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005055 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005056 extra = max(0, e + len(str(c)) - 1)
5057 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005058
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005059 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005060 # rounding down
5061 shift = e+q
5062 if shift >= 0:
5063 cshift = c*10**shift
5064 else:
5065 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005066 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005067
5068 # reduce remainder back to original precision
5069 rem = _div_nearest(rem, 10**extra)
5070
5071 # error in result of _iexp < 120; error after division < 0.62
5072 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5073
5074def _dpower(xc, xe, yc, ye, p):
5075 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5076 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5077
5078 10**(p-1) <= c <= 10**p, and
5079 (c-1)*10**e < x**y < (c+1)*10**e
5080
5081 in other words, c*10**e is an approximation to x**y with p digits
5082 of precision, and with an error in c of at most 1. (This is
5083 almost, but not quite, the same as the error being < 1ulp: when c
5084 == 10**(p-1) we can only guarantee error < 10ulp.)
5085
5086 We assume that: x is positive and not equal to 1, and y is nonzero.
5087 """
5088
5089 # Find b such that 10**(b-1) <= |y| <= 10**b
5090 b = len(str(abs(yc))) + ye
5091
5092 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5093 lxc = _dlog(xc, xe, p+b+1)
5094
5095 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5096 shift = ye-b
5097 if shift >= 0:
5098 pc = lxc*yc*10**shift
5099 else:
5100 pc = _div_nearest(lxc*yc, 10**-shift)
5101
5102 if pc == 0:
5103 # we prefer a result that isn't exactly 1; this makes it
5104 # easier to compute a correctly rounded result in __pow__
5105 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5106 coeff, exp = 10**(p-1)+1, 1-p
5107 else:
5108 coeff, exp = 10**p-1, -p
5109 else:
5110 coeff, exp = _dexp(pc, -(p+1), p+1)
5111 coeff = _div_nearest(coeff, 10)
5112 exp += 1
5113
5114 return coeff, exp
5115
5116def _log10_lb(c, correction = {
5117 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5118 '6': 23, '7': 16, '8': 10, '9': 5}):
5119 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5120 if c <= 0:
5121 raise ValueError("The argument to _log10_lb should be nonnegative.")
5122 str_c = str(c)
5123 return 100*len(str_c) - correction[str_c[0]]
5124
Facundo Batista59c58842007-04-10 12:58:45 +00005125##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005126
Facundo Batista353750c2007-09-13 18:13:15 +00005127def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005128 """Convert other to Decimal.
5129
5130 Verifies that it's ok to use in an implicit construction.
5131 """
5132 if isinstance(other, Decimal):
5133 return other
5134 if isinstance(other, (int, long)):
5135 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005136 if raiseit:
5137 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005138 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005139
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005140_infinity_map = {
5141 'inf' : 1,
5142 'infinity' : 1,
5143 '+inf' : 1,
5144 '+infinity' : 1,
5145 '-inf' : -1,
5146 '-infinity' : -1
5147}
5148
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005149def _isinfinity(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005150 """Determines whether a string or float is infinity.
5151
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005152 +1 for negative infinity; 0 for finite ; +1 for positive infinity
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005153 """
5154 num = str(num).lower()
5155 return _infinity_map.get(num, 0)
5156
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005157def _isnan(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005158 """Determines whether a string or float is NaN
5159
5160 (1, sign, diagnostic info as string) => NaN
5161 (2, sign, diagnostic info as string) => sNaN
5162 0 => not a NaN
5163 """
5164 num = str(num).lower()
5165 if not num:
5166 return 0
5167
Facundo Batista59c58842007-04-10 12:58:45 +00005168 # Get the sign, get rid of trailing [+-]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005169 sign = 0
5170 if num[0] == '+':
5171 num = num[1:]
Facundo Batista59c58842007-04-10 12:58:45 +00005172 elif num[0] == '-': # elif avoids '+-nan'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005173 num = num[1:]
5174 sign = 1
5175
5176 if num.startswith('nan'):
Facundo Batista59c58842007-04-10 12:58:45 +00005177 if len(num) > 3 and not num[3:].isdigit(): # diagnostic info
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005178 return 0
5179 return (1, sign, num[3:].lstrip('0'))
5180 if num.startswith('snan'):
5181 if len(num) > 4 and not num[4:].isdigit():
5182 return 0
5183 return (2, sign, num[4:].lstrip('0'))
5184 return 0
5185
5186
Facundo Batista59c58842007-04-10 12:58:45 +00005187##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005188
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005189# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005190# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005191
5192DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005193 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005194 traps=[DivisionByZero, Overflow, InvalidOperation],
5195 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005196 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005197 Emax=999999999,
5198 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005199 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005200)
5201
5202# Pre-made alternate contexts offered by the specification
5203# Don't change these; the user should be able to select these
5204# contexts and be able to reproduce results from other implementations
5205# of the spec.
5206
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005207BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005208 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005209 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5210 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005211)
5212
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005213ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005214 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005215 traps=[],
5216 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005217)
5218
5219
Facundo Batista59c58842007-04-10 12:58:45 +00005220##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005221
Facundo Batista59c58842007-04-10 12:58:45 +00005222# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005223Inf = Decimal('Inf')
5224negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005225NaN = Decimal('NaN')
5226Dec_0 = Decimal(0)
5227Dec_p1 = Decimal(1)
5228Dec_n1 = Decimal(-1)
5229Dec_p2 = Decimal(2)
5230Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005231
Facundo Batista59c58842007-04-10 12:58:45 +00005232# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005233Infsign = (Inf, negInf)
5234
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005235
Facundo Batista59c58842007-04-10 12:58:45 +00005236##### crud for parsing strings #############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005237import re
5238
5239# There's an optional sign at the start, and an optional exponent
5240# at the end. The exponent has an optional sign and at least one
5241# digit. In between, must have either at least one digit followed
5242# by an optional fraction, or a decimal point followed by at least
5243# one digit. Yuck.
5244
5245_parser = re.compile(r"""
5246# \s*
5247 (?P<sign>[-+])?
5248 (
5249 (?P<int>\d+) (\. (?P<frac>\d*))?
5250 |
5251 \. (?P<onlyfrac>\d+)
5252 )
5253 ([eE](?P<exp>[-+]? \d+))?
5254# \s*
5255 $
Facundo Batista59c58842007-04-10 12:58:45 +00005256""", re.VERBOSE).match # Uncomment the \s* to allow leading or trailing spaces.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005257
5258del re
5259
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005260def _string2exact(s):
Facundo Batista59c58842007-04-10 12:58:45 +00005261 """Return sign, n, p s.t.
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00005262
Facundo Batista59c58842007-04-10 12:58:45 +00005263 Float string value == -1**sign * n * 10**p exactly
5264 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005265 m = _parser(s)
5266 if m is None:
5267 raise ValueError("invalid literal for Decimal: %r" % s)
5268
5269 if m.group('sign') == "-":
5270 sign = 1
5271 else:
5272 sign = 0
5273
5274 exp = m.group('exp')
5275 if exp is None:
5276 exp = 0
5277 else:
5278 exp = int(exp)
5279
5280 intpart = m.group('int')
5281 if intpart is None:
5282 intpart = ""
5283 fracpart = m.group('onlyfrac')
5284 else:
5285 fracpart = m.group('frac')
5286 if fracpart is None:
5287 fracpart = ""
5288
5289 exp -= len(fracpart)
5290
5291 mantissa = intpart + fracpart
5292 tmp = map(int, mantissa)
5293 backup = tmp
5294 while tmp and tmp[0] == 0:
5295 del tmp[0]
5296
5297 # It's a zero
5298 if not tmp:
5299 if backup:
5300 return (sign, tuple(backup), exp)
5301 return (sign, (0,), exp)
5302 mantissa = tuple(tmp)
5303
5304 return (sign, mantissa, exp)
5305
5306
5307if __name__ == '__main__':
5308 import doctest, sys
5309 doctest.testmod(sys.modules[__name__])