blob: 45ecf88f003254655e8c829d4ed1cd5cbb1a87c9 [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 Batista9b5e2312007-10-19 19:25:57 +0000565 raise ValueError('Invalid tuple size in creation of Decimal '
566 'from list or tuple. The list or tuple '
567 'should have exactly three elements.')
568 # process sign. The isinstance test rejects floats
569 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
570 raise ValueError("Invalid sign. The first value in the tuple "
571 "should be an integer; either 0 for a "
572 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000573 self._sign = value[0]
Facundo Batista9b5e2312007-10-19 19:25:57 +0000574 if value[2] == 'F':
575 # infinity: value[1] is ignored
576 self._int = (0,)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000577 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000578 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000579 else:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000580 # process and validate the digits in value[1]
581 digits = []
582 for digit in value[1]:
583 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
584 # skip leading zeros
585 if digits or digit != 0:
586 digits.append(digit)
587 else:
588 raise ValueError("The second value in the tuple must "
589 "be composed of integers in the range "
590 "0 through 9.")
591 if value[2] in ('n', 'N'):
592 # NaN: digits form the diagnostic
593 self._int = tuple(digits)
594 self._exp = value[2]
595 self._is_special = True
596 elif isinstance(value[2], (int, long)):
597 # finite number: digits give the coefficient
598 self._int = tuple(digits or [0])
599 self._exp = value[2]
600 self._is_special = False
601 else:
602 raise ValueError("The third value in the tuple must "
603 "be an integer, or one of the "
604 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000605 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000606
Raymond Hettingerbf440692004-07-10 14:14:37 +0000607 if isinstance(value, float):
608 raise TypeError("Cannot convert float to Decimal. " +
609 "First convert the float to a string")
610
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000611 # Other argument types may require the context during interpretation
612 if context is None:
613 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000614
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000615 # From a string
616 # REs insist on real strings, so we can too.
617 if isinstance(value, basestring):
618 if _isinfinity(value):
619 self._exp = 'F'
620 self._int = (0,)
621 self._is_special = True
622 if _isinfinity(value) == 1:
623 self._sign = 0
624 else:
625 self._sign = 1
626 return self
627 if _isnan(value):
628 sig, sign, diag = _isnan(value)
629 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000630 if sig == 1:
Facundo Batista59c58842007-04-10 12:58:45 +0000631 self._exp = 'n' # qNaN
632 else: # sig == 2
633 self._exp = 'N' # sNaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000634 self._sign = sign
Facundo Batista59c58842007-04-10 12:58:45 +0000635 self._int = tuple(map(int, diag)) # Diagnostic info
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000636 return self
637 try:
638 self._sign, self._int, self._exp = _string2exact(value)
639 except ValueError:
640 self._is_special = True
Facundo Batista353750c2007-09-13 18:13:15 +0000641 return context._raise_error(ConversionSyntax,
642 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000643 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000644
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000645 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000646
647 def _isnan(self):
648 """Returns whether the number is not actually one.
649
650 0 if a number
Facundo Batista353750c2007-09-13 18:13:15 +0000651 1 if NaN (it could be a normal quiet NaN or a phantom one)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000652 2 if sNaN
653 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000654 if self._is_special:
655 exp = self._exp
656 if exp == 'n':
657 return 1
658 elif exp == 'N':
659 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000660 return 0
661
662 def _isinfinity(self):
663 """Returns whether the number is infinite
664
665 0 if finite or not a number
666 1 if +INF
667 -1 if -INF
668 """
669 if self._exp == 'F':
670 if self._sign:
671 return -1
672 return 1
673 return 0
674
Facundo Batista353750c2007-09-13 18:13:15 +0000675 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000676 """Returns whether the number is not actually one.
677
678 if self, other are sNaN, signal
679 if self, other are NaN return nan
680 return 0
681
682 Done before operations.
683 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000684
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000685 self_is_nan = self._isnan()
686 if other is None:
687 other_is_nan = False
688 else:
689 other_is_nan = other._isnan()
690
691 if self_is_nan or other_is_nan:
692 if context is None:
693 context = getcontext()
694
695 if self_is_nan == 2:
696 return context._raise_error(InvalidOperation, 'sNaN',
697 1, self)
698 if other_is_nan == 2:
699 return context._raise_error(InvalidOperation, 'sNaN',
700 1, other)
701 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000702 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000703
Facundo Batista353750c2007-09-13 18:13:15 +0000704 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000705 return 0
706
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000707 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000708 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000709
Facundo Batista1a191df2007-10-02 17:01:24 +0000710 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000711 """
Facundo Batista1a191df2007-10-02 17:01:24 +0000712 return self._is_special or self._int[0] != 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000713
Facundo Batista353750c2007-09-13 18:13:15 +0000714 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000715 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000716 if other is NotImplemented:
Facundo Batista353750c2007-09-13 18:13:15 +0000717 # Never return NotImplemented
718 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000719
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000720 if self._is_special or other._is_special:
Facundo Batista353750c2007-09-13 18:13:15 +0000721 # check for nans, without raising on a signaling nan
722 if self._isnan() or other._isnan():
Facundo Batista59c58842007-04-10 12:58:45 +0000723 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000724
725 # INF = INF
726 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000727
Facundo Batista353750c2007-09-13 18:13:15 +0000728 # check for zeros; note that cmp(0, -0) should return 0
729 if not self:
730 if not other:
731 return 0
732 else:
733 return -((-1)**other._sign)
734 if not other:
735 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000736
Facundo Batista59c58842007-04-10 12:58:45 +0000737 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000738 if other._sign < self._sign:
739 return -1
740 if self._sign < other._sign:
741 return 1
742
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000743 self_adjusted = self.adjusted()
744 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000745 if self_adjusted == other_adjusted:
746 self_padded = self._int + (0,)*(self._exp - other._exp)
747 other_padded = other._int + (0,)*(other._exp - self._exp)
748 return cmp(self_padded, other_padded) * (-1)**self._sign
749 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000750 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000751 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000752 return -((-1)**self._sign)
753
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000754 def __eq__(self, other):
755 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000756 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000757 return self.__cmp__(other) == 0
758
759 def __ne__(self, other):
760 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000761 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000762 return self.__cmp__(other) != 0
763
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000764 def compare(self, other, context=None):
765 """Compares one to another.
766
767 -1 => a < b
768 0 => a = b
769 1 => a > b
770 NaN => one is NaN
771 Like __cmp__, but returns Decimal instances.
772 """
Facundo Batista353750c2007-09-13 18:13:15 +0000773 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000774
Facundo Batista59c58842007-04-10 12:58:45 +0000775 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000776 if (self._is_special or other and other._is_special):
777 ans = self._check_nans(other, context)
778 if ans:
779 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000780
Facundo Batista353750c2007-09-13 18:13:15 +0000781 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000782
783 def __hash__(self):
784 """x.__hash__() <==> hash(x)"""
785 # Decimal integers must hash the same as the ints
786 # Non-integer decimals are normalized and hashed as strings
Georg Brandl1fb9f522006-05-11 19:57:09 +0000787 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000788 if self._is_special:
789 if self._isnan():
790 raise TypeError('Cannot hash a NaN value.')
791 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000792 if not self:
793 return 0
794 if self._isinteger():
795 op = _WorkRep(self.to_integral_value())
796 # to make computation feasible for Decimals with large
797 # exponent, we use the fact that hash(n) == hash(m) for
798 # any two nonzero integers n and m such that (i) n and m
799 # have the same sign, and (ii) n is congruent to m modulo
800 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
801 # hash((-1)**s*c*pow(10, e, 2**64-1).
802 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000803 return hash(str(self.normalize()))
804
805 def as_tuple(self):
806 """Represents the number as a triple tuple.
807
808 To show the internals exactly as they are.
809 """
810 return (self._sign, self._int, self._exp)
811
812 def __repr__(self):
813 """Represents the number as an instance of Decimal."""
814 # Invariant: eval(repr(d)) == d
815 return 'Decimal("%s")' % str(self)
816
Facundo Batista353750c2007-09-13 18:13:15 +0000817 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000818 """Return string representation of the number in scientific notation.
819
820 Captures all of the information in the underlying representation.
821 """
822
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000823 if self._is_special:
824 if self._isnan():
825 minus = '-'*self._sign
826 if self._int == (0,):
827 info = ''
828 else:
829 info = ''.join(map(str, self._int))
830 if self._isnan() == 2:
831 return minus + 'sNaN' + info
832 return minus + 'NaN' + info
833 if self._isinfinity():
834 minus = '-'*self._sign
835 return minus + 'Infinity'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000836
837 if context is None:
838 context = getcontext()
839
840 tmp = map(str, self._int)
841 numdigits = len(self._int)
842 leftdigits = self._exp + numdigits
Facundo Batista59c58842007-04-10 12:58:45 +0000843 if eng and not self: # self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
844 if self._exp < 0 and self._exp >= -6: # short, no need for e/E
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000845 s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
846 return s
Facundo Batista59c58842007-04-10 12:58:45 +0000847 # exp is closest mult. of 3 >= self._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000848 exp = ((self._exp - 1)// 3 + 1) * 3
849 if exp != self._exp:
850 s = '0.'+'0'*(exp - self._exp)
851 else:
852 s = '0'
853 if exp != 0:
854 if context.capitals:
855 s += 'E'
856 else:
857 s += 'e'
858 if exp > 0:
Facundo Batista59c58842007-04-10 12:58:45 +0000859 s += '+' # 0.0e+3, not 0.0e3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000860 s += str(exp)
861 s = '-'*self._sign + s
862 return s
863 if eng:
864 dotplace = (leftdigits-1)%3+1
865 adjexp = leftdigits -1 - (leftdigits-1)%3
866 else:
867 adjexp = leftdigits-1
868 dotplace = 1
869 if self._exp == 0:
870 pass
871 elif self._exp < 0 and adjexp >= 0:
872 tmp.insert(leftdigits, '.')
873 elif self._exp < 0 and adjexp >= -6:
874 tmp[0:0] = ['0'] * int(-leftdigits)
875 tmp.insert(0, '0.')
876 else:
877 if numdigits > dotplace:
878 tmp.insert(dotplace, '.')
879 elif numdigits < dotplace:
880 tmp.extend(['0']*(dotplace-numdigits))
881 if adjexp:
882 if not context.capitals:
883 tmp.append('e')
884 else:
885 tmp.append('E')
886 if adjexp > 0:
887 tmp.append('+')
888 tmp.append(str(adjexp))
889 if eng:
890 while tmp[0:1] == ['0']:
891 tmp[0:1] = []
892 if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
893 tmp[0:0] = ['0']
894 if self._sign:
895 tmp.insert(0, '-')
896
897 return ''.join(tmp)
898
899 def to_eng_string(self, context=None):
900 """Convert to engineering-type string.
901
902 Engineering notation has an exponent which is a multiple of 3, so there
903 are up to 3 digits left of the decimal place.
904
905 Same rules for when in exponential and when as a value as in __str__.
906 """
Facundo Batista353750c2007-09-13 18:13:15 +0000907 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000908
909 def __neg__(self, context=None):
910 """Returns a copy with the sign switched.
911
912 Rounds, if it has reason.
913 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000914 if self._is_special:
915 ans = self._check_nans(context=context)
916 if ans:
917 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000918
919 if not self:
920 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +0000921 ans = self.copy_sign(Dec_0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000922 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000923 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000924
925 if context is None:
926 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000927 if context._rounding_decision == ALWAYS_ROUND:
Facundo Batista353750c2007-09-13 18:13:15 +0000928 return ans._fix(context)
929 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000930
931 def __pos__(self, context=None):
932 """Returns a copy, unless it is a sNaN.
933
934 Rounds the number (if more then precision digits)
935 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000936 if self._is_special:
937 ans = self._check_nans(context=context)
938 if ans:
939 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000940
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000941 if not self:
942 # + (-0) = 0
Facundo Batista353750c2007-09-13 18:13:15 +0000943 ans = self.copy_sign(Dec_0)
944 else:
945 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000946
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000947 if context is None:
948 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000949 if context._rounding_decision == ALWAYS_ROUND:
Facundo Batista353750c2007-09-13 18:13:15 +0000950 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000951 return ans
952
953 def __abs__(self, round=1, context=None):
954 """Returns the absolute value of self.
955
956 If the second argument is 0, do not round.
957 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000958 if self._is_special:
959 ans = self._check_nans(context=context)
960 if ans:
961 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000962
963 if not round:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000964 if context is None:
965 context = getcontext()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000966 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000967 context._set_rounding_decision(NEVER_ROUND)
968
969 if self._sign:
970 ans = self.__neg__(context=context)
971 else:
972 ans = self.__pos__(context=context)
973
974 return ans
975
976 def __add__(self, other, context=None):
977 """Returns self + other.
978
979 -INF + INF (or the reverse) cause InvalidOperation errors.
980 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000981 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000982 if other is NotImplemented:
983 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000984
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000985 if context is None:
986 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000987
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000988 if self._is_special or other._is_special:
989 ans = self._check_nans(other, context)
990 if ans:
991 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000992
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000993 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000994 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000995 if self._sign != other._sign and other._isinfinity():
996 return context._raise_error(InvalidOperation, '-INF + INF')
997 return Decimal(self)
998 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000999 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000
1001 shouldround = context._rounding_decision == ALWAYS_ROUND
1002
1003 exp = min(self._exp, other._exp)
1004 negativezero = 0
1005 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +00001006 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001007 negativezero = 1
1008
1009 if not self and not other:
1010 sign = min(self._sign, other._sign)
1011 if negativezero:
1012 sign = 1
Facundo Batista353750c2007-09-13 18:13:15 +00001013 ans = Decimal( (sign, (0,), exp))
1014 if shouldround:
1015 ans = ans._fix(context)
1016 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001017 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001018 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001019 ans = other._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001020 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001021 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001022 return ans
1023 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001024 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001025 ans = self._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001026 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001027 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001028 return ans
1029
1030 op1 = _WorkRep(self)
1031 op2 = _WorkRep(other)
1032 op1, op2 = _normalize(op1, op2, shouldround, context.prec)
1033
1034 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001035 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001036 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001037 if op1.int == op2.int:
Facundo Batista353750c2007-09-13 18:13:15 +00001038 ans = Decimal((negativezero, (0,), exp))
1039 if shouldround:
1040 ans = ans._fix(context)
1041 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001042 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001043 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001044 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001045 if op1.sign == 1:
1046 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001047 op1.sign, op2.sign = op2.sign, op1.sign
1048 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001049 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001050 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001051 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001052 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001053 op1.sign, op2.sign = (0, 0)
1054 else:
1055 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001056 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001057
Raymond Hettinger17931de2004-10-27 06:21:46 +00001058 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001059 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001060 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001061 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001062
1063 result.exp = op1.exp
1064 ans = Decimal(result)
1065 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001066 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001067 return ans
1068
1069 __radd__ = __add__
1070
1071 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001072 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001073 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001074 if other is NotImplemented:
1075 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001076
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001077 if self._is_special or other._is_special:
1078 ans = self._check_nans(other, context=context)
1079 if ans:
1080 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081
Facundo Batista353750c2007-09-13 18:13:15 +00001082 # self - other is computed as self + other.copy_negate()
1083 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001084
1085 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001086 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001087 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001088 if other is NotImplemented:
1089 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001090
Facundo Batista353750c2007-09-13 18:13:15 +00001091 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001092
Facundo Batista353750c2007-09-13 18:13:15 +00001093 def _increment(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001094 """Special case of add, adding 1eExponent
1095
1096 Since it is common, (rounding, for example) this adds
1097 (sign)*one E self._exp to the number more efficiently than add.
1098
Facundo Batista353750c2007-09-13 18:13:15 +00001099 Assumes that self is nonspecial.
1100
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001101 For example:
1102 Decimal('5.624e10')._increment() == Decimal('5.625e10')
1103 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001104 L = list(self._int)
1105 L[-1] += 1
1106 spot = len(L)-1
1107 while L[spot] == 10:
1108 L[spot] = 0
1109 if spot == 0:
1110 L[0:0] = [1]
1111 break
1112 L[spot-1] += 1
1113 spot -= 1
Facundo Batista353750c2007-09-13 18:13:15 +00001114 return Decimal((self._sign, L, self._exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001115
1116 def __mul__(self, other, context=None):
1117 """Return self * other.
1118
1119 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1120 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001121 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001122 if other is NotImplemented:
1123 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001124
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001125 if context is None:
1126 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001127
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001128 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001129
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001130 if self._is_special or other._is_special:
1131 ans = self._check_nans(other, context)
1132 if ans:
1133 return ans
1134
1135 if self._isinfinity():
1136 if not other:
1137 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1138 return Infsign[resultsign]
1139
1140 if other._isinfinity():
1141 if not self:
1142 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1143 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001144
1145 resultexp = self._exp + other._exp
1146 shouldround = context._rounding_decision == ALWAYS_ROUND
1147
1148 # Special case for multiplying by zero
1149 if not self or not other:
1150 ans = Decimal((resultsign, (0,), resultexp))
1151 if shouldround:
Facundo Batista59c58842007-04-10 12:58:45 +00001152 # Fixing in case the exponent is out of bounds
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001153 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001154 return ans
1155
1156 # Special case for multiplying by power of 10
1157 if self._int == (1,):
1158 ans = Decimal((resultsign, other._int, resultexp))
1159 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001160 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001161 return ans
1162 if other._int == (1,):
1163 ans = Decimal((resultsign, self._int, resultexp))
1164 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001165 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001166 return ans
1167
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001168 op1 = _WorkRep(self)
1169 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001170
Facundo Batista59c58842007-04-10 12:58:45 +00001171 ans = Decimal((resultsign, map(int, str(op1.int * op2.int)), resultexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001172 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001173 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001174
1175 return ans
1176 __rmul__ = __mul__
1177
1178 def __div__(self, other, context=None):
1179 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001180 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001181 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001182 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001183
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001184 if context is None:
1185 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001186
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001187 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001188
1189 if self._is_special or other._is_special:
1190 ans = self._check_nans(other, context)
1191 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001192 return ans
1193
1194 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001195 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001196
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001197 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001198 return Infsign[sign]
1199
1200 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001201 context._raise_error(Clamped, 'Division by infinity')
1202 return Decimal((sign, (0,), context.Etiny()))
1203
1204 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001205 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001206 if not self:
1207 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001208 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001209
Facundo Batistacce8df22007-09-18 16:53:18 +00001210 if not self:
1211 exp = self._exp - other._exp
1212 coeff = 0
1213 else:
1214 # OK, so neither = 0, INF or NaN
1215 shift = len(other._int) - len(self._int) + context.prec + 1
1216 exp = self._exp - other._exp - shift
1217 op1 = _WorkRep(self)
1218 op2 = _WorkRep(other)
1219 if shift >= 0:
1220 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1221 else:
1222 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1223 if remainder:
1224 # result is not exact; adjust to ensure correct rounding
1225 if coeff % 5 == 0:
1226 coeff += 1
1227 else:
1228 # result is exact; get as close to ideal exponent as possible
1229 ideal_exp = self._exp - other._exp
1230 while exp < ideal_exp and coeff % 10 == 0:
1231 coeff //= 10
1232 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001233
Facundo Batistacce8df22007-09-18 16:53:18 +00001234 ans = Decimal((sign, map(int, str(coeff)), exp))
1235 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001236
Facundo Batistacce8df22007-09-18 16:53:18 +00001237 __truediv__ = __div__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001238
Facundo Batistacce8df22007-09-18 16:53:18 +00001239 def _divide(self, other, context):
1240 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001241
Facundo Batistacce8df22007-09-18 16:53:18 +00001242 Assumes that neither self nor other is a NaN, that self is not
1243 infinite and that other is nonzero.
1244 """
1245 sign = self._sign ^ other._sign
1246 if other._isinfinity():
1247 ideal_exp = self._exp
1248 else:
1249 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001250
Facundo Batistacce8df22007-09-18 16:53:18 +00001251 expdiff = self.adjusted() - other.adjusted()
1252 if not self or other._isinfinity() or expdiff <= -2:
1253 return (Decimal((sign, (0,), 0)),
1254 self._rescale(ideal_exp, context.rounding))
1255 if expdiff <= context.prec:
1256 op1 = _WorkRep(self)
1257 op2 = _WorkRep(other)
1258 if op1.exp >= op2.exp:
1259 op1.int *= 10**(op1.exp - op2.exp)
1260 else:
1261 op2.int *= 10**(op2.exp - op1.exp)
1262 q, r = divmod(op1.int, op2.int)
1263 if q < 10**context.prec:
1264 return (Decimal((sign, map(int, str(q)), 0)),
1265 Decimal((self._sign, map(int, str(r)), ideal_exp)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001266
Facundo Batistacce8df22007-09-18 16:53:18 +00001267 # Here the quotient is too large to be representable
1268 ans = context._raise_error(DivisionImpossible,
1269 'quotient too large in //, % or divmod')
1270 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001271
1272 def __rdiv__(self, other, context=None):
1273 """Swaps self/other and returns __div__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001274 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001275 if other is NotImplemented:
1276 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001277 return other.__div__(self, context=context)
1278 __rtruediv__ = __rdiv__
1279
1280 def __divmod__(self, other, context=None):
1281 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001282 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001283 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001284 other = _convert_other(other)
1285 if other is NotImplemented:
1286 return other
1287
1288 if context is None:
1289 context = getcontext()
1290
1291 ans = self._check_nans(other, context)
1292 if ans:
1293 return (ans, ans)
1294
1295 sign = self._sign ^ other._sign
1296 if self._isinfinity():
1297 if other._isinfinity():
1298 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1299 return ans, ans
1300 else:
1301 return (Infsign[sign],
1302 context._raise_error(InvalidOperation, 'INF % x'))
1303
1304 if not other:
1305 if not self:
1306 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1307 return ans, ans
1308 else:
1309 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1310 context._raise_error(InvalidOperation, 'x % 0'))
1311
1312 quotient, remainder = self._divide(other, context)
1313 if context._rounding_decision == ALWAYS_ROUND:
1314 remainder = remainder._fix(context)
1315 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001316
1317 def __rdivmod__(self, other, context=None):
1318 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001319 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001320 if other is NotImplemented:
1321 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001322 return other.__divmod__(self, context=context)
1323
1324 def __mod__(self, other, context=None):
1325 """
1326 self % other
1327 """
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
Facundo Batistacce8df22007-09-18 16:53:18 +00001332 if context is None:
1333 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001334
Facundo Batistacce8df22007-09-18 16:53:18 +00001335 ans = self._check_nans(other, context)
1336 if ans:
1337 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001338
Facundo Batistacce8df22007-09-18 16:53:18 +00001339 if self._isinfinity():
1340 return context._raise_error(InvalidOperation, 'INF % x')
1341 elif not other:
1342 if self:
1343 return context._raise_error(InvalidOperation, 'x % 0')
1344 else:
1345 return context._raise_error(DivisionUndefined, '0 % 0')
1346
1347 remainder = self._divide(other, context)[1]
1348 if context._rounding_decision == ALWAYS_ROUND:
1349 remainder = remainder._fix(context)
1350 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001351
1352 def __rmod__(self, other, context=None):
1353 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001354 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001355 if other is NotImplemented:
1356 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001357 return other.__mod__(self, context=context)
1358
1359 def remainder_near(self, other, context=None):
1360 """
1361 Remainder nearest to 0- abs(remainder-near) <= other/2
1362 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001363 if context is None:
1364 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001365
Facundo Batista353750c2007-09-13 18:13:15 +00001366 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001367
Facundo Batista353750c2007-09-13 18:13:15 +00001368 ans = self._check_nans(other, context)
1369 if ans:
1370 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001371
Facundo Batista353750c2007-09-13 18:13:15 +00001372 # self == +/-infinity -> InvalidOperation
1373 if self._isinfinity():
1374 return context._raise_error(InvalidOperation,
1375 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001376
Facundo Batista353750c2007-09-13 18:13:15 +00001377 # other == 0 -> either InvalidOperation or DivisionUndefined
1378 if not other:
1379 if self:
1380 return context._raise_error(InvalidOperation,
1381 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001382 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001383 return context._raise_error(DivisionUndefined,
1384 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001385
Facundo Batista353750c2007-09-13 18:13:15 +00001386 # other = +/-infinity -> remainder = self
1387 if other._isinfinity():
1388 ans = Decimal(self)
1389 return ans._fix(context)
1390
1391 # self = 0 -> remainder = self, with ideal exponent
1392 ideal_exponent = min(self._exp, other._exp)
1393 if not self:
1394 ans = Decimal((self._sign, (0,), ideal_exponent))
1395 return ans._fix(context)
1396
1397 # catch most cases of large or small quotient
1398 expdiff = self.adjusted() - other.adjusted()
1399 if expdiff >= context.prec + 1:
1400 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001401 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001402 if expdiff <= -2:
1403 # expdiff <= -2 => abs(self/other) < 0.1
1404 ans = self._rescale(ideal_exponent, context.rounding)
1405 return ans._fix(context)
1406
1407 # adjust both arguments to have the same exponent, then divide
1408 op1 = _WorkRep(self)
1409 op2 = _WorkRep(other)
1410 if op1.exp >= op2.exp:
1411 op1.int *= 10**(op1.exp - op2.exp)
1412 else:
1413 op2.int *= 10**(op2.exp - op1.exp)
1414 q, r = divmod(op1.int, op2.int)
1415 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1416 # 10**ideal_exponent. Apply correction to ensure that
1417 # abs(remainder) <= abs(other)/2
1418 if 2*r + (q&1) > op2.int:
1419 r -= op2.int
1420 q += 1
1421
1422 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001423 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001424
1425 # result has same sign as self unless r is negative
1426 sign = self._sign
1427 if r < 0:
1428 sign = 1-sign
1429 r = -r
1430
1431 ans = Decimal((sign, map(int, str(r)), ideal_exponent))
1432 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001433
1434 def __floordiv__(self, other, context=None):
1435 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001436 other = _convert_other(other)
1437 if other is NotImplemented:
1438 return other
1439
1440 if context is None:
1441 context = getcontext()
1442
1443 ans = self._check_nans(other, context)
1444 if ans:
1445 return ans
1446
1447 if self._isinfinity():
1448 if other._isinfinity():
1449 return context._raise_error(InvalidOperation, 'INF // INF')
1450 else:
1451 return Infsign[self._sign ^ other._sign]
1452
1453 if not other:
1454 if self:
1455 return context._raise_error(DivisionByZero, 'x // 0',
1456 self._sign ^ other._sign)
1457 else:
1458 return context._raise_error(DivisionUndefined, '0 // 0')
1459
1460 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001461
1462 def __rfloordiv__(self, other, context=None):
1463 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001464 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001465 if other is NotImplemented:
1466 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001467 return other.__floordiv__(self, context=context)
1468
1469 def __float__(self):
1470 """Float representation."""
1471 return float(str(self))
1472
1473 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001474 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001475 if self._is_special:
1476 if self._isnan():
1477 context = getcontext()
1478 return context._raise_error(InvalidContext)
1479 elif self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001480 raise OverflowError("Cannot convert infinity to long")
Facundo Batista353750c2007-09-13 18:13:15 +00001481 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001482 if self._exp >= 0:
Facundo Batista353750c2007-09-13 18:13:15 +00001483 return s*int(''.join(map(str, self._int)))*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001484 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001485 return s*int(''.join(map(str, self._int))[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001486
1487 def __long__(self):
1488 """Converts to a long.
1489
1490 Equivalent to long(int(self))
1491 """
1492 return long(self.__int__())
1493
Facundo Batista353750c2007-09-13 18:13:15 +00001494 def _fix_nan(self, context):
1495 """Decapitate the payload of a NaN to fit the context"""
1496 payload = self._int
1497
1498 # maximum length of payload is precision if _clamp=0,
1499 # precision-1 if _clamp=1.
1500 max_payload_len = context.prec - context._clamp
1501 if len(payload) > max_payload_len:
1502 pos = len(payload)-max_payload_len
1503 while pos < len(payload) and payload[pos] == 0:
1504 pos += 1
1505 payload = payload[pos:]
1506 return Decimal((self._sign, payload, self._exp))
Facundo Batista6c398da2007-09-17 17:30:13 +00001507 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001508
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001509 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001510 """Round if it is necessary to keep self within prec precision.
1511
1512 Rounds and fixes the exponent. Does not raise on a sNaN.
1513
1514 Arguments:
1515 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001516 context - context used.
1517 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001518
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001519 if context is None:
1520 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001521
Facundo Batista353750c2007-09-13 18:13:15 +00001522 if self._is_special:
1523 if self._isnan():
1524 # decapitate payload if necessary
1525 return self._fix_nan(context)
1526 else:
1527 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001528 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001529
Facundo Batista353750c2007-09-13 18:13:15 +00001530 # if self is zero then exponent should be between Etiny and
1531 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1532 Etiny = context.Etiny()
1533 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001534 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001535 exp_max = [context.Emax, Etop][context._clamp]
1536 new_exp = min(max(self._exp, Etiny), exp_max)
1537 if new_exp != self._exp:
1538 context._raise_error(Clamped)
1539 return Decimal((self._sign, (0,), new_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001540 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001541 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001542
1543 # exp_min is the smallest allowable exponent of the result,
1544 # equal to max(self.adjusted()-context.prec+1, Etiny)
1545 exp_min = len(self._int) + self._exp - context.prec
1546 if exp_min > Etop:
1547 # overflow: exp_min > Etop iff self.adjusted() > Emax
1548 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001549 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001550 return context._raise_error(Overflow, 'above Emax', self._sign)
1551 self_is_subnormal = exp_min < Etiny
1552 if self_is_subnormal:
1553 context._raise_error(Subnormal)
1554 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001555
Facundo Batista353750c2007-09-13 18:13:15 +00001556 # round if self has too many digits
1557 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001558 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001559 ans = self._rescale(exp_min, context.rounding)
1560 if ans != self:
1561 context._raise_error(Inexact)
1562 if self_is_subnormal:
1563 context._raise_error(Underflow)
1564 if not ans:
1565 # raise Clamped on underflow to 0
1566 context._raise_error(Clamped)
1567 elif len(ans._int) == context.prec+1:
1568 # we get here only if rescaling rounds the
1569 # cofficient up to exactly 10**context.prec
1570 if ans._exp < Etop:
1571 ans = Decimal((ans._sign, ans._int[:-1], ans._exp+1))
1572 else:
1573 # Inexact and Rounded have already been raised
1574 ans = context._raise_error(Overflow, 'above Emax',
1575 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001576 return ans
1577
Facundo Batista353750c2007-09-13 18:13:15 +00001578 # fold down if _clamp == 1 and self has too few digits
1579 if context._clamp == 1 and self._exp > Etop:
1580 context._raise_error(Clamped)
1581 self_padded = self._int + (0,)*(self._exp - Etop)
1582 return Decimal((self._sign, self_padded, Etop))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001583
Facundo Batista353750c2007-09-13 18:13:15 +00001584 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001585 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001586
1587 _pick_rounding_function = {}
1588
Facundo Batista353750c2007-09-13 18:13:15 +00001589 # for each of the rounding functions below:
1590 # self is a finite, nonzero Decimal
1591 # prec is an integer satisfying 0 <= prec < len(self._int)
1592 # the rounded result will have exponent self._exp + len(self._int) - prec;
1593
1594 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001595 """Also known as round-towards-0, truncate."""
Facundo Batista353750c2007-09-13 18:13:15 +00001596 newexp = self._exp + len(self._int) - prec
1597 return Decimal((self._sign, self._int[:prec] or (0,), newexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001598
Facundo Batista353750c2007-09-13 18:13:15 +00001599 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001600 """Rounds away from 0."""
Facundo Batista353750c2007-09-13 18:13:15 +00001601 newexp = self._exp + len(self._int) - prec
1602 tmp = Decimal((self._sign, self._int[:prec] or (0,), newexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001603 for digit in self._int[prec:]:
1604 if digit != 0:
Facundo Batista353750c2007-09-13 18:13:15 +00001605 return tmp._increment()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001606 return tmp
1607
Facundo Batista353750c2007-09-13 18:13:15 +00001608 def _round_half_up(self, prec):
1609 """Rounds 5 up (away from 0)"""
1610 if self._int[prec] >= 5:
1611 return self._round_up(prec)
1612 else:
1613 return self._round_down(prec)
1614
1615 def _round_half_down(self, prec):
1616 """Round 5 down"""
1617 if self._int[prec] == 5:
1618 for digit in self._int[prec+1:]:
1619 if digit != 0:
1620 break
1621 else:
1622 return self._round_down(prec)
1623 return self._round_half_up(prec)
1624
1625 def _round_half_even(self, prec):
1626 """Round 5 to even, rest to nearest."""
1627 if prec and self._int[prec-1] & 1:
1628 return self._round_half_up(prec)
1629 else:
1630 return self._round_half_down(prec)
1631
1632 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001633 """Rounds up (not away from 0 if negative.)"""
1634 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001635 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001636 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001637 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001638
Facundo Batista353750c2007-09-13 18:13:15 +00001639 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001640 """Rounds down (not towards 0 if negative)"""
1641 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001642 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001643 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001644 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001645
Facundo Batista353750c2007-09-13 18:13:15 +00001646 def _round_05up(self, prec):
1647 """Round down unless digit prec-1 is 0 or 5."""
1648 if prec == 0 or self._int[prec-1] in (0, 5):
1649 return self._round_up(prec)
1650 else:
1651 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001652
Facundo Batista353750c2007-09-13 18:13:15 +00001653 def fma(self, other, third, context=None):
1654 """Fused multiply-add.
1655
1656 Returns self*other+third with no rounding of the intermediate
1657 product self*other.
1658
1659 self and other are multiplied together, with no rounding of
1660 the result. The third operand is then added to the result,
1661 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001662 """
Facundo Batista353750c2007-09-13 18:13:15 +00001663
1664 other = _convert_other(other, raiseit=True)
1665 third = _convert_other(third, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001666
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001667 if context is None:
1668 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001669
Facundo Batista353750c2007-09-13 18:13:15 +00001670 # do self*other in fresh context with no traps and no rounding
1671 mul_context = Context(traps=[], flags=[],
1672 _rounding_decision=NEVER_ROUND)
1673 product = self.__mul__(other, mul_context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001674
Facundo Batista353750c2007-09-13 18:13:15 +00001675 if mul_context.flags[InvalidOperation]:
1676 # reraise in current context
1677 return context._raise_error(InvalidOperation,
1678 'invalid multiplication in fma',
1679 1, product)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001680
Facundo Batista353750c2007-09-13 18:13:15 +00001681 ans = product.__add__(third, context)
1682 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001683
Facundo Batista353750c2007-09-13 18:13:15 +00001684 def _power_modulo(self, other, modulo, context=None):
1685 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001686
Facundo Batista353750c2007-09-13 18:13:15 +00001687 # if can't convert other and modulo to Decimal, raise
1688 # TypeError; there's no point returning NotImplemented (no
1689 # equivalent of __rpow__ for three argument pow)
1690 other = _convert_other(other, raiseit=True)
1691 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001692
Facundo Batista353750c2007-09-13 18:13:15 +00001693 if context is None:
1694 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001695
Facundo Batista353750c2007-09-13 18:13:15 +00001696 # deal with NaNs: if there are any sNaNs then first one wins,
1697 # (i.e. behaviour for NaNs is identical to that of fma)
1698 self_is_nan = self._isnan()
1699 other_is_nan = other._isnan()
1700 modulo_is_nan = modulo._isnan()
1701 if self_is_nan or other_is_nan or modulo_is_nan:
1702 if self_is_nan == 2:
1703 return context._raise_error(InvalidOperation, 'sNaN',
1704 1, self)
1705 if other_is_nan == 2:
1706 return context._raise_error(InvalidOperation, 'sNaN',
1707 1, other)
1708 if modulo_is_nan == 2:
1709 return context._raise_error(InvalidOperation, 'sNaN',
1710 1, modulo)
1711 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001712 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001713 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001714 return other._fix_nan(context)
1715 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001716
Facundo Batista353750c2007-09-13 18:13:15 +00001717 # check inputs: we apply same restrictions as Python's pow()
1718 if not (self._isinteger() and
1719 other._isinteger() and
1720 modulo._isinteger()):
1721 return context._raise_error(InvalidOperation,
1722 'pow() 3rd argument not allowed '
1723 'unless all arguments are integers')
1724 if other < 0:
1725 return context._raise_error(InvalidOperation,
1726 'pow() 2nd argument cannot be '
1727 'negative when 3rd argument specified')
1728 if not modulo:
1729 return context._raise_error(InvalidOperation,
1730 'pow() 3rd argument cannot be 0')
1731
1732 # additional restriction for decimal: the modulus must be less
1733 # than 10**prec in absolute value
1734 if modulo.adjusted() >= context.prec:
1735 return context._raise_error(InvalidOperation,
1736 'insufficient precision: pow() 3rd '
1737 'argument must not have more than '
1738 'precision digits')
1739
1740 # define 0**0 == NaN, for consistency with two-argument pow
1741 # (even though it hurts!)
1742 if not other and not self:
1743 return context._raise_error(InvalidOperation,
1744 'at least one of pow() 1st argument '
1745 'and 2nd argument must be nonzero ;'
1746 '0**0 is not defined')
1747
1748 # compute sign of result
1749 if other._iseven():
1750 sign = 0
1751 else:
1752 sign = self._sign
1753
1754 # convert modulo to a Python integer, and self and other to
1755 # Decimal integers (i.e. force their exponents to be >= 0)
1756 modulo = abs(int(modulo))
1757 base = _WorkRep(self.to_integral_value())
1758 exponent = _WorkRep(other.to_integral_value())
1759
1760 # compute result using integer pow()
1761 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1762 for i in xrange(exponent.exp):
1763 base = pow(base, 10, modulo)
1764 base = pow(base, exponent.int, modulo)
1765
1766 return Decimal((sign, map(int, str(base)), 0))
1767
1768 def _power_exact(self, other, p):
1769 """Attempt to compute self**other exactly.
1770
1771 Given Decimals self and other and an integer p, attempt to
1772 compute an exact result for the power self**other, with p
1773 digits of precision. Return None if self**other is not
1774 exactly representable in p digits.
1775
1776 Assumes that elimination of special cases has already been
1777 performed: self and other must both be nonspecial; self must
1778 be positive and not numerically equal to 1; other must be
1779 nonzero. For efficiency, other._exp should not be too large,
1780 so that 10**abs(other._exp) is a feasible calculation."""
1781
1782 # In the comments below, we write x for the value of self and
1783 # y for the value of other. Write x = xc*10**xe and y =
1784 # yc*10**ye.
1785
1786 # The main purpose of this method is to identify the *failure*
1787 # of x**y to be exactly representable with as little effort as
1788 # possible. So we look for cheap and easy tests that
1789 # eliminate the possibility of x**y being exact. Only if all
1790 # these tests are passed do we go on to actually compute x**y.
1791
1792 # Here's the main idea. First normalize both x and y. We
1793 # express y as a rational m/n, with m and n relatively prime
1794 # and n>0. Then for x**y to be exactly representable (at
1795 # *any* precision), xc must be the nth power of a positive
1796 # integer and xe must be divisible by n. If m is negative
1797 # then additionally xc must be a power of either 2 or 5, hence
1798 # a power of 2**n or 5**n.
1799 #
1800 # There's a limit to how small |y| can be: if y=m/n as above
1801 # then:
1802 #
1803 # (1) if xc != 1 then for the result to be representable we
1804 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1805 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1806 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1807 # representable.
1808 #
1809 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1810 # |y| < 1/|xe| then the result is not representable.
1811 #
1812 # Note that since x is not equal to 1, at least one of (1) and
1813 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1814 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1815 #
1816 # There's also a limit to how large y can be, at least if it's
1817 # positive: the normalized result will have coefficient xc**y,
1818 # so if it's representable then xc**y < 10**p, and y <
1819 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1820 # not exactly representable.
1821
1822 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1823 # so |y| < 1/xe and the result is not representable.
1824 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1825 # < 1/nbits(xc).
1826
1827 x = _WorkRep(self)
1828 xc, xe = x.int, x.exp
1829 while xc % 10 == 0:
1830 xc //= 10
1831 xe += 1
1832
1833 y = _WorkRep(other)
1834 yc, ye = y.int, y.exp
1835 while yc % 10 == 0:
1836 yc //= 10
1837 ye += 1
1838
1839 # case where xc == 1: result is 10**(xe*y), with xe*y
1840 # required to be an integer
1841 if xc == 1:
1842 if ye >= 0:
1843 exponent = xe*yc*10**ye
1844 else:
1845 exponent, remainder = divmod(xe*yc, 10**-ye)
1846 if remainder:
1847 return None
1848 if y.sign == 1:
1849 exponent = -exponent
1850 # if other is a nonnegative integer, use ideal exponent
1851 if other._isinteger() and other._sign == 0:
1852 ideal_exponent = self._exp*int(other)
1853 zeros = min(exponent-ideal_exponent, p-1)
1854 else:
1855 zeros = 0
1856 return Decimal((0, (1,) + (0,)*zeros, exponent-zeros))
1857
1858 # case where y is negative: xc must be either a power
1859 # of 2 or a power of 5.
1860 if y.sign == 1:
1861 last_digit = xc % 10
1862 if last_digit in (2,4,6,8):
1863 # quick test for power of 2
1864 if xc & -xc != xc:
1865 return None
1866 # now xc is a power of 2; e is its exponent
1867 e = _nbits(xc)-1
1868 # find e*y and xe*y; both must be integers
1869 if ye >= 0:
1870 y_as_int = yc*10**ye
1871 e = e*y_as_int
1872 xe = xe*y_as_int
1873 else:
1874 ten_pow = 10**-ye
1875 e, remainder = divmod(e*yc, ten_pow)
1876 if remainder:
1877 return None
1878 xe, remainder = divmod(xe*yc, ten_pow)
1879 if remainder:
1880 return None
1881
1882 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1883 return None
1884 xc = 5**e
1885
1886 elif last_digit == 5:
1887 # e >= log_5(xc) if xc is a power of 5; we have
1888 # equality all the way up to xc=5**2658
1889 e = _nbits(xc)*28//65
1890 xc, remainder = divmod(5**e, xc)
1891 if remainder:
1892 return None
1893 while xc % 5 == 0:
1894 xc //= 5
1895 e -= 1
1896 if ye >= 0:
1897 y_as_integer = yc*10**ye
1898 e = e*y_as_integer
1899 xe = xe*y_as_integer
1900 else:
1901 ten_pow = 10**-ye
1902 e, remainder = divmod(e*yc, ten_pow)
1903 if remainder:
1904 return None
1905 xe, remainder = divmod(xe*yc, ten_pow)
1906 if remainder:
1907 return None
1908 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1909 return None
1910 xc = 2**e
1911 else:
1912 return None
1913
1914 if xc >= 10**p:
1915 return None
1916 xe = -e-xe
1917 return Decimal((0, map(int, str(xc)), xe))
1918
1919 # now y is positive; find m and n such that y = m/n
1920 if ye >= 0:
1921 m, n = yc*10**ye, 1
1922 else:
1923 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1924 return None
1925 xc_bits = _nbits(xc)
1926 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1927 return None
1928 m, n = yc, 10**(-ye)
1929 while m % 2 == n % 2 == 0:
1930 m //= 2
1931 n //= 2
1932 while m % 5 == n % 5 == 0:
1933 m //= 5
1934 n //= 5
1935
1936 # compute nth root of xc*10**xe
1937 if n > 1:
1938 # if 1 < xc < 2**n then xc isn't an nth power
1939 if xc != 1 and xc_bits <= n:
1940 return None
1941
1942 xe, rem = divmod(xe, n)
1943 if rem != 0:
1944 return None
1945
1946 # compute nth root of xc using Newton's method
1947 a = 1L << -(-_nbits(xc)//n) # initial estimate
1948 while True:
1949 q, r = divmod(xc, a**(n-1))
1950 if a <= q:
1951 break
1952 else:
1953 a = (a*(n-1) + q)//n
1954 if not (a == q and r == 0):
1955 return None
1956 xc = a
1957
1958 # now xc*10**xe is the nth root of the original xc*10**xe
1959 # compute mth power of xc*10**xe
1960
1961 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1962 # 10**p and the result is not representable.
1963 if xc > 1 and m > p*100//_log10_lb(xc):
1964 return None
1965 xc = xc**m
1966 xe *= m
1967 if xc > 10**p:
1968 return None
1969
1970 # by this point the result *is* exactly representable
1971 # adjust the exponent to get as close as possible to the ideal
1972 # exponent, if necessary
1973 str_xc = str(xc)
1974 if other._isinteger() and other._sign == 0:
1975 ideal_exponent = self._exp*int(other)
1976 zeros = min(xe-ideal_exponent, p-len(str_xc))
1977 else:
1978 zeros = 0
1979 return Decimal((0, map(int, str_xc)+[0,]*zeros, xe-zeros))
1980
1981 def __pow__(self, other, modulo=None, context=None):
1982 """Return self ** other [ % modulo].
1983
1984 With two arguments, compute self**other.
1985
1986 With three arguments, compute (self**other) % modulo. For the
1987 three argument form, the following restrictions on the
1988 arguments hold:
1989
1990 - all three arguments must be integral
1991 - other must be nonnegative
1992 - either self or other (or both) must be nonzero
1993 - modulo must be nonzero and must have at most p digits,
1994 where p is the context precision.
1995
1996 If any of these restrictions is violated the InvalidOperation
1997 flag is raised.
1998
1999 The result of pow(self, other, modulo) is identical to the
2000 result that would be obtained by computing (self**other) %
2001 modulo with unbounded precision, but is computed more
2002 efficiently. It is always exact.
2003 """
2004
2005 if modulo is not None:
2006 return self._power_modulo(other, modulo, context)
2007
2008 other = _convert_other(other)
2009 if other is NotImplemented:
2010 return other
2011
2012 if context is None:
2013 context = getcontext()
2014
2015 # either argument is a NaN => result is NaN
2016 ans = self._check_nans(other, context)
2017 if ans:
2018 return ans
2019
2020 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2021 if not other:
2022 if not self:
2023 return context._raise_error(InvalidOperation, '0 ** 0')
2024 else:
2025 return Dec_p1
2026
2027 # result has sign 1 iff self._sign is 1 and other is an odd integer
2028 result_sign = 0
2029 if self._sign == 1:
2030 if other._isinteger():
2031 if not other._iseven():
2032 result_sign = 1
2033 else:
2034 # -ve**noninteger = NaN
2035 # (-0)**noninteger = 0**noninteger
2036 if self:
2037 return context._raise_error(InvalidOperation,
2038 'x ** y with x negative and y not an integer')
2039 # negate self, without doing any unwanted rounding
2040 self = Decimal((0, self._int, self._exp))
2041
2042 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2043 if not self:
2044 if other._sign == 0:
2045 return Decimal((result_sign, (0,), 0))
2046 else:
2047 return Infsign[result_sign]
2048
2049 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002050 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002051 if other._sign == 0:
2052 return Infsign[result_sign]
2053 else:
2054 return Decimal((result_sign, (0,), 0))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002055
Facundo Batista353750c2007-09-13 18:13:15 +00002056 # 1**other = 1, but the choice of exponent and the flags
2057 # depend on the exponent of self, and on whether other is a
2058 # positive integer, a negative integer, or neither
2059 if self == Dec_p1:
2060 if other._isinteger():
2061 # exp = max(self._exp*max(int(other), 0),
2062 # 1-context.prec) but evaluating int(other) directly
2063 # is dangerous until we know other is small (other
2064 # could be 1e999999999)
2065 if other._sign == 1:
2066 multiplier = 0
2067 elif other > context.prec:
2068 multiplier = context.prec
2069 else:
2070 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002071
Facundo Batista353750c2007-09-13 18:13:15 +00002072 exp = self._exp * multiplier
2073 if exp < 1-context.prec:
2074 exp = 1-context.prec
2075 context._raise_error(Rounded)
2076 else:
2077 context._raise_error(Inexact)
2078 context._raise_error(Rounded)
2079 exp = 1-context.prec
2080
2081 return Decimal((result_sign, (1,)+(0,)*-exp, exp))
2082
2083 # compute adjusted exponent of self
2084 self_adj = self.adjusted()
2085
2086 # self ** infinity is infinity if self > 1, 0 if self < 1
2087 # self ** -infinity is infinity if self < 1, 0 if self > 1
2088 if other._isinfinity():
2089 if (other._sign == 0) == (self_adj < 0):
2090 return Decimal((result_sign, (0,), 0))
2091 else:
2092 return Infsign[result_sign]
2093
2094 # from here on, the result always goes through the call
2095 # to _fix at the end of this function.
2096 ans = None
2097
2098 # crude test to catch cases of extreme overflow/underflow. If
2099 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2100 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2101 # self**other >= 10**(Emax+1), so overflow occurs. The test
2102 # for underflow is similar.
2103 bound = self._log10_exp_bound() + other.adjusted()
2104 if (self_adj >= 0) == (other._sign == 0):
2105 # self > 1 and other +ve, or self < 1 and other -ve
2106 # possibility of overflow
2107 if bound >= len(str(context.Emax)):
2108 ans = Decimal((result_sign, (1,), context.Emax+1))
2109 else:
2110 # self > 1 and other -ve, or self < 1 and other +ve
2111 # possibility of underflow to 0
2112 Etiny = context.Etiny()
2113 if bound >= len(str(-Etiny)):
2114 ans = Decimal((result_sign, (1,), Etiny-1))
2115
2116 # try for an exact result with precision +1
2117 if ans is None:
2118 ans = self._power_exact(other, context.prec + 1)
2119 if ans is not None and result_sign == 1:
2120 ans = Decimal((1, ans._int, ans._exp))
2121
2122 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2123 if ans is None:
2124 p = context.prec
2125 x = _WorkRep(self)
2126 xc, xe = x.int, x.exp
2127 y = _WorkRep(other)
2128 yc, ye = y.int, y.exp
2129 if y.sign == 1:
2130 yc = -yc
2131
2132 # compute correctly rounded result: start with precision +3,
2133 # then increase precision until result is unambiguously roundable
2134 extra = 3
2135 while True:
2136 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2137 if coeff % (5*10**(len(str(coeff))-p-1)):
2138 break
2139 extra += 3
2140
2141 ans = Decimal((result_sign, map(int, str(coeff)), exp))
2142
2143 # the specification says that for non-integer other we need to
2144 # raise Inexact, even when the result is actually exact. In
2145 # the same way, we need to raise Underflow here if the result
2146 # is subnormal. (The call to _fix will take care of raising
2147 # Rounded and Subnormal, as usual.)
2148 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002149 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002150 # pad with zeros up to length context.prec+1 if necessary
2151 if len(ans._int) <= context.prec:
2152 expdiff = context.prec+1 - len(ans._int)
2153 ans = Decimal((ans._sign, ans._int+(0,)*expdiff, ans._exp-expdiff))
2154 if ans.adjusted() < context.Emin:
2155 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002156
Facundo Batista353750c2007-09-13 18:13:15 +00002157 # unlike exp, ln and log10, the power function respects the
2158 # rounding mode; no need to use ROUND_HALF_EVEN here
2159 ans = ans._fix(context)
2160 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002161
2162 def __rpow__(self, other, context=None):
2163 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002164 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002165 if other is NotImplemented:
2166 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002167 return other.__pow__(self, context=context)
2168
2169 def normalize(self, context=None):
2170 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002171
Facundo Batista353750c2007-09-13 18:13:15 +00002172 if context is None:
2173 context = getcontext()
2174
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002175 if self._is_special:
2176 ans = self._check_nans(context=context)
2177 if ans:
2178 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002179
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002180 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002181 if dup._isinfinity():
2182 return dup
2183
2184 if not dup:
2185 return Decimal( (dup._sign, (0,), 0) )
Facundo Batista353750c2007-09-13 18:13:15 +00002186 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002187 end = len(dup._int)
2188 exp = dup._exp
Facundo Batista353750c2007-09-13 18:13:15 +00002189 while dup._int[end-1] == 0 and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002190 exp += 1
2191 end -= 1
2192 return Decimal( (dup._sign, dup._int[:end], exp) )
2193
Facundo Batistabd2fe832007-09-13 18:42:09 +00002194 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002195 """Quantize self so its exponent is the same as that of exp.
2196
2197 Similar to self._rescale(exp._exp) but with error checking.
2198 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002199 exp = _convert_other(exp, raiseit=True)
2200
Facundo Batista353750c2007-09-13 18:13:15 +00002201 if context is None:
2202 context = getcontext()
2203 if rounding is None:
2204 rounding = context.rounding
2205
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002206 if self._is_special or exp._is_special:
2207 ans = self._check_nans(exp, context)
2208 if ans:
2209 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002210
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002211 if exp._isinfinity() or self._isinfinity():
2212 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002213 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002214 return context._raise_error(InvalidOperation,
2215 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002216
Facundo Batistabd2fe832007-09-13 18:42:09 +00002217 # if we're not watching exponents, do a simple rescale
2218 if not watchexp:
2219 ans = self._rescale(exp._exp, rounding)
2220 # raise Inexact and Rounded where appropriate
2221 if ans._exp > self._exp:
2222 context._raise_error(Rounded)
2223 if ans != self:
2224 context._raise_error(Inexact)
2225 return ans
2226
Facundo Batista353750c2007-09-13 18:13:15 +00002227 # exp._exp should be between Etiny and Emax
2228 if not (context.Etiny() <= exp._exp <= context.Emax):
2229 return context._raise_error(InvalidOperation,
2230 'target exponent out of bounds in quantize')
2231
2232 if not self:
2233 ans = Decimal((self._sign, (0,), exp._exp))
2234 return ans._fix(context)
2235
2236 self_adjusted = self.adjusted()
2237 if self_adjusted > context.Emax:
2238 return context._raise_error(InvalidOperation,
2239 'exponent of quantize result too large for current context')
2240 if self_adjusted - exp._exp + 1 > context.prec:
2241 return context._raise_error(InvalidOperation,
2242 'quantize result has too many digits for current context')
2243
2244 ans = self._rescale(exp._exp, rounding)
2245 if ans.adjusted() > context.Emax:
2246 return context._raise_error(InvalidOperation,
2247 'exponent of quantize result too large for current context')
2248 if len(ans._int) > context.prec:
2249 return context._raise_error(InvalidOperation,
2250 'quantize result has too many digits for current context')
2251
2252 # raise appropriate flags
2253 if ans._exp > self._exp:
2254 context._raise_error(Rounded)
2255 if ans != self:
2256 context._raise_error(Inexact)
2257 if ans and ans.adjusted() < context.Emin:
2258 context._raise_error(Subnormal)
2259
2260 # call to fix takes care of any necessary folddown
2261 ans = ans._fix(context)
2262 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002263
2264 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002265 """Return True if self and other have the same exponent; otherwise
2266 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002267
Facundo Batista1a191df2007-10-02 17:01:24 +00002268 If either operand is a special value, the following rules are used:
2269 * return True if both operands are infinities
2270 * return True if both operands are NaNs
2271 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002272 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002273 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002274 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002275 return (self.is_nan() and other.is_nan() or
2276 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002277 return self._exp == other._exp
2278
Facundo Batista353750c2007-09-13 18:13:15 +00002279 def _rescale(self, exp, rounding):
2280 """Rescale self so that the exponent is exp, either by padding with zeros
2281 or by truncating digits, using the given rounding mode.
2282
2283 Specials are returned without change. This operation is
2284 quiet: it raises no flags, and uses no information from the
2285 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002286
2287 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002288 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002289 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002290 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002291 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002292 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002293 return Decimal((self._sign, (0,), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002294
Facundo Batista353750c2007-09-13 18:13:15 +00002295 if self._exp >= exp:
2296 # pad answer with zeros if necessary
2297 return Decimal((self._sign, self._int + (0,)*(self._exp - exp), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002298
Facundo Batista353750c2007-09-13 18:13:15 +00002299 # too many digits; round and lose data. If self.adjusted() <
2300 # exp-1, replace self by 10**(exp-1) before rounding
2301 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002302 if digits < 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002303 self = Decimal((self._sign, (1,), exp-1))
2304 digits = 0
2305 this_function = getattr(self, self._pick_rounding_function[rounding])
2306 return this_function(digits)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002307
Facundo Batista353750c2007-09-13 18:13:15 +00002308 def to_integral_exact(self, rounding=None, context=None):
2309 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002310
Facundo Batista353750c2007-09-13 18:13:15 +00002311 If no rounding mode is specified, take the rounding mode from
2312 the context. This method raises the Rounded and Inexact flags
2313 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002314
Facundo Batista353750c2007-09-13 18:13:15 +00002315 See also: to_integral_value, which does exactly the same as
2316 this method except that it doesn't raise Inexact or Rounded.
2317 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002318 if self._is_special:
2319 ans = self._check_nans(context=context)
2320 if ans:
2321 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002322 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002323 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002324 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002325 if not self:
2326 return Decimal((self._sign, (0,), 0))
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002327 if context is None:
2328 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002329 if rounding is None:
2330 rounding = context.rounding
2331 context._raise_error(Rounded)
2332 ans = self._rescale(0, rounding)
2333 if ans != self:
2334 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002335 return ans
2336
Facundo Batista353750c2007-09-13 18:13:15 +00002337 def to_integral_value(self, rounding=None, context=None):
2338 """Rounds to the nearest integer, without raising inexact, rounded."""
2339 if context is None:
2340 context = getcontext()
2341 if rounding is None:
2342 rounding = context.rounding
2343 if self._is_special:
2344 ans = self._check_nans(context=context)
2345 if ans:
2346 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002347 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002348 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002349 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002350 else:
2351 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002352
Facundo Batista353750c2007-09-13 18:13:15 +00002353 # the method name changed, but we provide also the old one, for compatibility
2354 to_integral = to_integral_value
2355
2356 def sqrt(self, context=None):
2357 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002358 if self._is_special:
2359 ans = self._check_nans(context=context)
2360 if ans:
2361 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002362
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002363 if self._isinfinity() and self._sign == 0:
2364 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002365
2366 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002367 # exponent = self._exp // 2. sqrt(-0) = -0
2368 ans = Decimal((self._sign, (0,), self._exp // 2))
2369 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002370
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002371 if context is None:
2372 context = getcontext()
2373
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002374 if self._sign == 1:
2375 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2376
Facundo Batista353750c2007-09-13 18:13:15 +00002377 # At this point self represents a positive number. Let p be
2378 # the desired precision and express self in the form c*100**e
2379 # with c a positive real number and e an integer, c and e
2380 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2381 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2382 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2383 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2384 # the closest integer to sqrt(c) with the even integer chosen
2385 # in the case of a tie.
2386 #
2387 # To ensure correct rounding in all cases, we use the
2388 # following trick: we compute the square root to an extra
2389 # place (precision p+1 instead of precision p), rounding down.
2390 # Then, if the result is inexact and its last digit is 0 or 5,
2391 # we increase the last digit to 1 or 6 respectively; if it's
2392 # exact we leave the last digit alone. Now the final round to
2393 # p places (or fewer in the case of underflow) will round
2394 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002395
Facundo Batista353750c2007-09-13 18:13:15 +00002396 # use an extra digit of precision
2397 prec = context.prec+1
2398
2399 # write argument in the form c*100**e where e = self._exp//2
2400 # is the 'ideal' exponent, to be used if the square root is
2401 # exactly representable. l is the number of 'digits' of c in
2402 # base 100, so that 100**(l-1) <= c < 100**l.
2403 op = _WorkRep(self)
2404 e = op.exp >> 1
2405 if op.exp & 1:
2406 c = op.int * 10
2407 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002408 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002409 c = op.int
2410 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002411
Facundo Batista353750c2007-09-13 18:13:15 +00002412 # rescale so that c has exactly prec base 100 'digits'
2413 shift = prec-l
2414 if shift >= 0:
2415 c *= 100**shift
2416 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002417 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002418 c, remainder = divmod(c, 100**-shift)
2419 exact = not remainder
2420 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002421
Facundo Batista353750c2007-09-13 18:13:15 +00002422 # find n = floor(sqrt(c)) using Newton's method
2423 n = 10**prec
2424 while True:
2425 q = c//n
2426 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002427 break
Facundo Batista353750c2007-09-13 18:13:15 +00002428 else:
2429 n = n + q >> 1
2430 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002431
Facundo Batista353750c2007-09-13 18:13:15 +00002432 if exact:
2433 # result is exact; rescale to use ideal exponent e
2434 if shift >= 0:
2435 # assert n % 10**shift == 0
2436 n //= 10**shift
2437 else:
2438 n *= 10**-shift
2439 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002440 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002441 # result is not exact; fix last digit as described above
2442 if n % 5 == 0:
2443 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002444
Facundo Batista353750c2007-09-13 18:13:15 +00002445 ans = Decimal((0, map(int, str(n)), e))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002446
Facundo Batista353750c2007-09-13 18:13:15 +00002447 # round, and fit to current context
2448 context = context._shallow_copy()
2449 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002450 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002451 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002452
Facundo Batista353750c2007-09-13 18:13:15 +00002453 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002454
2455 def max(self, other, context=None):
2456 """Returns the larger value.
2457
Facundo Batista353750c2007-09-13 18:13:15 +00002458 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002459 NaN (and signals if one is sNaN). Also rounds.
2460 """
Facundo Batista353750c2007-09-13 18:13:15 +00002461 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002462
Facundo Batista6c398da2007-09-17 17:30:13 +00002463 if context is None:
2464 context = getcontext()
2465
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002466 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002467 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002468 # number is always returned
2469 sn = self._isnan()
2470 on = other._isnan()
2471 if sn or on:
2472 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002473 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002474 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002475 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002476 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002477
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002478 c = self.__cmp__(other)
2479 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002480 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002481 # then an ordering is applied:
2482 #
Facundo Batista59c58842007-04-10 12:58:45 +00002483 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002484 # positive sign and min returns the operand with the negative sign
2485 #
Facundo Batista59c58842007-04-10 12:58:45 +00002486 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002487 # the result. This is exactly the ordering used in compare_total.
2488 c = self.compare_total(other)
2489
2490 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002491 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002492 else:
2493 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002494
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002495 if context._rounding_decision == ALWAYS_ROUND:
2496 return ans._fix(context)
2497 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002498
2499 def min(self, other, context=None):
2500 """Returns the smaller value.
2501
Facundo Batista59c58842007-04-10 12:58:45 +00002502 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002503 NaN (and signals if one is sNaN). Also rounds.
2504 """
Facundo Batista353750c2007-09-13 18:13:15 +00002505 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002506
Facundo Batista6c398da2007-09-17 17:30:13 +00002507 if context is None:
2508 context = getcontext()
2509
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002510 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002511 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002512 # number is always returned
2513 sn = self._isnan()
2514 on = other._isnan()
2515 if sn or on:
2516 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002517 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002518 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002519 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002520 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002521
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002522 c = self.__cmp__(other)
2523 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002524 c = self.compare_total(other)
2525
2526 if c == -1:
2527 ans = self
2528 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002529 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002530
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002531 if context._rounding_decision == ALWAYS_ROUND:
2532 return ans._fix(context)
2533 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002534
2535 def _isinteger(self):
2536 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002537 if self._is_special:
2538 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002539 if self._exp >= 0:
2540 return True
2541 rest = self._int[self._exp:]
2542 return rest == (0,)*len(rest)
2543
2544 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002545 """Returns True if self is even. Assumes self is an integer."""
2546 if not self or self._exp > 0:
2547 return True
Raymond Hettinger61992ef2004-08-06 23:42:16 +00002548 return self._int[-1+self._exp] & 1 == 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002549
2550 def adjusted(self):
2551 """Return the adjusted exponent of self"""
2552 try:
2553 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002554 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002555 except TypeError:
2556 return 0
2557
Facundo Batista353750c2007-09-13 18:13:15 +00002558 def canonical(self, context=None):
2559 """Returns the same Decimal object.
2560
2561 As we do not have different encodings for the same number, the
2562 received object already is in its canonical form.
2563 """
2564 return self
2565
2566 def compare_signal(self, other, context=None):
2567 """Compares self to the other operand numerically.
2568
2569 It's pretty much like compare(), but all NaNs signal, with signaling
2570 NaNs taking precedence over quiet NaNs.
2571 """
2572 if context is None:
2573 context = getcontext()
2574
2575 self_is_nan = self._isnan()
2576 other_is_nan = other._isnan()
2577 if self_is_nan == 2:
2578 return context._raise_error(InvalidOperation, 'sNaN',
2579 1, self)
2580 if other_is_nan == 2:
2581 return context._raise_error(InvalidOperation, 'sNaN',
2582 1, other)
2583 if self_is_nan:
2584 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2585 1, self)
2586 if other_is_nan:
2587 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2588 1, other)
2589 return self.compare(other, context=context)
2590
2591 def compare_total(self, other):
2592 """Compares self to other using the abstract representations.
2593
2594 This is not like the standard compare, which use their numerical
2595 value. Note that a total ordering is defined for all possible abstract
2596 representations.
2597 """
2598 # if one is negative and the other is positive, it's easy
2599 if self._sign and not other._sign:
2600 return Dec_n1
2601 if not self._sign and other._sign:
2602 return Dec_p1
2603 sign = self._sign
2604
2605 # let's handle both NaN types
2606 self_nan = self._isnan()
2607 other_nan = other._isnan()
2608 if self_nan or other_nan:
2609 if self_nan == other_nan:
2610 if self._int < other._int:
2611 if sign:
2612 return Dec_p1
2613 else:
2614 return Dec_n1
2615 if self._int > other._int:
2616 if sign:
2617 return Dec_n1
2618 else:
2619 return Dec_p1
2620 return Dec_0
2621
2622 if sign:
2623 if self_nan == 1:
2624 return Dec_n1
2625 if other_nan == 1:
2626 return Dec_p1
2627 if self_nan == 2:
2628 return Dec_n1
2629 if other_nan == 2:
2630 return Dec_p1
2631 else:
2632 if self_nan == 1:
2633 return Dec_p1
2634 if other_nan == 1:
2635 return Dec_n1
2636 if self_nan == 2:
2637 return Dec_p1
2638 if other_nan == 2:
2639 return Dec_n1
2640
2641 if self < other:
2642 return Dec_n1
2643 if self > other:
2644 return Dec_p1
2645
2646 if self._exp < other._exp:
2647 if sign:
2648 return Dec_p1
2649 else:
2650 return Dec_n1
2651 if self._exp > other._exp:
2652 if sign:
2653 return Dec_n1
2654 else:
2655 return Dec_p1
2656 return Dec_0
2657
2658
2659 def compare_total_mag(self, other):
2660 """Compares self to other using abstract repr., ignoring sign.
2661
2662 Like compare_total, but with operand's sign ignored and assumed to be 0.
2663 """
2664 s = self.copy_abs()
2665 o = other.copy_abs()
2666 return s.compare_total(o)
2667
2668 def copy_abs(self):
2669 """Returns a copy with the sign set to 0. """
2670 return Decimal((0, self._int, self._exp))
2671
2672 def copy_negate(self):
2673 """Returns a copy with the sign inverted."""
2674 if self._sign:
2675 return Decimal((0, self._int, self._exp))
2676 else:
2677 return Decimal((1, self._int, self._exp))
2678
2679 def copy_sign(self, other):
2680 """Returns self with the sign of other."""
2681 return Decimal((other._sign, self._int, self._exp))
2682
2683 def exp(self, context=None):
2684 """Returns e ** self."""
2685
2686 if context is None:
2687 context = getcontext()
2688
2689 # exp(NaN) = NaN
2690 ans = self._check_nans(context=context)
2691 if ans:
2692 return ans
2693
2694 # exp(-Infinity) = 0
2695 if self._isinfinity() == -1:
2696 return Dec_0
2697
2698 # exp(0) = 1
2699 if not self:
2700 return Dec_p1
2701
2702 # exp(Infinity) = Infinity
2703 if self._isinfinity() == 1:
2704 return Decimal(self)
2705
2706 # the result is now guaranteed to be inexact (the true
2707 # mathematical result is transcendental). There's no need to
2708 # raise Rounded and Inexact here---they'll always be raised as
2709 # a result of the call to _fix.
2710 p = context.prec
2711 adj = self.adjusted()
2712
2713 # we only need to do any computation for quite a small range
2714 # of adjusted exponents---for example, -29 <= adj <= 10 for
2715 # the default context. For smaller exponent the result is
2716 # indistinguishable from 1 at the given precision, while for
2717 # larger exponent the result either overflows or underflows.
2718 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2719 # overflow
2720 ans = Decimal((0, (1,), context.Emax+1))
2721 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2722 # underflow to 0
2723 ans = Decimal((0, (1,), context.Etiny()-1))
2724 elif self._sign == 0 and adj < -p:
2725 # p+1 digits; final round will raise correct flags
2726 ans = Decimal((0, (1,) + (0,)*(p-1) + (1,), -p))
2727 elif self._sign == 1 and adj < -p-1:
2728 # p+1 digits; final round will raise correct flags
2729 ans = Decimal((0, (9,)*(p+1), -p-1))
2730 # general case
2731 else:
2732 op = _WorkRep(self)
2733 c, e = op.int, op.exp
2734 if op.sign == 1:
2735 c = -c
2736
2737 # compute correctly rounded result: increase precision by
2738 # 3 digits at a time until we get an unambiguously
2739 # roundable result
2740 extra = 3
2741 while True:
2742 coeff, exp = _dexp(c, e, p+extra)
2743 if coeff % (5*10**(len(str(coeff))-p-1)):
2744 break
2745 extra += 3
2746
2747 ans = Decimal((0, map(int, str(coeff)), exp))
2748
2749 # at this stage, ans should round correctly with *any*
2750 # rounding mode, not just with ROUND_HALF_EVEN
2751 context = context._shallow_copy()
2752 rounding = context._set_rounding(ROUND_HALF_EVEN)
2753 ans = ans._fix(context)
2754 context.rounding = rounding
2755
2756 return ans
2757
2758 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002759 """Return True if self is canonical; otherwise return False.
2760
2761 Currently, the encoding of a Decimal instance is always
2762 canonical, so this method returns True for any Decimal.
2763 """
2764 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002765
2766 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002767 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002768
Facundo Batista1a191df2007-10-02 17:01:24 +00002769 A Decimal instance is considered finite if it is neither
2770 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002771 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002772 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002773
2774 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002775 """Return True if self is infinite; otherwise return False."""
2776 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002777
2778 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002779 """Return True if self is a qNaN or sNaN; otherwise return False."""
2780 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002781
2782 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002783 """Return True if self is a normal number; otherwise return False."""
2784 if self._is_special or not self:
2785 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002786 if context is None:
2787 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002788 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002789
2790 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002791 """Return True if self is a quiet NaN; otherwise return False."""
2792 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002793
2794 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002795 """Return True if self is negative; otherwise return False."""
2796 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002797
2798 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002799 """Return True if self is a signaling NaN; otherwise return False."""
2800 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002801
2802 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002803 """Return True if self is subnormal; otherwise return False."""
2804 if self._is_special or not self:
2805 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002806 if context is None:
2807 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002808 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002809
2810 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002811 """Return True if self is a zero; otherwise return False."""
2812 return not self._is_special and self._int[0] == 0
Facundo Batista353750c2007-09-13 18:13:15 +00002813
2814 def _ln_exp_bound(self):
2815 """Compute a lower bound for the adjusted exponent of self.ln().
2816 In other words, compute r such that self.ln() >= 10**r. Assumes
2817 that self is finite and positive and that self != 1.
2818 """
2819
2820 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2821 adj = self._exp + len(self._int) - 1
2822 if adj >= 1:
2823 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2824 return len(str(adj*23//10)) - 1
2825 if adj <= -2:
2826 # argument <= 0.1
2827 return len(str((-1-adj)*23//10)) - 1
2828 op = _WorkRep(self)
2829 c, e = op.int, op.exp
2830 if adj == 0:
2831 # 1 < self < 10
2832 num = str(c-10**-e)
2833 den = str(c)
2834 return len(num) - len(den) - (num < den)
2835 # adj == -1, 0.1 <= self < 1
2836 return e + len(str(10**-e - c)) - 1
2837
2838
2839 def ln(self, context=None):
2840 """Returns the natural (base e) logarithm of self."""
2841
2842 if context is None:
2843 context = getcontext()
2844
2845 # ln(NaN) = NaN
2846 ans = self._check_nans(context=context)
2847 if ans:
2848 return ans
2849
2850 # ln(0.0) == -Infinity
2851 if not self:
2852 return negInf
2853
2854 # ln(Infinity) = Infinity
2855 if self._isinfinity() == 1:
2856 return Inf
2857
2858 # ln(1.0) == 0.0
2859 if self == Dec_p1:
2860 return Dec_0
2861
2862 # ln(negative) raises InvalidOperation
2863 if self._sign == 1:
2864 return context._raise_error(InvalidOperation,
2865 'ln of a negative value')
2866
2867 # result is irrational, so necessarily inexact
2868 op = _WorkRep(self)
2869 c, e = op.int, op.exp
2870 p = context.prec
2871
2872 # correctly rounded result: repeatedly increase precision by 3
2873 # until we get an unambiguously roundable result
2874 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2875 while True:
2876 coeff = _dlog(c, e, places)
2877 # assert len(str(abs(coeff)))-p >= 1
2878 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2879 break
2880 places += 3
2881 ans = Decimal((int(coeff<0), map(int, str(abs(coeff))), -places))
2882
2883 context = context._shallow_copy()
2884 rounding = context._set_rounding(ROUND_HALF_EVEN)
2885 ans = ans._fix(context)
2886 context.rounding = rounding
2887 return ans
2888
2889 def _log10_exp_bound(self):
2890 """Compute a lower bound for the adjusted exponent of self.log10().
2891 In other words, find r such that self.log10() >= 10**r.
2892 Assumes that self is finite and positive and that self != 1.
2893 """
2894
2895 # For x >= 10 or x < 0.1 we only need a bound on the integer
2896 # part of log10(self), and this comes directly from the
2897 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2898 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2899 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2900
2901 adj = self._exp + len(self._int) - 1
2902 if adj >= 1:
2903 # self >= 10
2904 return len(str(adj))-1
2905 if adj <= -2:
2906 # self < 0.1
2907 return len(str(-1-adj))-1
2908 op = _WorkRep(self)
2909 c, e = op.int, op.exp
2910 if adj == 0:
2911 # 1 < self < 10
2912 num = str(c-10**-e)
2913 den = str(231*c)
2914 return len(num) - len(den) - (num < den) + 2
2915 # adj == -1, 0.1 <= self < 1
2916 num = str(10**-e-c)
2917 return len(num) + e - (num < "231") - 1
2918
2919 def log10(self, context=None):
2920 """Returns the base 10 logarithm of self."""
2921
2922 if context is None:
2923 context = getcontext()
2924
2925 # log10(NaN) = NaN
2926 ans = self._check_nans(context=context)
2927 if ans:
2928 return ans
2929
2930 # log10(0.0) == -Infinity
2931 if not self:
2932 return negInf
2933
2934 # log10(Infinity) = Infinity
2935 if self._isinfinity() == 1:
2936 return Inf
2937
2938 # log10(negative or -Infinity) raises InvalidOperation
2939 if self._sign == 1:
2940 return context._raise_error(InvalidOperation,
2941 'log10 of a negative value')
2942
2943 # log10(10**n) = n
2944 if self._int[0] == 1 and self._int[1:] == (0,)*(len(self._int) - 1):
2945 # answer may need rounding
2946 ans = Decimal(self._exp + len(self._int) - 1)
2947 else:
2948 # result is irrational, so necessarily inexact
2949 op = _WorkRep(self)
2950 c, e = op.int, op.exp
2951 p = context.prec
2952
2953 # correctly rounded result: repeatedly increase precision
2954 # until result is unambiguously roundable
2955 places = p-self._log10_exp_bound()+2
2956 while True:
2957 coeff = _dlog10(c, e, places)
2958 # assert len(str(abs(coeff)))-p >= 1
2959 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2960 break
2961 places += 3
2962 ans = Decimal((int(coeff<0), map(int, str(abs(coeff))), -places))
2963
2964 context = context._shallow_copy()
2965 rounding = context._set_rounding(ROUND_HALF_EVEN)
2966 ans = ans._fix(context)
2967 context.rounding = rounding
2968 return ans
2969
2970 def logb(self, context=None):
2971 """ Returns the exponent of the magnitude of self's MSD.
2972
2973 The result is the integer which is the exponent of the magnitude
2974 of the most significant digit of self (as though it were truncated
2975 to a single digit while maintaining the value of that digit and
2976 without limiting the resulting exponent).
2977 """
2978 # logb(NaN) = NaN
2979 ans = self._check_nans(context=context)
2980 if ans:
2981 return ans
2982
2983 if context is None:
2984 context = getcontext()
2985
2986 # logb(+/-Inf) = +Inf
2987 if self._isinfinity():
2988 return Inf
2989
2990 # logb(0) = -Inf, DivisionByZero
2991 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00002992 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00002993
2994 # otherwise, simply return the adjusted exponent of self, as a
2995 # Decimal. Note that no attempt is made to fit the result
2996 # into the current context.
2997 return Decimal(self.adjusted())
2998
2999 def _islogical(self):
3000 """Return True if self is a logical operand.
3001
3002 For being logical, it must be a finite numbers with a sign of 0,
3003 an exponent of 0, and a coefficient whose digits must all be
3004 either 0 or 1.
3005 """
3006 if self._sign != 0 or self._exp != 0:
3007 return False
3008 for dig in self._int:
3009 if dig not in (0, 1):
3010 return False
3011 return True
3012
3013 def _fill_logical(self, context, opa, opb):
3014 dif = context.prec - len(opa)
3015 if dif > 0:
3016 opa = (0,)*dif + opa
3017 elif dif < 0:
3018 opa = opa[-context.prec:]
3019 dif = context.prec - len(opb)
3020 if dif > 0:
3021 opb = (0,)*dif + opb
3022 elif dif < 0:
3023 opb = opb[-context.prec:]
3024 return opa, opb
3025
3026 def logical_and(self, other, context=None):
3027 """Applies an 'and' operation between self and other's digits."""
3028 if context is None:
3029 context = getcontext()
3030 if not self._islogical() or not other._islogical():
3031 return context._raise_error(InvalidOperation)
3032
3033 # fill to context.prec
3034 (opa, opb) = self._fill_logical(context, self._int, other._int)
3035
3036 # make the operation, and clean starting zeroes
3037 result = [a&b for a,b in zip(opa,opb)]
3038 for i,d in enumerate(result):
3039 if d == 1:
3040 break
3041 result = tuple(result[i:])
3042
3043 # if empty, we must have at least a zero
3044 if not result:
3045 result = (0,)
3046 return Decimal((0, result, 0))
3047
3048 def logical_invert(self, context=None):
3049 """Invert all its digits."""
3050 if context is None:
3051 context = getcontext()
3052 return self.logical_xor(Decimal((0,(1,)*context.prec,0)), context)
3053
3054 def logical_or(self, other, context=None):
3055 """Applies an 'or' operation between self and other's digits."""
3056 if context is None:
3057 context = getcontext()
3058 if not self._islogical() or not other._islogical():
3059 return context._raise_error(InvalidOperation)
3060
3061 # fill to context.prec
3062 (opa, opb) = self._fill_logical(context, self._int, other._int)
3063
3064 # make the operation, and clean starting zeroes
3065 result = [a|b for a,b in zip(opa,opb)]
3066 for i,d in enumerate(result):
3067 if d == 1:
3068 break
3069 result = tuple(result[i:])
3070
3071 # if empty, we must have at least a zero
3072 if not result:
3073 result = (0,)
3074 return Decimal((0, result, 0))
3075
3076 def logical_xor(self, other, context=None):
3077 """Applies an 'xor' operation between self and other's digits."""
3078 if context is None:
3079 context = getcontext()
3080 if not self._islogical() or not other._islogical():
3081 return context._raise_error(InvalidOperation)
3082
3083 # fill to context.prec
3084 (opa, opb) = self._fill_logical(context, self._int, other._int)
3085
3086 # make the operation, and clean starting zeroes
3087 result = [a^b for a,b in zip(opa,opb)]
3088 for i,d in enumerate(result):
3089 if d == 1:
3090 break
3091 result = tuple(result[i:])
3092
3093 # if empty, we must have at least a zero
3094 if not result:
3095 result = (0,)
3096 return Decimal((0, result, 0))
3097
3098 def max_mag(self, other, context=None):
3099 """Compares the values numerically with their sign ignored."""
3100 other = _convert_other(other, raiseit=True)
3101
Facundo Batista6c398da2007-09-17 17:30:13 +00003102 if context is None:
3103 context = getcontext()
3104
Facundo Batista353750c2007-09-13 18:13:15 +00003105 if self._is_special or other._is_special:
3106 # If one operand is a quiet NaN and the other is number, then the
3107 # number is always returned
3108 sn = self._isnan()
3109 on = other._isnan()
3110 if sn or on:
3111 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003112 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003113 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003114 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003115 return self._check_nans(other, context)
3116
3117 c = self.copy_abs().__cmp__(other.copy_abs())
3118 if c == 0:
3119 c = self.compare_total(other)
3120
3121 if c == -1:
3122 ans = other
3123 else:
3124 ans = self
3125
Facundo Batista353750c2007-09-13 18:13:15 +00003126 if context._rounding_decision == ALWAYS_ROUND:
3127 return ans._fix(context)
3128 return ans
3129
3130 def min_mag(self, other, context=None):
3131 """Compares the values numerically with their sign ignored."""
3132 other = _convert_other(other, raiseit=True)
3133
Facundo Batista6c398da2007-09-17 17:30:13 +00003134 if context is None:
3135 context = getcontext()
3136
Facundo Batista353750c2007-09-13 18:13:15 +00003137 if self._is_special or other._is_special:
3138 # If one operand is a quiet NaN and the other is number, then the
3139 # number is always returned
3140 sn = self._isnan()
3141 on = other._isnan()
3142 if sn or on:
3143 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003144 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003145 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003146 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003147 return self._check_nans(other, context)
3148
3149 c = self.copy_abs().__cmp__(other.copy_abs())
3150 if c == 0:
3151 c = self.compare_total(other)
3152
3153 if c == -1:
3154 ans = self
3155 else:
3156 ans = other
3157
Facundo Batista353750c2007-09-13 18:13:15 +00003158 if context._rounding_decision == ALWAYS_ROUND:
3159 return ans._fix(context)
3160 return ans
3161
3162 def next_minus(self, context=None):
3163 """Returns the largest representable number smaller than itself."""
3164 if context is None:
3165 context = getcontext()
3166
3167 ans = self._check_nans(context=context)
3168 if ans:
3169 return ans
3170
3171 if self._isinfinity() == -1:
3172 return negInf
3173 if self._isinfinity() == 1:
3174 return Decimal((0, (9,)*context.prec, context.Etop()))
3175
3176 context = context.copy()
3177 context._set_rounding(ROUND_FLOOR)
3178 context._ignore_all_flags()
3179 new_self = self._fix(context)
3180 if new_self != self:
3181 return new_self
3182 return self.__sub__(Decimal((0, (1,), context.Etiny()-1)), context)
3183
3184 def next_plus(self, context=None):
3185 """Returns the smallest representable number larger than itself."""
3186 if context is None:
3187 context = getcontext()
3188
3189 ans = self._check_nans(context=context)
3190 if ans:
3191 return ans
3192
3193 if self._isinfinity() == 1:
3194 return Inf
3195 if self._isinfinity() == -1:
3196 return Decimal((1, (9,)*context.prec, context.Etop()))
3197
3198 context = context.copy()
3199 context._set_rounding(ROUND_CEILING)
3200 context._ignore_all_flags()
3201 new_self = self._fix(context)
3202 if new_self != self:
3203 return new_self
3204 return self.__add__(Decimal((0, (1,), context.Etiny()-1)), context)
3205
3206 def next_toward(self, other, context=None):
3207 """Returns the number closest to self, in the direction towards other.
3208
3209 The result is the closest representable number to self
3210 (excluding self) that is in the direction towards other,
3211 unless both have the same value. If the two operands are
3212 numerically equal, then the result is a copy of self with the
3213 sign set to be the same as the sign of other.
3214 """
3215 other = _convert_other(other, raiseit=True)
3216
3217 if context is None:
3218 context = getcontext()
3219
3220 ans = self._check_nans(other, context)
3221 if ans:
3222 return ans
3223
3224 comparison = self.__cmp__(other)
3225 if comparison == 0:
3226 return Decimal((other._sign, self._int, self._exp))
3227
3228 if comparison == -1:
3229 ans = self.next_plus(context)
3230 else: # comparison == 1
3231 ans = self.next_minus(context)
3232
3233 # decide which flags to raise using value of ans
3234 if ans._isinfinity():
3235 context._raise_error(Overflow,
3236 'Infinite result from next_toward',
3237 ans._sign)
3238 context._raise_error(Rounded)
3239 context._raise_error(Inexact)
3240 elif ans.adjusted() < context.Emin:
3241 context._raise_error(Underflow)
3242 context._raise_error(Subnormal)
3243 context._raise_error(Rounded)
3244 context._raise_error(Inexact)
3245 # if precision == 1 then we don't raise Clamped for a
3246 # result 0E-Etiny.
3247 if not ans:
3248 context._raise_error(Clamped)
3249
3250 return ans
3251
3252 def number_class(self, context=None):
3253 """Returns an indication of the class of self.
3254
3255 The class is one of the following strings:
3256 -sNaN
3257 -NaN
3258 -Infinity
3259 -Normal
3260 -Subnormal
3261 -Zero
3262 +Zero
3263 +Subnormal
3264 +Normal
3265 +Infinity
3266 """
3267 if self.is_snan():
3268 return "sNaN"
3269 if self.is_qnan():
3270 return "NaN"
3271 inf = self._isinfinity()
3272 if inf == 1:
3273 return "+Infinity"
3274 if inf == -1:
3275 return "-Infinity"
3276 if self.is_zero():
3277 if self._sign:
3278 return "-Zero"
3279 else:
3280 return "+Zero"
3281 if context is None:
3282 context = getcontext()
3283 if self.is_subnormal(context=context):
3284 if self._sign:
3285 return "-Subnormal"
3286 else:
3287 return "+Subnormal"
3288 # just a normal, regular, boring number, :)
3289 if self._sign:
3290 return "-Normal"
3291 else:
3292 return "+Normal"
3293
3294 def radix(self):
3295 """Just returns 10, as this is Decimal, :)"""
3296 return Decimal(10)
3297
3298 def rotate(self, other, context=None):
3299 """Returns a rotated copy of self, value-of-other times."""
3300 if context is None:
3301 context = getcontext()
3302
3303 ans = self._check_nans(other, context)
3304 if ans:
3305 return ans
3306
3307 if other._exp != 0:
3308 return context._raise_error(InvalidOperation)
3309 if not (-context.prec <= int(other) <= context.prec):
3310 return context._raise_error(InvalidOperation)
3311
3312 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003313 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003314
3315 # get values, pad if necessary
3316 torot = int(other)
3317 rotdig = self._int
3318 topad = context.prec - len(rotdig)
3319 if topad:
3320 rotdig = ((0,)*topad) + rotdig
3321
3322 # let's rotate!
3323 rotated = rotdig[torot:] + rotdig[:torot]
3324
3325 # clean starting zeroes
3326 for i,d in enumerate(rotated):
3327 if d != 0:
3328 break
3329 rotated = rotated[i:]
3330
3331 return Decimal((self._sign, rotated, self._exp))
3332
3333
3334 def scaleb (self, other, context=None):
3335 """Returns self operand after adding the second value to its exp."""
3336 if context is None:
3337 context = getcontext()
3338
3339 ans = self._check_nans(other, context)
3340 if ans:
3341 return ans
3342
3343 if other._exp != 0:
3344 return context._raise_error(InvalidOperation)
3345 liminf = -2 * (context.Emax + context.prec)
3346 limsup = 2 * (context.Emax + context.prec)
3347 if not (liminf <= int(other) <= limsup):
3348 return context._raise_error(InvalidOperation)
3349
3350 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003351 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003352
3353 d = Decimal((self._sign, self._int, self._exp + int(other)))
3354 d = d._fix(context)
3355 return d
3356
3357 def shift(self, other, context=None):
3358 """Returns a shifted copy of self, value-of-other times."""
3359 if context is None:
3360 context = getcontext()
3361
3362 ans = self._check_nans(other, context)
3363 if ans:
3364 return ans
3365
3366 if other._exp != 0:
3367 return context._raise_error(InvalidOperation)
3368 if not (-context.prec <= int(other) <= context.prec):
3369 return context._raise_error(InvalidOperation)
3370
3371 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003372 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003373
3374 # get values, pad if necessary
3375 torot = int(other)
3376 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003377 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003378 rotdig = self._int
3379 topad = context.prec - len(rotdig)
3380 if topad:
3381 rotdig = ((0,)*topad) + rotdig
3382
3383 # let's shift!
3384 if torot < 0:
3385 rotated = rotdig[:torot]
3386 else:
3387 rotated = (rotdig + ((0,) * torot))
3388 rotated = rotated[-context.prec:]
3389
3390 # clean starting zeroes
3391 if rotated:
3392 for i,d in enumerate(rotated):
3393 if d != 0:
3394 break
3395 rotated = rotated[i:]
3396 else:
3397 rotated = (0,)
3398
3399 return Decimal((self._sign, rotated, self._exp))
3400
3401
Facundo Batista59c58842007-04-10 12:58:45 +00003402 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003403 def __reduce__(self):
3404 return (self.__class__, (str(self),))
3405
3406 def __copy__(self):
3407 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003408 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003409 return self.__class__(str(self))
3410
3411 def __deepcopy__(self, memo):
3412 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003413 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003414 return self.__class__(str(self))
3415
Facundo Batista59c58842007-04-10 12:58:45 +00003416##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003417
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003418
3419# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003420rounding_functions = [name for name in Decimal.__dict__.keys()
3421 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003422for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003423 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003424 globalname = name[1:].upper()
3425 val = globals()[globalname]
3426 Decimal._pick_rounding_function[val] = name
3427
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003428del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003429
Nick Coghlanced12182006-09-02 03:54:17 +00003430class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003431 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003432
Nick Coghlanced12182006-09-02 03:54:17 +00003433 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003434 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003435 """
3436 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003437 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003438 def __enter__(self):
3439 self.saved_context = getcontext()
3440 setcontext(self.new_context)
3441 return self.new_context
3442 def __exit__(self, t, v, tb):
3443 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003444
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003445class Context(object):
3446 """Contains the context for a Decimal instance.
3447
3448 Contains:
3449 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003450 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003451 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003452 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003453 raised when it is caused. Otherwise, a value is
3454 substituted in.
3455 flags - When an exception is caused, flags[exception] is incremented.
3456 (Whether or not the trap_enabler is set)
3457 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003458 Emin - Minimum exponent
3459 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003460 capitals - If 1, 1*10^1 is printed as 1E+1.
3461 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003462 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003463 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003464
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003465 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003466 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003467 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003468 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003469 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003470 _ignored_flags=None):
3471 if flags is None:
3472 flags = []
3473 if _ignored_flags is None:
3474 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003475 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003476 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003477 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003478 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003479 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003480 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003481 for name, val in locals().items():
3482 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003483 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003484 else:
3485 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003486 del self.self
3487
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003488 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003489 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003490 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003491 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3492 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3493 % vars(self))
3494 names = [f.__name__ for f, v in self.flags.items() if v]
3495 s.append('flags=[' + ', '.join(names) + ']')
3496 names = [t.__name__ for t, v in self.traps.items() if v]
3497 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003498 return ', '.join(s) + ')'
3499
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003500 def clear_flags(self):
3501 """Reset all flags to zero"""
3502 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003503 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003504
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003505 def _shallow_copy(self):
3506 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003507 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003508 self._rounding_decision, self.Emin, self.Emax,
3509 self.capitals, self._clamp, self._ignored_flags)
3510 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003511
3512 def copy(self):
3513 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003514 nc = Context(self.prec, self.rounding, self.traps.copy(),
3515 self.flags.copy(), self._rounding_decision, self.Emin,
3516 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003517 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003518 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003519
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003520 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003521 """Handles an error
3522
3523 If the flag is in _ignored_flags, returns the default response.
3524 Otherwise, it increments the flag, then, if the corresponding
3525 trap_enabler is set, it reaises the exception. Otherwise, it returns
3526 the default value after incrementing the flag.
3527 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003528 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003529 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003530 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003531 return error().handle(self, *args)
3532
3533 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003534 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003535 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003536 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003537
3538 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003539 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003540 raise error, explanation
3541
3542 def _ignore_all_flags(self):
3543 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003544 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003545
3546 def _ignore_flags(self, *flags):
3547 """Ignore the flags, if they are raised"""
3548 # Do not mutate-- This way, copies of a context leave the original
3549 # alone.
3550 self._ignored_flags = (self._ignored_flags + list(flags))
3551 return list(flags)
3552
3553 def _regard_flags(self, *flags):
3554 """Stop ignoring the flags, if they are raised"""
3555 if flags and isinstance(flags[0], (tuple,list)):
3556 flags = flags[0]
3557 for flag in flags:
3558 self._ignored_flags.remove(flag)
3559
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003560 def __hash__(self):
3561 """A Context cannot be hashed."""
3562 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003563 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003564
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003565 def Etiny(self):
3566 """Returns Etiny (= Emin - prec + 1)"""
3567 return int(self.Emin - self.prec + 1)
3568
3569 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003570 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003571 return int(self.Emax - self.prec + 1)
3572
3573 def _set_rounding_decision(self, type):
3574 """Sets the rounding decision.
3575
3576 Sets the rounding decision, and returns the current (previous)
3577 rounding decision. Often used like:
3578
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003579 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003580 # That so you don't change the calling context
3581 # if an error occurs in the middle (say DivisionImpossible is raised).
3582
3583 rounding = context._set_rounding_decision(NEVER_ROUND)
3584 instance = instance / Decimal(2)
3585 context._set_rounding_decision(rounding)
3586
3587 This will make it not round for that operation.
3588 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003589
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003590 rounding = self._rounding_decision
3591 self._rounding_decision = type
3592 return rounding
3593
3594 def _set_rounding(self, type):
3595 """Sets the rounding type.
3596
3597 Sets the rounding type, and returns the current (previous)
3598 rounding type. Often used like:
3599
3600 context = context.copy()
3601 # so you don't change the calling context
3602 # if an error occurs in the middle.
3603 rounding = context._set_rounding(ROUND_UP)
3604 val = self.__sub__(other, context=context)
3605 context._set_rounding(rounding)
3606
3607 This will make it round up for that operation.
3608 """
3609 rounding = self.rounding
3610 self.rounding= type
3611 return rounding
3612
Raymond Hettingerfed52962004-07-14 15:41:57 +00003613 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003614 """Creates a new Decimal instance but using self as context."""
3615 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003616 if d._isnan() and len(d._int) > self.prec - self._clamp:
3617 return self._raise_error(ConversionSyntax,
3618 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003619 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003620
Facundo Batista59c58842007-04-10 12:58:45 +00003621 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003622 def abs(self, a):
3623 """Returns the absolute value of the operand.
3624
3625 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003626 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003627 the plus operation on the operand.
3628
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003629 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003630 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003631 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003632 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003633 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003634 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003635 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003636 Decimal("101.5")
3637 """
3638 return a.__abs__(context=self)
3639
3640 def add(self, a, b):
3641 """Return the sum of the two operands.
3642
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003643 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003644 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003645 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003646 Decimal("1.02E+4")
3647 """
3648 return a.__add__(b, context=self)
3649
3650 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003651 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003652
Facundo Batista353750c2007-09-13 18:13:15 +00003653 def canonical(self, a):
3654 """Returns the same Decimal object.
3655
3656 As we do not have different encodings for the same number, the
3657 received object already is in its canonical form.
3658
3659 >>> ExtendedContext.canonical(Decimal('2.50'))
3660 Decimal("2.50")
3661 """
3662 return a.canonical(context=self)
3663
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003664 def compare(self, a, b):
3665 """Compares values numerically.
3666
3667 If the signs of the operands differ, a value representing each operand
3668 ('-1' if the operand is less than zero, '0' if the operand is zero or
3669 negative zero, or '1' if the operand is greater than zero) is used in
3670 place of that operand for the comparison instead of the actual
3671 operand.
3672
3673 The comparison is then effected by subtracting the second operand from
3674 the first and then returning a value according to the result of the
3675 subtraction: '-1' if the result is less than zero, '0' if the result is
3676 zero or negative zero, or '1' if the result is greater than zero.
3677
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003678 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003679 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003680 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003681 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003682 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003683 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003684 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003685 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003686 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003687 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003688 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003689 Decimal("-1")
3690 """
3691 return a.compare(b, context=self)
3692
Facundo Batista353750c2007-09-13 18:13:15 +00003693 def compare_signal(self, a, b):
3694 """Compares the values of the two operands numerically.
3695
3696 It's pretty much like compare(), but all NaNs signal, with signaling
3697 NaNs taking precedence over quiet NaNs.
3698
3699 >>> c = ExtendedContext
3700 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3701 Decimal("-1")
3702 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3703 Decimal("0")
3704 >>> c.flags[InvalidOperation] = 0
3705 >>> print c.flags[InvalidOperation]
3706 0
3707 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3708 Decimal("NaN")
3709 >>> print c.flags[InvalidOperation]
3710 1
3711 >>> c.flags[InvalidOperation] = 0
3712 >>> print c.flags[InvalidOperation]
3713 0
3714 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3715 Decimal("NaN")
3716 >>> print c.flags[InvalidOperation]
3717 1
3718 """
3719 return a.compare_signal(b, context=self)
3720
3721 def compare_total(self, a, b):
3722 """Compares two operands using their abstract representation.
3723
3724 This is not like the standard compare, which use their numerical
3725 value. Note that a total ordering is defined for all possible abstract
3726 representations.
3727
3728 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3729 Decimal("-1")
3730 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3731 Decimal("-1")
3732 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3733 Decimal("-1")
3734 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3735 Decimal("0")
3736 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3737 Decimal("1")
3738 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3739 Decimal("-1")
3740 """
3741 return a.compare_total(b)
3742
3743 def compare_total_mag(self, a, b):
3744 """Compares two operands using their abstract representation ignoring sign.
3745
3746 Like compare_total, but with operand's sign ignored and assumed to be 0.
3747 """
3748 return a.compare_total_mag(b)
3749
3750 def copy_abs(self, a):
3751 """Returns a copy of the operand with the sign set to 0.
3752
3753 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3754 Decimal("2.1")
3755 >>> ExtendedContext.copy_abs(Decimal('-100'))
3756 Decimal("100")
3757 """
3758 return a.copy_abs()
3759
3760 def copy_decimal(self, a):
3761 """Returns a copy of the decimal objet.
3762
3763 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3764 Decimal("2.1")
3765 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3766 Decimal("-1.00")
3767 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003768 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003769
3770 def copy_negate(self, a):
3771 """Returns a copy of the operand with the sign inverted.
3772
3773 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3774 Decimal("-101.5")
3775 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3776 Decimal("101.5")
3777 """
3778 return a.copy_negate()
3779
3780 def copy_sign(self, a, b):
3781 """Copies the second operand's sign to the first one.
3782
3783 In detail, it returns a copy of the first operand with the sign
3784 equal to the sign of the second operand.
3785
3786 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3787 Decimal("1.50")
3788 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3789 Decimal("1.50")
3790 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3791 Decimal("-1.50")
3792 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3793 Decimal("-1.50")
3794 """
3795 return a.copy_sign(b)
3796
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003797 def divide(self, a, b):
3798 """Decimal division in a specified context.
3799
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003800 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003801 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003802 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003803 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003804 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003805 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003806 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003807 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003808 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003809 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003810 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003811 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003812 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003813 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003814 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003815 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003816 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003817 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003818 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003819 Decimal("1.20E+6")
3820 """
3821 return a.__div__(b, context=self)
3822
3823 def divide_int(self, a, b):
3824 """Divides two numbers and returns the integer part of the result.
3825
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003826 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003827 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003828 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003829 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003830 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003831 Decimal("3")
3832 """
3833 return a.__floordiv__(b, context=self)
3834
3835 def divmod(self, a, b):
3836 return a.__divmod__(b, context=self)
3837
Facundo Batista353750c2007-09-13 18:13:15 +00003838 def exp(self, a):
3839 """Returns e ** a.
3840
3841 >>> c = ExtendedContext.copy()
3842 >>> c.Emin = -999
3843 >>> c.Emax = 999
3844 >>> c.exp(Decimal('-Infinity'))
3845 Decimal("0")
3846 >>> c.exp(Decimal('-1'))
3847 Decimal("0.367879441")
3848 >>> c.exp(Decimal('0'))
3849 Decimal("1")
3850 >>> c.exp(Decimal('1'))
3851 Decimal("2.71828183")
3852 >>> c.exp(Decimal('0.693147181'))
3853 Decimal("2.00000000")
3854 >>> c.exp(Decimal('+Infinity'))
3855 Decimal("Infinity")
3856 """
3857 return a.exp(context=self)
3858
3859 def fma(self, a, b, c):
3860 """Returns a multiplied by b, plus c.
3861
3862 The first two operands are multiplied together, using multiply,
3863 the third operand is then added to the result of that
3864 multiplication, using add, all with only one final rounding.
3865
3866 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3867 Decimal("22")
3868 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3869 Decimal("-8")
3870 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3871 Decimal("1.38435736E+12")
3872 """
3873 return a.fma(b, c, context=self)
3874
3875 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003876 """Return True if the operand is canonical; otherwise return False.
3877
3878 Currently, the encoding of a Decimal instance is always
3879 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00003880
3881 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003882 True
Facundo Batista353750c2007-09-13 18:13:15 +00003883 """
Facundo Batista1a191df2007-10-02 17:01:24 +00003884 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00003885
3886 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003887 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003888
Facundo Batista1a191df2007-10-02 17:01:24 +00003889 A Decimal instance is considered finite if it is neither
3890 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00003891
3892 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003893 True
Facundo Batista353750c2007-09-13 18:13:15 +00003894 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003895 True
Facundo Batista353750c2007-09-13 18:13:15 +00003896 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003897 True
Facundo Batista353750c2007-09-13 18:13:15 +00003898 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003899 False
Facundo Batista353750c2007-09-13 18:13:15 +00003900 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003901 False
Facundo Batista353750c2007-09-13 18:13:15 +00003902 """
3903 return a.is_finite()
3904
3905 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003906 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003907
3908 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003909 False
Facundo Batista353750c2007-09-13 18:13:15 +00003910 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003911 True
Facundo Batista353750c2007-09-13 18:13:15 +00003912 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003913 False
Facundo Batista353750c2007-09-13 18:13:15 +00003914 """
3915 return a.is_infinite()
3916
3917 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003918 """Return True if the operand is a qNaN or sNaN;
3919 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003920
3921 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003922 False
Facundo Batista353750c2007-09-13 18:13:15 +00003923 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003924 True
Facundo Batista353750c2007-09-13 18:13:15 +00003925 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003926 True
Facundo Batista353750c2007-09-13 18:13:15 +00003927 """
3928 return a.is_nan()
3929
3930 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003931 """Return True if the operand is a normal number;
3932 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003933
3934 >>> c = ExtendedContext.copy()
3935 >>> c.Emin = -999
3936 >>> c.Emax = 999
3937 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003938 True
Facundo Batista353750c2007-09-13 18:13:15 +00003939 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003940 False
Facundo Batista353750c2007-09-13 18:13:15 +00003941 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003942 False
Facundo Batista353750c2007-09-13 18:13:15 +00003943 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003944 False
Facundo Batista353750c2007-09-13 18:13:15 +00003945 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003946 False
Facundo Batista353750c2007-09-13 18:13:15 +00003947 """
3948 return a.is_normal(context=self)
3949
3950 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003951 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003952
3953 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003954 False
Facundo Batista353750c2007-09-13 18:13:15 +00003955 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003956 True
Facundo Batista353750c2007-09-13 18:13:15 +00003957 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003958 False
Facundo Batista353750c2007-09-13 18:13:15 +00003959 """
3960 return a.is_qnan()
3961
3962 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003963 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003964
3965 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003966 False
Facundo Batista353750c2007-09-13 18:13:15 +00003967 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003968 True
Facundo Batista353750c2007-09-13 18:13:15 +00003969 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003970 True
Facundo Batista353750c2007-09-13 18:13:15 +00003971 """
3972 return a.is_signed()
3973
3974 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003975 """Return True if the operand is a signaling NaN;
3976 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003977
3978 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003979 False
Facundo Batista353750c2007-09-13 18:13:15 +00003980 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003981 False
Facundo Batista353750c2007-09-13 18:13:15 +00003982 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003983 True
Facundo Batista353750c2007-09-13 18:13:15 +00003984 """
3985 return a.is_snan()
3986
3987 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003988 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003989
3990 >>> c = ExtendedContext.copy()
3991 >>> c.Emin = -999
3992 >>> c.Emax = 999
3993 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003994 False
Facundo Batista353750c2007-09-13 18:13:15 +00003995 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003996 True
Facundo Batista353750c2007-09-13 18:13:15 +00003997 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003998 False
Facundo Batista353750c2007-09-13 18:13:15 +00003999 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004000 False
Facundo Batista353750c2007-09-13 18:13:15 +00004001 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004002 False
Facundo Batista353750c2007-09-13 18:13:15 +00004003 """
4004 return a.is_subnormal(context=self)
4005
4006 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004007 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004008
4009 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004010 True
Facundo Batista353750c2007-09-13 18:13:15 +00004011 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004012 False
Facundo Batista353750c2007-09-13 18:13:15 +00004013 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004014 True
Facundo Batista353750c2007-09-13 18:13:15 +00004015 """
4016 return a.is_zero()
4017
4018 def ln(self, a):
4019 """Returns the natural (base e) logarithm of the operand.
4020
4021 >>> c = ExtendedContext.copy()
4022 >>> c.Emin = -999
4023 >>> c.Emax = 999
4024 >>> c.ln(Decimal('0'))
4025 Decimal("-Infinity")
4026 >>> c.ln(Decimal('1.000'))
4027 Decimal("0")
4028 >>> c.ln(Decimal('2.71828183'))
4029 Decimal("1.00000000")
4030 >>> c.ln(Decimal('10'))
4031 Decimal("2.30258509")
4032 >>> c.ln(Decimal('+Infinity'))
4033 Decimal("Infinity")
4034 """
4035 return a.ln(context=self)
4036
4037 def log10(self, a):
4038 """Returns the base 10 logarithm of the operand.
4039
4040 >>> c = ExtendedContext.copy()
4041 >>> c.Emin = -999
4042 >>> c.Emax = 999
4043 >>> c.log10(Decimal('0'))
4044 Decimal("-Infinity")
4045 >>> c.log10(Decimal('0.001'))
4046 Decimal("-3")
4047 >>> c.log10(Decimal('1.000'))
4048 Decimal("0")
4049 >>> c.log10(Decimal('2'))
4050 Decimal("0.301029996")
4051 >>> c.log10(Decimal('10'))
4052 Decimal("1")
4053 >>> c.log10(Decimal('70'))
4054 Decimal("1.84509804")
4055 >>> c.log10(Decimal('+Infinity'))
4056 Decimal("Infinity")
4057 """
4058 return a.log10(context=self)
4059
4060 def logb(self, a):
4061 """ Returns the exponent of the magnitude of the operand's MSD.
4062
4063 The result is the integer which is the exponent of the magnitude
4064 of the most significant digit of the operand (as though the
4065 operand were truncated to a single digit while maintaining the
4066 value of that digit and without limiting the resulting exponent).
4067
4068 >>> ExtendedContext.logb(Decimal('250'))
4069 Decimal("2")
4070 >>> ExtendedContext.logb(Decimal('2.50'))
4071 Decimal("0")
4072 >>> ExtendedContext.logb(Decimal('0.03'))
4073 Decimal("-2")
4074 >>> ExtendedContext.logb(Decimal('0'))
4075 Decimal("-Infinity")
4076 """
4077 return a.logb(context=self)
4078
4079 def logical_and(self, a, b):
4080 """Applies the logical operation 'and' between each operand's digits.
4081
4082 The operands must be both logical numbers.
4083
4084 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4085 Decimal("0")
4086 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4087 Decimal("0")
4088 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4089 Decimal("0")
4090 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4091 Decimal("1")
4092 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4093 Decimal("1000")
4094 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4095 Decimal("10")
4096 """
4097 return a.logical_and(b, context=self)
4098
4099 def logical_invert(self, a):
4100 """Invert all the digits in the operand.
4101
4102 The operand must be a logical number.
4103
4104 >>> ExtendedContext.logical_invert(Decimal('0'))
4105 Decimal("111111111")
4106 >>> ExtendedContext.logical_invert(Decimal('1'))
4107 Decimal("111111110")
4108 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4109 Decimal("0")
4110 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4111 Decimal("10101010")
4112 """
4113 return a.logical_invert(context=self)
4114
4115 def logical_or(self, a, b):
4116 """Applies the logical operation 'or' between each operand's digits.
4117
4118 The operands must be both logical numbers.
4119
4120 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4121 Decimal("0")
4122 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4123 Decimal("1")
4124 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4125 Decimal("1")
4126 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4127 Decimal("1")
4128 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4129 Decimal("1110")
4130 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4131 Decimal("1110")
4132 """
4133 return a.logical_or(b, context=self)
4134
4135 def logical_xor(self, a, b):
4136 """Applies the logical operation 'xor' between each operand's digits.
4137
4138 The operands must be both logical numbers.
4139
4140 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4141 Decimal("0")
4142 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4143 Decimal("1")
4144 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4145 Decimal("1")
4146 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4147 Decimal("0")
4148 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4149 Decimal("110")
4150 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4151 Decimal("1101")
4152 """
4153 return a.logical_xor(b, context=self)
4154
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004155 def max(self, a,b):
4156 """max compares two values numerically and returns the maximum.
4157
4158 If either operand is a NaN then the general rules apply.
4159 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004160 operation. If they are numerically equal then the left-hand operand
4161 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004162 infinity) of the two operands is chosen as the result.
4163
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004164 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004165 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004166 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004167 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004168 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004169 Decimal("1")
4170 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4171 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004172 """
4173 return a.max(b, context=self)
4174
Facundo Batista353750c2007-09-13 18:13:15 +00004175 def max_mag(self, a, b):
4176 """Compares the values numerically with their sign ignored."""
4177 return a.max_mag(b, context=self)
4178
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004179 def min(self, a,b):
4180 """min compares two values numerically and returns the minimum.
4181
4182 If either operand is a NaN then the general rules apply.
4183 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004184 operation. If they are numerically equal then the left-hand operand
4185 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004186 infinity) of the two operands is chosen as the result.
4187
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004188 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004189 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004190 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004191 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004192 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004193 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004194 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4195 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004196 """
4197 return a.min(b, context=self)
4198
Facundo Batista353750c2007-09-13 18:13:15 +00004199 def min_mag(self, a, b):
4200 """Compares the values numerically with their sign ignored."""
4201 return a.min_mag(b, context=self)
4202
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004203 def minus(self, a):
4204 """Minus corresponds to unary prefix minus in Python.
4205
4206 The operation is evaluated using the same rules as subtract; the
4207 operation minus(a) is calculated as subtract('0', a) where the '0'
4208 has the same exponent as the operand.
4209
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004210 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004211 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004212 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004213 Decimal("1.3")
4214 """
4215 return a.__neg__(context=self)
4216
4217 def multiply(self, a, b):
4218 """multiply multiplies two operands.
4219
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004220 If either operand is a special value then the general rules apply.
4221 Otherwise, the operands are multiplied together ('long multiplication'),
4222 resulting in a number which may be as long as the sum of the lengths
4223 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004224
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004225 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004226 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004227 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004228 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004229 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004230 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004231 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004232 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004233 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004234 Decimal("4.28135971E+11")
4235 """
4236 return a.__mul__(b, context=self)
4237
Facundo Batista353750c2007-09-13 18:13:15 +00004238 def next_minus(self, a):
4239 """Returns the largest representable number smaller than a.
4240
4241 >>> c = ExtendedContext.copy()
4242 >>> c.Emin = -999
4243 >>> c.Emax = 999
4244 >>> ExtendedContext.next_minus(Decimal('1'))
4245 Decimal("0.999999999")
4246 >>> c.next_minus(Decimal('1E-1007'))
4247 Decimal("0E-1007")
4248 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4249 Decimal("-1.00000004")
4250 >>> c.next_minus(Decimal('Infinity'))
4251 Decimal("9.99999999E+999")
4252 """
4253 return a.next_minus(context=self)
4254
4255 def next_plus(self, a):
4256 """Returns the smallest representable number larger than a.
4257
4258 >>> c = ExtendedContext.copy()
4259 >>> c.Emin = -999
4260 >>> c.Emax = 999
4261 >>> ExtendedContext.next_plus(Decimal('1'))
4262 Decimal("1.00000001")
4263 >>> c.next_plus(Decimal('-1E-1007'))
4264 Decimal("-0E-1007")
4265 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4266 Decimal("-1.00000002")
4267 >>> c.next_plus(Decimal('-Infinity'))
4268 Decimal("-9.99999999E+999")
4269 """
4270 return a.next_plus(context=self)
4271
4272 def next_toward(self, a, b):
4273 """Returns the number closest to a, in direction towards b.
4274
4275 The result is the closest representable number from the first
4276 operand (but not the first operand) that is in the direction
4277 towards the second operand, unless the operands have the same
4278 value.
4279
4280 >>> c = ExtendedContext.copy()
4281 >>> c.Emin = -999
4282 >>> c.Emax = 999
4283 >>> c.next_toward(Decimal('1'), Decimal('2'))
4284 Decimal("1.00000001")
4285 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4286 Decimal("-0E-1007")
4287 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4288 Decimal("-1.00000002")
4289 >>> c.next_toward(Decimal('1'), Decimal('0'))
4290 Decimal("0.999999999")
4291 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4292 Decimal("0E-1007")
4293 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4294 Decimal("-1.00000004")
4295 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4296 Decimal("-0.00")
4297 """
4298 return a.next_toward(b, context=self)
4299
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004300 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004301 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004302
4303 Essentially a plus operation with all trailing zeros removed from the
4304 result.
4305
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004306 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004307 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004308 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004309 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004310 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004311 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004312 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004313 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004314 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004315 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004316 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004317 Decimal("0")
4318 """
4319 return a.normalize(context=self)
4320
Facundo Batista353750c2007-09-13 18:13:15 +00004321 def number_class(self, a):
4322 """Returns an indication of the class of the operand.
4323
4324 The class is one of the following strings:
4325 -sNaN
4326 -NaN
4327 -Infinity
4328 -Normal
4329 -Subnormal
4330 -Zero
4331 +Zero
4332 +Subnormal
4333 +Normal
4334 +Infinity
4335
4336 >>> c = Context(ExtendedContext)
4337 >>> c.Emin = -999
4338 >>> c.Emax = 999
4339 >>> c.number_class(Decimal('Infinity'))
4340 '+Infinity'
4341 >>> c.number_class(Decimal('1E-10'))
4342 '+Normal'
4343 >>> c.number_class(Decimal('2.50'))
4344 '+Normal'
4345 >>> c.number_class(Decimal('0.1E-999'))
4346 '+Subnormal'
4347 >>> c.number_class(Decimal('0'))
4348 '+Zero'
4349 >>> c.number_class(Decimal('-0'))
4350 '-Zero'
4351 >>> c.number_class(Decimal('-0.1E-999'))
4352 '-Subnormal'
4353 >>> c.number_class(Decimal('-1E-10'))
4354 '-Normal'
4355 >>> c.number_class(Decimal('-2.50'))
4356 '-Normal'
4357 >>> c.number_class(Decimal('-Infinity'))
4358 '-Infinity'
4359 >>> c.number_class(Decimal('NaN'))
4360 'NaN'
4361 >>> c.number_class(Decimal('-NaN'))
4362 'NaN'
4363 >>> c.number_class(Decimal('sNaN'))
4364 'sNaN'
4365 """
4366 return a.number_class(context=self)
4367
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004368 def plus(self, a):
4369 """Plus corresponds to unary prefix plus in Python.
4370
4371 The operation is evaluated using the same rules as add; the
4372 operation plus(a) is calculated as add('0', a) where the '0'
4373 has the same exponent as the operand.
4374
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004375 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004376 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004377 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004378 Decimal("-1.3")
4379 """
4380 return a.__pos__(context=self)
4381
4382 def power(self, a, b, modulo=None):
4383 """Raises a to the power of b, to modulo if given.
4384
Facundo Batista353750c2007-09-13 18:13:15 +00004385 With two arguments, compute a**b. If a is negative then b
4386 must be integral. The result will be inexact unless b is
4387 integral and the result is finite and can be expressed exactly
4388 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004389
Facundo Batista353750c2007-09-13 18:13:15 +00004390 With three arguments, compute (a**b) % modulo. For the
4391 three argument form, the following restrictions on the
4392 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004393
Facundo Batista353750c2007-09-13 18:13:15 +00004394 - all three arguments must be integral
4395 - b must be nonnegative
4396 - at least one of a or b must be nonzero
4397 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004398
Facundo Batista353750c2007-09-13 18:13:15 +00004399 The result of pow(a, b, modulo) is identical to the result
4400 that would be obtained by computing (a**b) % modulo with
4401 unbounded precision, but is computed more efficiently. It is
4402 always exact.
4403
4404 >>> c = ExtendedContext.copy()
4405 >>> c.Emin = -999
4406 >>> c.Emax = 999
4407 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004408 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004409 >>> c.power(Decimal('-2'), Decimal('3'))
4410 Decimal("-8")
4411 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004412 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004413 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004414 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004415 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4416 Decimal("2.00000000")
4417 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004418 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004419 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004420 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004421 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004422 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004423 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004424 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004425 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004426 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004427 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004428 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004429 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004430 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004431 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004432 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004433
4434 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4435 Decimal("11")
4436 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4437 Decimal("-11")
4438 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4439 Decimal("1")
4440 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4441 Decimal("11")
4442 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4443 Decimal("11729830")
4444 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4445 Decimal("-0")
4446 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4447 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004448 """
4449 return a.__pow__(b, modulo, context=self)
4450
4451 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004452 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004453
4454 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004455 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004456 exponent is being increased), multiplied by a positive power of ten (if
4457 the exponent is being decreased), or is unchanged (if the exponent is
4458 already equal to that of the right-hand operand).
4459
4460 Unlike other operations, if the length of the coefficient after the
4461 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004462 operation condition is raised. This guarantees that, unless there is
4463 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004464 equal to that of the right-hand operand.
4465
4466 Also unlike other operations, quantize will never raise Underflow, even
4467 if the result is subnormal and inexact.
4468
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004469 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004470 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004471 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004472 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004473 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004474 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004475 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004476 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004477 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004478 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004479 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004480 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004481 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004482 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004483 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004484 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004485 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004486 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004487 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004488 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004489 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004490 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004491 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004492 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004493 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004494 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004495 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004496 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004497 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004498 Decimal("2E+2")
4499 """
4500 return a.quantize(b, context=self)
4501
Facundo Batista353750c2007-09-13 18:13:15 +00004502 def radix(self):
4503 """Just returns 10, as this is Decimal, :)
4504
4505 >>> ExtendedContext.radix()
4506 Decimal("10")
4507 """
4508 return Decimal(10)
4509
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004510 def remainder(self, a, b):
4511 """Returns the remainder from integer division.
4512
4513 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004514 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004515 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004516 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004517
4518 This operation will fail under the same conditions as integer division
4519 (that is, if integer division on the same two operands would fail, the
4520 remainder cannot be calculated).
4521
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004522 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004523 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004524 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004525 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004526 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004527 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004528 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004529 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004530 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004531 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004532 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004533 Decimal("1.0")
4534 """
4535 return a.__mod__(b, context=self)
4536
4537 def remainder_near(self, a, b):
4538 """Returns to be "a - b * n", where n is the integer nearest the exact
4539 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004540 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004541 sign of a.
4542
4543 This operation will fail under the same conditions as integer division
4544 (that is, if integer division on the same two operands would fail, the
4545 remainder cannot be calculated).
4546
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004547 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004548 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004549 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004550 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004551 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004552 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004553 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004554 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004555 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004556 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004557 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004558 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004559 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004560 Decimal("-0.3")
4561 """
4562 return a.remainder_near(b, context=self)
4563
Facundo Batista353750c2007-09-13 18:13:15 +00004564 def rotate(self, a, b):
4565 """Returns a rotated copy of a, b times.
4566
4567 The coefficient of the result is a rotated copy of the digits in
4568 the coefficient of the first operand. The number of places of
4569 rotation is taken from the absolute value of the second operand,
4570 with the rotation being to the left if the second operand is
4571 positive or to the right otherwise.
4572
4573 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4574 Decimal("400000003")
4575 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4576 Decimal("12")
4577 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4578 Decimal("891234567")
4579 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4580 Decimal("123456789")
4581 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4582 Decimal("345678912")
4583 """
4584 return a.rotate(b, context=self)
4585
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004586 def same_quantum(self, a, b):
4587 """Returns True if the two operands have the same exponent.
4588
4589 The result is never affected by either the sign or the coefficient of
4590 either operand.
4591
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004592 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004593 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004594 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004595 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004596 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004597 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004598 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004599 True
4600 """
4601 return a.same_quantum(b)
4602
Facundo Batista353750c2007-09-13 18:13:15 +00004603 def scaleb (self, a, b):
4604 """Returns the first operand after adding the second value its exp.
4605
4606 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4607 Decimal("0.0750")
4608 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4609 Decimal("7.50")
4610 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4611 Decimal("7.50E+3")
4612 """
4613 return a.scaleb (b, context=self)
4614
4615 def shift(self, a, b):
4616 """Returns a shifted copy of a, b times.
4617
4618 The coefficient of the result is a shifted copy of the digits
4619 in the coefficient of the first operand. The number of places
4620 to shift is taken from the absolute value of the second operand,
4621 with the shift being to the left if the second operand is
4622 positive or to the right otherwise. Digits shifted into the
4623 coefficient are zeros.
4624
4625 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4626 Decimal("400000000")
4627 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4628 Decimal("0")
4629 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4630 Decimal("1234567")
4631 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4632 Decimal("123456789")
4633 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4634 Decimal("345678900")
4635 """
4636 return a.shift(b, context=self)
4637
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004638 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004639 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004640
4641 If the result must be inexact, it is rounded using the round-half-even
4642 algorithm.
4643
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004644 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004645 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004646 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004647 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004648 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004649 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004650 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004651 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004652 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004653 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004654 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004655 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004656 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004657 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004658 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004659 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004660 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004661 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004662 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004663 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004664 """
4665 return a.sqrt(context=self)
4666
4667 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004668 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004669
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004670 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004671 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004672 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004673 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004674 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004675 Decimal("-0.77")
4676 """
4677 return a.__sub__(b, context=self)
4678
4679 def to_eng_string(self, a):
4680 """Converts a number to a string, using scientific notation.
4681
4682 The operation is not affected by the context.
4683 """
4684 return a.to_eng_string(context=self)
4685
4686 def to_sci_string(self, a):
4687 """Converts a number to a string, using scientific notation.
4688
4689 The operation is not affected by the context.
4690 """
4691 return a.__str__(context=self)
4692
Facundo Batista353750c2007-09-13 18:13:15 +00004693 def to_integral_exact(self, a):
4694 """Rounds to an integer.
4695
4696 When the operand has a negative exponent, the result is the same
4697 as using the quantize() operation using the given operand as the
4698 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4699 of the operand as the precision setting; Inexact and Rounded flags
4700 are allowed in this operation. The rounding mode is taken from the
4701 context.
4702
4703 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4704 Decimal("2")
4705 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4706 Decimal("100")
4707 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4708 Decimal("100")
4709 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4710 Decimal("102")
4711 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4712 Decimal("-102")
4713 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4714 Decimal("1.0E+6")
4715 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4716 Decimal("7.89E+77")
4717 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4718 Decimal("-Infinity")
4719 """
4720 return a.to_integral_exact(context=self)
4721
4722 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004723 """Rounds to an integer.
4724
4725 When the operand has a negative exponent, the result is the same
4726 as using the quantize() operation using the given operand as the
4727 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4728 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004729 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004730
Facundo Batista353750c2007-09-13 18:13:15 +00004731 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004732 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004733 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004734 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004735 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004736 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004737 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004738 Decimal("102")
Facundo Batista353750c2007-09-13 18:13:15 +00004739 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004740 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004741 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004742 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004743 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004744 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004745 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004746 Decimal("-Infinity")
4747 """
Facundo Batista353750c2007-09-13 18:13:15 +00004748 return a.to_integral_value(context=self)
4749
4750 # the method name changed, but we provide also the old one, for compatibility
4751 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004752
4753class _WorkRep(object):
4754 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004755 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004756 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004757 # exp: None, int, or string
4758
4759 def __init__(self, value=None):
4760 if value is None:
4761 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004762 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004763 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004764 elif isinstance(value, Decimal):
4765 self.sign = value._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004766 cum = 0
Raymond Hettinger17931de2004-10-27 06:21:46 +00004767 for digit in value._int:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004768 cum = cum * 10 + digit
4769 self.int = cum
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004770 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004771 else:
4772 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004773 self.sign = value[0]
4774 self.int = value[1]
4775 self.exp = value[2]
4776
4777 def __repr__(self):
4778 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4779
4780 __str__ = __repr__
4781
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004782
4783
4784def _normalize(op1, op2, shouldround = 0, prec = 0):
4785 """Normalizes op1, op2 to have the same exp and length of coefficient.
4786
4787 Done during addition.
4788 """
Facundo Batista353750c2007-09-13 18:13:15 +00004789 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004790 tmp = op2
4791 other = op1
4792 else:
4793 tmp = op1
4794 other = op2
4795
Facundo Batista353750c2007-09-13 18:13:15 +00004796 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4797 # Then adding 10**exp to tmp has the same effect (after rounding)
4798 # as adding any positive quantity smaller than 10**exp; similarly
4799 # for subtraction. So if other is smaller than 10**exp we replace
4800 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4801 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004802 tmp_len = len(str(tmp.int))
4803 other_len = len(str(other.int))
Facundo Batista353750c2007-09-13 18:13:15 +00004804 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4805 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004806 other.int = 1
Facundo Batista353750c2007-09-13 18:13:15 +00004807 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004808
Facundo Batista353750c2007-09-13 18:13:15 +00004809 tmp.int *= 10 ** (tmp.exp - other.exp)
4810 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004811 return op1, op2
4812
Facundo Batista353750c2007-09-13 18:13:15 +00004813##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4814
4815# This function from Tim Peters was taken from here:
4816# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4817# The correction being in the function definition is for speed, and
4818# the whole function is not resolved with math.log because of avoiding
4819# the use of floats.
4820def _nbits(n, correction = {
4821 '0': 4, '1': 3, '2': 2, '3': 2,
4822 '4': 1, '5': 1, '6': 1, '7': 1,
4823 '8': 0, '9': 0, 'a': 0, 'b': 0,
4824 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4825 """Number of bits in binary representation of the positive integer n,
4826 or 0 if n == 0.
4827 """
4828 if n < 0:
4829 raise ValueError("The argument to _nbits should be nonnegative.")
4830 hex_n = "%x" % n
4831 return 4*len(hex_n) - correction[hex_n[0]]
4832
4833def _sqrt_nearest(n, a):
4834 """Closest integer to the square root of the positive integer n. a is
4835 an initial approximation to the square root. Any positive integer
4836 will do for a, but the closer a is to the square root of n the
4837 faster convergence will be.
4838
4839 """
4840 if n <= 0 or a <= 0:
4841 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4842
4843 b=0
4844 while a != b:
4845 b, a = a, a--n//a>>1
4846 return a
4847
4848def _rshift_nearest(x, shift):
4849 """Given an integer x and a nonnegative integer shift, return closest
4850 integer to x / 2**shift; use round-to-even in case of a tie.
4851
4852 """
4853 b, q = 1L << shift, x >> shift
4854 return q + (2*(x & (b-1)) + (q&1) > b)
4855
4856def _div_nearest(a, b):
4857 """Closest integer to a/b, a and b positive integers; rounds to even
4858 in the case of a tie.
4859
4860 """
4861 q, r = divmod(a, b)
4862 return q + (2*r + (q&1) > b)
4863
4864def _ilog(x, M, L = 8):
4865 """Integer approximation to M*log(x/M), with absolute error boundable
4866 in terms only of x/M.
4867
4868 Given positive integers x and M, return an integer approximation to
4869 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4870 between the approximation and the exact result is at most 22. For
4871 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4872 both cases these are upper bounds on the error; it will usually be
4873 much smaller."""
4874
4875 # The basic algorithm is the following: let log1p be the function
4876 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4877 # the reduction
4878 #
4879 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4880 #
4881 # repeatedly until the argument to log1p is small (< 2**-L in
4882 # absolute value). For small y we can use the Taylor series
4883 # expansion
4884 #
4885 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4886 #
4887 # truncating at T such that y**T is small enough. The whole
4888 # computation is carried out in a form of fixed-point arithmetic,
4889 # with a real number z being represented by an integer
4890 # approximation to z*M. To avoid loss of precision, the y below
4891 # is actually an integer approximation to 2**R*y*M, where R is the
4892 # number of reductions performed so far.
4893
4894 y = x-M
4895 # argument reduction; R = number of reductions performed
4896 R = 0
4897 while (R <= L and long(abs(y)) << L-R >= M or
4898 R > L and abs(y) >> R-L >= M):
4899 y = _div_nearest(long(M*y) << 1,
4900 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4901 R += 1
4902
4903 # Taylor series with T terms
4904 T = -int(-10*len(str(M))//(3*L))
4905 yshift = _rshift_nearest(y, R)
4906 w = _div_nearest(M, T)
4907 for k in xrange(T-1, 0, -1):
4908 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4909
4910 return _div_nearest(w*y, M)
4911
4912def _dlog10(c, e, p):
4913 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4914 approximation to 10**p * log10(c*10**e), with an absolute error of
4915 at most 1. Assumes that c*10**e is not exactly 1."""
4916
4917 # increase precision by 2; compensate for this by dividing
4918 # final result by 100
4919 p += 2
4920
4921 # write c*10**e as d*10**f with either:
4922 # f >= 0 and 1 <= d <= 10, or
4923 # f <= 0 and 0.1 <= d <= 1.
4924 # Thus for c*10**e close to 1, f = 0
4925 l = len(str(c))
4926 f = e+l - (e+l >= 1)
4927
4928 if p > 0:
4929 M = 10**p
4930 k = e+p-f
4931 if k >= 0:
4932 c *= 10**k
4933 else:
4934 c = _div_nearest(c, 10**-k)
4935
4936 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004937 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004938 log_d = _div_nearest(log_d*M, log_10)
4939 log_tenpower = f*M # exact
4940 else:
4941 log_d = 0 # error < 2.31
4942 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4943
4944 return _div_nearest(log_tenpower+log_d, 100)
4945
4946def _dlog(c, e, p):
4947 """Given integers c, e and p with c > 0, compute an integer
4948 approximation to 10**p * log(c*10**e), with an absolute error of
4949 at most 1. Assumes that c*10**e is not exactly 1."""
4950
4951 # Increase precision by 2. The precision increase is compensated
4952 # for at the end with a division by 100.
4953 p += 2
4954
4955 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4956 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4957 # as 10**p * log(d) + 10**p*f * log(10).
4958 l = len(str(c))
4959 f = e+l - (e+l >= 1)
4960
4961 # compute approximation to 10**p*log(d), with error < 27
4962 if p > 0:
4963 k = e+p-f
4964 if k >= 0:
4965 c *= 10**k
4966 else:
4967 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4968
4969 # _ilog magnifies existing error in c by a factor of at most 10
4970 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4971 else:
4972 # p <= 0: just approximate the whole thing by 0; error < 2.31
4973 log_d = 0
4974
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004975 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00004976 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004977 extra = len(str(abs(f)))-1
4978 if p + extra >= 0:
4979 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4980 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4981 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00004982 else:
4983 f_log_ten = 0
4984 else:
4985 f_log_ten = 0
4986
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004987 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004988 return _div_nearest(f_log_ten + log_d, 100)
4989
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004990class _Log10Memoize(object):
4991 """Class to compute, store, and allow retrieval of, digits of the
4992 constant log(10) = 2.302585.... This constant is needed by
4993 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4994 def __init__(self):
4995 self.digits = "23025850929940456840179914546843642076011014886"
4996
4997 def getdigits(self, p):
4998 """Given an integer p >= 0, return floor(10**p)*log(10).
4999
5000 For example, self.getdigits(3) returns 2302.
5001 """
5002 # digits are stored as a string, for quick conversion to
5003 # integer in the case that we've already computed enough
5004 # digits; the stored digits should always be correct
5005 # (truncated, not rounded to nearest).
5006 if p < 0:
5007 raise ValueError("p should be nonnegative")
5008
5009 if p >= len(self.digits):
5010 # compute p+3, p+6, p+9, ... digits; continue until at
5011 # least one of the extra digits is nonzero
5012 extra = 3
5013 while True:
5014 # compute p+extra digits, correct to within 1ulp
5015 M = 10**(p+extra+2)
5016 digits = str(_div_nearest(_ilog(10*M, M), 100))
5017 if digits[-extra:] != '0'*extra:
5018 break
5019 extra += 3
5020 # keep all reliable digits so far; remove trailing zeros
5021 # and next nonzero digit
5022 self.digits = digits.rstrip('0')[:-1]
5023 return int(self.digits[:p+1])
5024
5025_log10_digits = _Log10Memoize().getdigits
5026
Facundo Batista353750c2007-09-13 18:13:15 +00005027def _iexp(x, M, L=8):
5028 """Given integers x and M, M > 0, such that x/M is small in absolute
5029 value, compute an integer approximation to M*exp(x/M). For 0 <=
5030 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5031 is usually much smaller)."""
5032
5033 # Algorithm: to compute exp(z) for a real number z, first divide z
5034 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5035 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5036 # series
5037 #
5038 # expm1(x) = x + x**2/2! + x**3/3! + ...
5039 #
5040 # Now use the identity
5041 #
5042 # expm1(2x) = expm1(x)*(expm1(x)+2)
5043 #
5044 # R times to compute the sequence expm1(z/2**R),
5045 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5046
5047 # Find R such that x/2**R/M <= 2**-L
5048 R = _nbits((long(x)<<L)//M)
5049
5050 # Taylor series. (2**L)**T > M
5051 T = -int(-10*len(str(M))//(3*L))
5052 y = _div_nearest(x, T)
5053 Mshift = long(M)<<R
5054 for i in xrange(T-1, 0, -1):
5055 y = _div_nearest(x*(Mshift + y), Mshift * i)
5056
5057 # Expansion
5058 for k in xrange(R-1, -1, -1):
5059 Mshift = long(M)<<(k+2)
5060 y = _div_nearest(y*(y+Mshift), Mshift)
5061
5062 return M+y
5063
5064def _dexp(c, e, p):
5065 """Compute an approximation to exp(c*10**e), with p decimal places of
5066 precision.
5067
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005068 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005069
5070 10**(p-1) <= d <= 10**p, and
5071 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5072
5073 In other words, d*10**f is an approximation to exp(c*10**e) with p
5074 digits of precision, and with an error in d of at most 1. This is
5075 almost, but not quite, the same as the error being < 1ulp: when d
5076 = 10**(p-1) the error could be up to 10 ulp."""
5077
5078 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5079 p += 2
5080
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005081 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005082 extra = max(0, e + len(str(c)) - 1)
5083 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005084
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005085 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005086 # rounding down
5087 shift = e+q
5088 if shift >= 0:
5089 cshift = c*10**shift
5090 else:
5091 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005092 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005093
5094 # reduce remainder back to original precision
5095 rem = _div_nearest(rem, 10**extra)
5096
5097 # error in result of _iexp < 120; error after division < 0.62
5098 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5099
5100def _dpower(xc, xe, yc, ye, p):
5101 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5102 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5103
5104 10**(p-1) <= c <= 10**p, and
5105 (c-1)*10**e < x**y < (c+1)*10**e
5106
5107 in other words, c*10**e is an approximation to x**y with p digits
5108 of precision, and with an error in c of at most 1. (This is
5109 almost, but not quite, the same as the error being < 1ulp: when c
5110 == 10**(p-1) we can only guarantee error < 10ulp.)
5111
5112 We assume that: x is positive and not equal to 1, and y is nonzero.
5113 """
5114
5115 # Find b such that 10**(b-1) <= |y| <= 10**b
5116 b = len(str(abs(yc))) + ye
5117
5118 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5119 lxc = _dlog(xc, xe, p+b+1)
5120
5121 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5122 shift = ye-b
5123 if shift >= 0:
5124 pc = lxc*yc*10**shift
5125 else:
5126 pc = _div_nearest(lxc*yc, 10**-shift)
5127
5128 if pc == 0:
5129 # we prefer a result that isn't exactly 1; this makes it
5130 # easier to compute a correctly rounded result in __pow__
5131 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5132 coeff, exp = 10**(p-1)+1, 1-p
5133 else:
5134 coeff, exp = 10**p-1, -p
5135 else:
5136 coeff, exp = _dexp(pc, -(p+1), p+1)
5137 coeff = _div_nearest(coeff, 10)
5138 exp += 1
5139
5140 return coeff, exp
5141
5142def _log10_lb(c, correction = {
5143 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5144 '6': 23, '7': 16, '8': 10, '9': 5}):
5145 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5146 if c <= 0:
5147 raise ValueError("The argument to _log10_lb should be nonnegative.")
5148 str_c = str(c)
5149 return 100*len(str_c) - correction[str_c[0]]
5150
Facundo Batista59c58842007-04-10 12:58:45 +00005151##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005152
Facundo Batista353750c2007-09-13 18:13:15 +00005153def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005154 """Convert other to Decimal.
5155
5156 Verifies that it's ok to use in an implicit construction.
5157 """
5158 if isinstance(other, Decimal):
5159 return other
5160 if isinstance(other, (int, long)):
5161 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005162 if raiseit:
5163 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005164 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005165
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005166_infinity_map = {
5167 'inf' : 1,
5168 'infinity' : 1,
5169 '+inf' : 1,
5170 '+infinity' : 1,
5171 '-inf' : -1,
5172 '-infinity' : -1
5173}
5174
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005175def _isinfinity(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005176 """Determines whether a string or float is infinity.
5177
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005178 +1 for negative infinity; 0 for finite ; +1 for positive infinity
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005179 """
5180 num = str(num).lower()
5181 return _infinity_map.get(num, 0)
5182
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005183def _isnan(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005184 """Determines whether a string or float is NaN
5185
5186 (1, sign, diagnostic info as string) => NaN
5187 (2, sign, diagnostic info as string) => sNaN
5188 0 => not a NaN
5189 """
5190 num = str(num).lower()
5191 if not num:
5192 return 0
5193
Facundo Batista59c58842007-04-10 12:58:45 +00005194 # Get the sign, get rid of trailing [+-]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005195 sign = 0
5196 if num[0] == '+':
5197 num = num[1:]
Facundo Batista59c58842007-04-10 12:58:45 +00005198 elif num[0] == '-': # elif avoids '+-nan'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005199 num = num[1:]
5200 sign = 1
5201
5202 if num.startswith('nan'):
Facundo Batista59c58842007-04-10 12:58:45 +00005203 if len(num) > 3 and not num[3:].isdigit(): # diagnostic info
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005204 return 0
5205 return (1, sign, num[3:].lstrip('0'))
5206 if num.startswith('snan'):
5207 if len(num) > 4 and not num[4:].isdigit():
5208 return 0
5209 return (2, sign, num[4:].lstrip('0'))
5210 return 0
5211
5212
Facundo Batista59c58842007-04-10 12:58:45 +00005213##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005214
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005215# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005216# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005217
5218DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005219 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005220 traps=[DivisionByZero, Overflow, InvalidOperation],
5221 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005222 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005223 Emax=999999999,
5224 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005225 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005226)
5227
5228# Pre-made alternate contexts offered by the specification
5229# Don't change these; the user should be able to select these
5230# contexts and be able to reproduce results from other implementations
5231# of the spec.
5232
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005233BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005234 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005235 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5236 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005237)
5238
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005239ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005240 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005241 traps=[],
5242 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005243)
5244
5245
Facundo Batista59c58842007-04-10 12:58:45 +00005246##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005247
Facundo Batista59c58842007-04-10 12:58:45 +00005248# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005249Inf = Decimal('Inf')
5250negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005251NaN = Decimal('NaN')
5252Dec_0 = Decimal(0)
5253Dec_p1 = Decimal(1)
5254Dec_n1 = Decimal(-1)
5255Dec_p2 = Decimal(2)
5256Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005257
Facundo Batista59c58842007-04-10 12:58:45 +00005258# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005259Infsign = (Inf, negInf)
5260
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005261
Facundo Batista59c58842007-04-10 12:58:45 +00005262##### crud for parsing strings #############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005263import re
5264
5265# There's an optional sign at the start, and an optional exponent
5266# at the end. The exponent has an optional sign and at least one
5267# digit. In between, must have either at least one digit followed
5268# by an optional fraction, or a decimal point followed by at least
5269# one digit. Yuck.
5270
5271_parser = re.compile(r"""
5272# \s*
5273 (?P<sign>[-+])?
5274 (
5275 (?P<int>\d+) (\. (?P<frac>\d*))?
5276 |
5277 \. (?P<onlyfrac>\d+)
5278 )
5279 ([eE](?P<exp>[-+]? \d+))?
5280# \s*
5281 $
Facundo Batista59c58842007-04-10 12:58:45 +00005282""", re.VERBOSE).match # Uncomment the \s* to allow leading or trailing spaces.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005283
5284del re
5285
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005286def _string2exact(s):
Facundo Batista59c58842007-04-10 12:58:45 +00005287 """Return sign, n, p s.t.
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00005288
Facundo Batista59c58842007-04-10 12:58:45 +00005289 Float string value == -1**sign * n * 10**p exactly
5290 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005291 m = _parser(s)
5292 if m is None:
5293 raise ValueError("invalid literal for Decimal: %r" % s)
5294
5295 if m.group('sign') == "-":
5296 sign = 1
5297 else:
5298 sign = 0
5299
5300 exp = m.group('exp')
5301 if exp is None:
5302 exp = 0
5303 else:
5304 exp = int(exp)
5305
5306 intpart = m.group('int')
5307 if intpart is None:
5308 intpart = ""
5309 fracpart = m.group('onlyfrac')
5310 else:
5311 fracpart = m.group('frac')
5312 if fracpart is None:
5313 fracpart = ""
5314
5315 exp -= len(fracpart)
5316
5317 mantissa = intpart + fracpart
5318 tmp = map(int, mantissa)
5319 backup = tmp
5320 while tmp and tmp[0] == 0:
5321 del tmp[0]
5322
5323 # It's a zero
5324 if not tmp:
5325 if backup:
5326 return (sign, tuple(backup), exp)
5327 return (sign, (0,), exp)
5328 mantissa = tuple(tmp)
5329
5330 return (sign, mantissa, exp)
5331
5332
5333if __name__ == '__main__':
5334 import doctest, sys
5335 doctest.testmod(sys.modules[__name__])