blob: dbe06951078f816a181fc3d2273c7340f5a6e6c2 [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
Raymond Hettinger097a1902008-01-11 02:24:13 +0000139try:
140 from collections import namedtuple as _namedtuple
141 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
142except ImportError:
143 DecimalTuple = lambda *args: args
144
Facundo Batista59c58842007-04-10 12:58:45 +0000145# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000146ROUND_DOWN = 'ROUND_DOWN'
147ROUND_HALF_UP = 'ROUND_HALF_UP'
148ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
149ROUND_CEILING = 'ROUND_CEILING'
150ROUND_FLOOR = 'ROUND_FLOOR'
151ROUND_UP = 'ROUND_UP'
152ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Facundo Batista353750c2007-09-13 18:13:15 +0000153ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000154
Facundo Batista59c58842007-04-10 12:58:45 +0000155# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000156
157class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000158 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000159
160 Used exceptions derive from this.
161 If an exception derives from another exception besides this (such as
162 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
163 called if the others are present. This isn't actually used for
164 anything, though.
165
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000166 handle -- Called when context._raise_error is called and the
167 trap_enabler is set. First argument is self, second is the
168 context. More arguments can be given, those being after
169 the explanation in _raise_error (For example,
170 context._raise_error(NewError, '(-x)!', self._sign) would
171 call NewError().handle(context, self._sign).)
172
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000173 To define a new exception, it should be sufficient to have it derive
174 from DecimalException.
175 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000176 def handle(self, context, *args):
177 pass
178
179
180class Clamped(DecimalException):
181 """Exponent of a 0 changed to fit bounds.
182
183 This occurs and signals clamped if the exponent of a result has been
184 altered in order to fit the constraints of a specific concrete
Facundo Batista59c58842007-04-10 12:58:45 +0000185 representation. This may occur when the exponent of a zero result would
186 be outside the bounds of a representation, or when a large normal
187 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000188 this latter case, the exponent is reduced to fit and the corresponding
189 number of zero digits are appended to the coefficient ("fold-down").
190 """
191
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000192class InvalidOperation(DecimalException):
193 """An invalid operation was performed.
194
195 Various bad things cause this:
196
197 Something creates a signaling NaN
198 -INF + INF
Facundo Batista59c58842007-04-10 12:58:45 +0000199 0 * (+-)INF
200 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000201 x % 0
202 (+-)INF % x
203 x._rescale( non-integer )
204 sqrt(-x) , x > 0
205 0 ** 0
206 x ** (non-integer)
207 x ** (+-)INF
208 An operand is invalid
Facundo Batista353750c2007-09-13 18:13:15 +0000209
210 The result of the operation after these is a quiet positive NaN,
211 except when the cause is a signaling NaN, in which case the result is
212 also a quiet NaN, but with the original sign, and an optional
213 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000214 """
215 def handle(self, context, *args):
216 if args:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000217 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
218 return ans._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000219 return NaN
220
221class ConversionSyntax(InvalidOperation):
222 """Trying to convert badly formed string.
223
224 This occurs and signals invalid-operation if an string is being
225 converted to a number and it does not conform to the numeric string
Facundo Batista59c58842007-04-10 12:58:45 +0000226 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000227 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000228 def handle(self, context, *args):
Facundo Batista353750c2007-09-13 18:13:15 +0000229 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000230
231class DivisionByZero(DecimalException, ZeroDivisionError):
232 """Division by 0.
233
234 This occurs and signals division-by-zero if division of a finite number
235 by zero was attempted (during a divide-integer or divide operation, or a
236 power operation with negative right-hand operand), and the dividend was
237 not zero.
238
239 The result of the operation is [sign,inf], where sign is the exclusive
240 or of the signs of the operands for divide, or is 1 for an odd power of
241 -0, for power.
242 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000243
Facundo Batistacce8df22007-09-18 16:53:18 +0000244 def handle(self, context, sign, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000245 return Infsign[sign]
246
247class DivisionImpossible(InvalidOperation):
248 """Cannot perform the division adequately.
249
250 This occurs and signals invalid-operation if the integer result of a
251 divide-integer or remainder operation had too many digits (would be
Facundo Batista59c58842007-04-10 12:58:45 +0000252 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000253 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000254
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000255 def handle(self, context, *args):
Facundo Batistacce8df22007-09-18 16:53:18 +0000256 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000257
258class DivisionUndefined(InvalidOperation, ZeroDivisionError):
259 """Undefined result of division.
260
261 This occurs and signals invalid-operation if division by zero was
262 attempted (during a divide-integer, divide, or remainder operation), and
Facundo Batista59c58842007-04-10 12:58:45 +0000263 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000264 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000265
Facundo Batistacce8df22007-09-18 16:53:18 +0000266 def handle(self, context, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000267 return NaN
268
269class Inexact(DecimalException):
270 """Had to round, losing information.
271
272 This occurs and signals inexact whenever the result of an operation is
273 not exact (that is, it needed to be rounded and any discarded digits
Facundo Batista59c58842007-04-10 12:58:45 +0000274 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000275 result in all cases is unchanged.
276
277 The inexact signal may be tested (or trapped) to determine if a given
278 operation (or sequence of operations) was inexact.
279 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000280
281class InvalidContext(InvalidOperation):
282 """Invalid context. Unknown rounding, for example.
283
284 This occurs and signals invalid-operation if an invalid context was
Facundo Batista59c58842007-04-10 12:58:45 +0000285 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000286 on creation and either the precision exceeds the capability of the
287 underlying concrete representation or an unknown or unsupported rounding
Facundo Batista59c58842007-04-10 12:58:45 +0000288 was specified. These aspects of the context need only be checked when
289 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000290 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000291
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000292 def handle(self, context, *args):
293 return NaN
294
295class Rounded(DecimalException):
296 """Number got rounded (not necessarily changed during rounding).
297
298 This occurs and signals rounded whenever the result of an operation is
299 rounded (that is, some zero or non-zero digits were discarded from the
Facundo Batista59c58842007-04-10 12:58:45 +0000300 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000301 result in all cases is unchanged.
302
303 The rounded signal may be tested (or trapped) to determine if a given
304 operation (or sequence of operations) caused a loss of precision.
305 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000306
307class Subnormal(DecimalException):
308 """Exponent < Emin before rounding.
309
310 This occurs and signals subnormal whenever the result of a conversion or
311 operation is subnormal (that is, its adjusted exponent is less than
Facundo Batista59c58842007-04-10 12:58:45 +0000312 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000313
314 The subnormal signal may be tested (or trapped) to determine if a given
315 or operation (or sequence of operations) yielded a subnormal result.
316 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000317
318class Overflow(Inexact, Rounded):
319 """Numerical overflow.
320
321 This occurs and signals overflow if the adjusted exponent of a result
322 (from a conversion or from an operation that is not an attempt to divide
323 by zero), after rounding, would be greater than the largest value that
324 can be handled by the implementation (the value Emax).
325
326 The result depends on the rounding mode:
327
328 For round-half-up and round-half-even (and for round-half-down and
329 round-up, if implemented), the result of the operation is [sign,inf],
Facundo Batista59c58842007-04-10 12:58:45 +0000330 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000331 result is the largest finite number that can be represented in the
Facundo Batista59c58842007-04-10 12:58:45 +0000332 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000333 round-ceiling, the result is the same as for round-down if the sign of
Facundo Batista59c58842007-04-10 12:58:45 +0000334 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000335 the result is the same as for round-down if the sign of the intermediate
Facundo Batista59c58842007-04-10 12:58:45 +0000336 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 will also be raised.
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000338 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000339
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000340 def handle(self, context, sign, *args):
341 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Facundo Batista353750c2007-09-13 18:13:15 +0000342 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000343 return Infsign[sign]
344 if sign == 0:
345 if context.rounding == ROUND_CEILING:
346 return Infsign[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000347 return _dec_from_triple(sign, '9'*context.prec,
348 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000349 if sign == 1:
350 if context.rounding == ROUND_FLOOR:
351 return Infsign[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000352 return _dec_from_triple(sign, '9'*context.prec,
353 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000354
355
356class Underflow(Inexact, Rounded, Subnormal):
357 """Numerical underflow with result rounded to 0.
358
359 This occurs and signals underflow if a result is inexact and the
360 adjusted exponent of the result would be smaller (more negative) than
361 the smallest value that can be handled by the implementation (the value
Facundo Batista59c58842007-04-10 12:58:45 +0000362 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000363
364 The result after an underflow will be a subnormal number rounded, if
Facundo Batista59c58842007-04-10 12:58:45 +0000365 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000366 in 0 with the sign of the intermediate result and an exponent of Etiny.
367
368 In all cases, Inexact, Rounded, and Subnormal will also be raised.
369 """
370
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000371# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000372_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000373 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000374
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000375# Map conditions (per the spec) to signals
376_condition_map = {ConversionSyntax:InvalidOperation,
377 DivisionImpossible:InvalidOperation,
378 DivisionUndefined:InvalidOperation,
379 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000380
Facundo Batista59c58842007-04-10 12:58:45 +0000381##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000382
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000383# The getcontext() and setcontext() function manage access to a thread-local
384# current context. Py2.4 offers direct support for thread locals. If that
385# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000386# work for older Pythons. If threads are not part of the build, create a
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000387# mock threading object with threading.local() returning the module namespace.
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000388
389try:
390 import threading
391except ImportError:
392 # Python was compiled without threads; create a mock object instead
393 import sys
Facundo Batista59c58842007-04-10 12:58:45 +0000394 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000395 def local(self, sys=sys):
396 return sys.modules[__name__]
397 threading = MockThreading()
398 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000399
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000400try:
401 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000402
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000403except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000404
Facundo Batista59c58842007-04-10 12:58:45 +0000405 # To fix reloading, force it to create a new context
406 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000407 if hasattr(threading.currentThread(), '__decimal_context__'):
408 del threading.currentThread().__decimal_context__
409
410 def setcontext(context):
411 """Set this thread's context to context."""
412 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000413 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000414 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000415 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000416
417 def getcontext():
418 """Returns this thread's context.
419
420 If this thread does not yet have a context, returns
421 a new context and sets this thread's context.
422 New contexts are copies of DefaultContext.
423 """
424 try:
425 return threading.currentThread().__decimal_context__
426 except AttributeError:
427 context = Context()
428 threading.currentThread().__decimal_context__ = context
429 return context
430
431else:
432
433 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000434 if hasattr(local, '__decimal_context__'):
435 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000436
437 def getcontext(_local=local):
438 """Returns this thread's context.
439
440 If this thread does not yet have a context, returns
441 a new context and sets this thread's context.
442 New contexts are copies of DefaultContext.
443 """
444 try:
445 return _local.__decimal_context__
446 except AttributeError:
447 context = Context()
448 _local.__decimal_context__ = context
449 return context
450
451 def setcontext(context, _local=local):
452 """Set this thread's context to context."""
453 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000454 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000455 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000456 _local.__decimal_context__ = context
457
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000458 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000459
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000460def localcontext(ctx=None):
461 """Return a context manager for a copy of the supplied context
462
463 Uses a copy of the current context if no context is specified
464 The returned context manager creates a local decimal context
465 in a with statement:
466 def sin(x):
467 with localcontext() as ctx:
468 ctx.prec += 2
469 # Rest of sin calculation algorithm
470 # uses a precision 2 greater than normal
Facundo Batista59c58842007-04-10 12:58:45 +0000471 return +s # Convert result to normal precision
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000472
473 def sin(x):
474 with localcontext(ExtendedContext):
475 # Rest of sin calculation algorithm
476 # uses the Extended Context from the
477 # General Decimal Arithmetic Specification
Facundo Batista59c58842007-04-10 12:58:45 +0000478 return +s # Convert result to normal context
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000479
480 """
Neal Norwitz681d8672006-09-02 18:51:34 +0000481 # The string below can't be included in the docstring until Python 2.6
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000482 # as the doctest module doesn't understand __future__ statements
483 """
484 >>> from __future__ import with_statement
485 >>> print getcontext().prec
486 28
487 >>> with localcontext():
488 ... ctx = getcontext()
Raymond Hettinger495df472007-02-08 01:42:35 +0000489 ... ctx.prec += 2
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000490 ... print ctx.prec
491 ...
492 30
493 >>> with localcontext(ExtendedContext):
494 ... print getcontext().prec
495 ...
496 9
497 >>> print getcontext().prec
498 28
499 """
Nick Coghlanced12182006-09-02 03:54:17 +0000500 if ctx is None: ctx = getcontext()
501 return _ContextManager(ctx)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000502
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000503
Facundo Batista59c58842007-04-10 12:58:45 +0000504##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000505
506class Decimal(object):
507 """Floating point class for decimal arithmetic."""
508
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000509 __slots__ = ('_exp','_int','_sign', '_is_special')
510 # Generally, the value of the Decimal instance is given by
511 # (-1)**_sign * _int * 10**_exp
512 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000513
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000514 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000515 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000516 """Create a decimal point instance.
517
518 >>> Decimal('3.14') # string input
519 Decimal("3.14")
Facundo Batista59c58842007-04-10 12:58:45 +0000520 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000521 Decimal("3.14")
522 >>> Decimal(314) # int or long
523 Decimal("314")
524 >>> Decimal(Decimal(314)) # another decimal instance
525 Decimal("314")
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000526 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
527 Decimal("3.14")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000528 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000529
Facundo Batista72bc54f2007-11-23 17:59:00 +0000530 # Note that the coefficient, self._int, is actually stored as
531 # a string rather than as a tuple of digits. This speeds up
532 # the "digits to integer" and "integer to digits" conversions
533 # that are used in almost every arithmetic operation on
534 # Decimals. This is an internal detail: the as_tuple function
535 # and the Decimal constructor still deal with tuples of
536 # digits.
537
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000538 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000539
Facundo Batista0d157a02007-11-30 17:15:25 +0000540 # From a string
541 # REs insist on real strings, so we can too.
542 if isinstance(value, basestring):
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000543 m = _parser(value.strip())
Facundo Batista0d157a02007-11-30 17:15:25 +0000544 if m is None:
545 if context is None:
546 context = getcontext()
547 return context._raise_error(ConversionSyntax,
548 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000549
Facundo Batista0d157a02007-11-30 17:15:25 +0000550 if m.group('sign') == "-":
551 self._sign = 1
552 else:
553 self._sign = 0
554 intpart = m.group('int')
555 if intpart is not None:
556 # finite number
557 fracpart = m.group('frac')
558 exp = int(m.group('exp') or '0')
559 if fracpart is not None:
560 self._int = (intpart+fracpart).lstrip('0') or '0'
561 self._exp = exp - len(fracpart)
562 else:
563 self._int = intpart.lstrip('0') or '0'
564 self._exp = exp
565 self._is_special = False
566 else:
567 diag = m.group('diag')
568 if diag is not None:
569 # NaN
570 self._int = diag.lstrip('0')
571 if m.group('signal'):
572 self._exp = 'N'
573 else:
574 self._exp = 'n'
575 else:
576 # infinity
577 self._int = '0'
578 self._exp = 'F'
579 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000580 return self
581
582 # From an integer
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000583 if isinstance(value, (int,long)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000584 if value >= 0:
585 self._sign = 0
586 else:
587 self._sign = 1
588 self._exp = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +0000589 self._int = str(abs(value))
Facundo Batista0d157a02007-11-30 17:15:25 +0000590 self._is_special = False
591 return self
592
593 # From another decimal
594 if isinstance(value, Decimal):
595 self._exp = value._exp
596 self._sign = value._sign
597 self._int = value._int
598 self._is_special = value._is_special
599 return self
600
601 # From an internal working value
602 if isinstance(value, _WorkRep):
603 self._sign = value.sign
604 self._int = str(value.int)
605 self._exp = int(value.exp)
606 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000607 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000608
609 # tuple/list conversion (possibly from as_tuple())
610 if isinstance(value, (list,tuple)):
611 if len(value) != 3:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000612 raise ValueError('Invalid tuple size in creation of Decimal '
613 'from list or tuple. The list or tuple '
614 'should have exactly three elements.')
615 # process sign. The isinstance test rejects floats
616 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
617 raise ValueError("Invalid sign. The first value in the tuple "
618 "should be an integer; either 0 for a "
619 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000620 self._sign = value[0]
Facundo Batista9b5e2312007-10-19 19:25:57 +0000621 if value[2] == 'F':
622 # infinity: value[1] is ignored
Facundo Batista72bc54f2007-11-23 17:59:00 +0000623 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000624 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000625 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000626 else:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000627 # process and validate the digits in value[1]
628 digits = []
629 for digit in value[1]:
630 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
631 # skip leading zeros
632 if digits or digit != 0:
633 digits.append(digit)
634 else:
635 raise ValueError("The second value in the tuple must "
636 "be composed of integers in the range "
637 "0 through 9.")
638 if value[2] in ('n', 'N'):
639 # NaN: digits form the diagnostic
Facundo Batista72bc54f2007-11-23 17:59:00 +0000640 self._int = ''.join(map(str, digits))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000641 self._exp = value[2]
642 self._is_special = True
643 elif isinstance(value[2], (int, long)):
644 # finite number: digits give the coefficient
Facundo Batista72bc54f2007-11-23 17:59:00 +0000645 self._int = ''.join(map(str, digits or [0]))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000646 self._exp = value[2]
647 self._is_special = False
648 else:
649 raise ValueError("The third value in the tuple must "
650 "be an integer, or one of the "
651 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000652 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000653
Raymond Hettingerbf440692004-07-10 14:14:37 +0000654 if isinstance(value, float):
655 raise TypeError("Cannot convert float to Decimal. " +
656 "First convert the float to a string")
657
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000658 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000659
660 def _isnan(self):
661 """Returns whether the number is not actually one.
662
663 0 if a number
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000664 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000665 2 if sNaN
666 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000667 if self._is_special:
668 exp = self._exp
669 if exp == 'n':
670 return 1
671 elif exp == 'N':
672 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000673 return 0
674
675 def _isinfinity(self):
676 """Returns whether the number is infinite
677
678 0 if finite or not a number
679 1 if +INF
680 -1 if -INF
681 """
682 if self._exp == 'F':
683 if self._sign:
684 return -1
685 return 1
686 return 0
687
Facundo Batista353750c2007-09-13 18:13:15 +0000688 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000689 """Returns whether the number is not actually one.
690
691 if self, other are sNaN, signal
692 if self, other are NaN return nan
693 return 0
694
695 Done before operations.
696 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000697
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000698 self_is_nan = self._isnan()
699 if other is None:
700 other_is_nan = False
701 else:
702 other_is_nan = other._isnan()
703
704 if self_is_nan or other_is_nan:
705 if context is None:
706 context = getcontext()
707
708 if self_is_nan == 2:
709 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000710 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000711 if other_is_nan == 2:
712 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000713 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000714 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000715 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000716
Facundo Batista353750c2007-09-13 18:13:15 +0000717 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000718 return 0
719
Mark Dickinson2fc92632008-02-06 22:10:50 +0000720 def _compare_check_nans(self, other, context):
721 """Version of _check_nans used for the signaling comparisons
722 compare_signal, __le__, __lt__, __ge__, __gt__.
723
724 Signal InvalidOperation if either self or other is a (quiet
725 or signaling) NaN. Signaling NaNs take precedence over quiet
726 NaNs.
727
728 Return 0 if neither operand is a NaN.
729
730 """
731 if context is None:
732 context = getcontext()
733
734 if self._is_special or other._is_special:
735 if self.is_snan():
736 return context._raise_error(InvalidOperation,
737 'comparison involving sNaN',
738 self)
739 elif other.is_snan():
740 return context._raise_error(InvalidOperation,
741 'comparison involving sNaN',
742 other)
743 elif self.is_qnan():
744 return context._raise_error(InvalidOperation,
745 'comparison involving NaN',
746 self)
747 elif other.is_qnan():
748 return context._raise_error(InvalidOperation,
749 'comparison involving NaN',
750 other)
751 return 0
752
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000753 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000754 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000755
Facundo Batista1a191df2007-10-02 17:01:24 +0000756 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000757 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000758 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000759
Mark Dickinson2fc92632008-02-06 22:10:50 +0000760 def _cmp(self, other):
761 """Compare the two non-NaN decimal instances self and other.
762
763 Returns -1 if self < other, 0 if self == other and 1
764 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000765
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000766 if self._is_special or other._is_special:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000767 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000768
Facundo Batista353750c2007-09-13 18:13:15 +0000769 # check for zeros; note that cmp(0, -0) should return 0
770 if not self:
771 if not other:
772 return 0
773 else:
774 return -((-1)**other._sign)
775 if not other:
776 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000777
Facundo Batista59c58842007-04-10 12:58:45 +0000778 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000779 if other._sign < self._sign:
780 return -1
781 if self._sign < other._sign:
782 return 1
783
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000784 self_adjusted = self.adjusted()
785 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000786 if self_adjusted == other_adjusted:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000787 self_padded = self._int + '0'*(self._exp - other._exp)
788 other_padded = other._int + '0'*(other._exp - self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +0000789 return cmp(self_padded, other_padded) * (-1)**self._sign
790 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000791 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000792 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000793 return -((-1)**self._sign)
794
Mark Dickinson2fc92632008-02-06 22:10:50 +0000795 # Note: The Decimal standard doesn't cover rich comparisons for
796 # Decimals. In particular, the specification is silent on the
797 # subject of what should happen for a comparison involving a NaN.
798 # We take the following approach:
799 #
800 # == comparisons involving a NaN always return False
801 # != comparisons involving a NaN always return True
802 # <, >, <= and >= comparisons involving a (quiet or signaling)
803 # NaN signal InvalidOperation, and return False if the
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000804 # InvalidOperation is not trapped.
Mark Dickinson2fc92632008-02-06 22:10:50 +0000805 #
806 # This behavior is designed to conform as closely as possible to
807 # that specified by IEEE 754.
808
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000809 def __eq__(self, other):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000810 other = _convert_other(other)
811 if other is NotImplemented:
812 return other
813 if self.is_nan() or other.is_nan():
814 return False
815 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000816
817 def __ne__(self, other):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000818 other = _convert_other(other)
819 if other is NotImplemented:
820 return other
821 if self.is_nan() or other.is_nan():
822 return True
823 return self._cmp(other) != 0
824
825 def __lt__(self, other, context=None):
826 other = _convert_other(other)
827 if other is NotImplemented:
828 return other
829 ans = self._compare_check_nans(other, context)
830 if ans:
831 return False
832 return self._cmp(other) < 0
833
834 def __le__(self, other, context=None):
835 other = _convert_other(other)
836 if other is NotImplemented:
837 return other
838 ans = self._compare_check_nans(other, context)
839 if ans:
840 return False
841 return self._cmp(other) <= 0
842
843 def __gt__(self, other, context=None):
844 other = _convert_other(other)
845 if other is NotImplemented:
846 return other
847 ans = self._compare_check_nans(other, context)
848 if ans:
849 return False
850 return self._cmp(other) > 0
851
852 def __ge__(self, other, context=None):
853 other = _convert_other(other)
854 if other is NotImplemented:
855 return other
856 ans = self._compare_check_nans(other, context)
857 if ans:
858 return False
859 return self._cmp(other) >= 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000860
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000861 def compare(self, other, context=None):
862 """Compares one to another.
863
864 -1 => a < b
865 0 => a = b
866 1 => a > b
867 NaN => one is NaN
868 Like __cmp__, but returns Decimal instances.
869 """
Facundo Batista353750c2007-09-13 18:13:15 +0000870 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000871
Facundo Batista59c58842007-04-10 12:58:45 +0000872 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000873 if (self._is_special or other and other._is_special):
874 ans = self._check_nans(other, context)
875 if ans:
876 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000877
Mark Dickinson2fc92632008-02-06 22:10:50 +0000878 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000879
880 def __hash__(self):
881 """x.__hash__() <==> hash(x)"""
882 # Decimal integers must hash the same as the ints
Facundo Batista52b25792008-01-08 12:25:20 +0000883 #
884 # The hash of a nonspecial noninteger Decimal must depend only
885 # on the value of that Decimal, and not on its representation.
886 # For example: hash(Decimal("100E-1")) == hash(Decimal("10")).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000887 if self._is_special:
888 if self._isnan():
889 raise TypeError('Cannot hash a NaN value.')
890 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000891 if not self:
892 return 0
893 if self._isinteger():
894 op = _WorkRep(self.to_integral_value())
895 # to make computation feasible for Decimals with large
896 # exponent, we use the fact that hash(n) == hash(m) for
897 # any two nonzero integers n and m such that (i) n and m
898 # have the same sign, and (ii) n is congruent to m modulo
899 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
900 # hash((-1)**s*c*pow(10, e, 2**64-1).
901 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Facundo Batista52b25792008-01-08 12:25:20 +0000902 # The value of a nonzero nonspecial Decimal instance is
903 # faithfully represented by the triple consisting of its sign,
904 # its adjusted exponent, and its coefficient with trailing
905 # zeros removed.
906 return hash((self._sign,
907 self._exp+len(self._int),
908 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000909
910 def as_tuple(self):
911 """Represents the number as a triple tuple.
912
913 To show the internals exactly as they are.
914 """
Raymond Hettinger097a1902008-01-11 02:24:13 +0000915 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000916
917 def __repr__(self):
918 """Represents the number as an instance of Decimal."""
919 # Invariant: eval(repr(d)) == d
920 return 'Decimal("%s")' % str(self)
921
Facundo Batista353750c2007-09-13 18:13:15 +0000922 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000923 """Return string representation of the number in scientific notation.
924
925 Captures all of the information in the underlying representation.
926 """
927
Facundo Batista62edb712007-12-03 16:29:52 +0000928 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000929 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +0000930 if self._exp == 'F':
931 return sign + 'Infinity'
932 elif self._exp == 'n':
933 return sign + 'NaN' + self._int
934 else: # self._exp == 'N'
935 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000936
Facundo Batista62edb712007-12-03 16:29:52 +0000937 # number of digits of self._int to left of decimal point
938 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000939
Facundo Batista62edb712007-12-03 16:29:52 +0000940 # dotplace is number of digits of self._int to the left of the
941 # decimal point in the mantissa of the output string (that is,
942 # after adjusting the exponent)
943 if self._exp <= 0 and leftdigits > -6:
944 # no exponent required
945 dotplace = leftdigits
946 elif not eng:
947 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000948 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +0000949 elif self._int == '0':
950 # engineering notation, zero
951 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000952 else:
Facundo Batista62edb712007-12-03 16:29:52 +0000953 # engineering notation, nonzero
954 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000955
Facundo Batista62edb712007-12-03 16:29:52 +0000956 if dotplace <= 0:
957 intpart = '0'
958 fracpart = '.' + '0'*(-dotplace) + self._int
959 elif dotplace >= len(self._int):
960 intpart = self._int+'0'*(dotplace-len(self._int))
961 fracpart = ''
962 else:
963 intpart = self._int[:dotplace]
964 fracpart = '.' + self._int[dotplace:]
965 if leftdigits == dotplace:
966 exp = ''
967 else:
968 if context is None:
969 context = getcontext()
970 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
971
972 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000973
974 def to_eng_string(self, context=None):
975 """Convert to engineering-type string.
976
977 Engineering notation has an exponent which is a multiple of 3, so there
978 are up to 3 digits left of the decimal place.
979
980 Same rules for when in exponential and when as a value as in __str__.
981 """
Facundo Batista353750c2007-09-13 18:13:15 +0000982 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000983
984 def __neg__(self, context=None):
985 """Returns a copy with the sign switched.
986
987 Rounds, if it has reason.
988 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000989 if self._is_special:
990 ans = self._check_nans(context=context)
991 if ans:
992 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000993
994 if not self:
995 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000996 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000997 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000998 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000999
1000 if context is None:
1001 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001002 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001003
1004 def __pos__(self, context=None):
1005 """Returns a copy, unless it is a sNaN.
1006
1007 Rounds the number (if more then precision digits)
1008 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001009 if self._is_special:
1010 ans = self._check_nans(context=context)
1011 if ans:
1012 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001013
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001014 if not self:
1015 # + (-0) = 0
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001016 ans = self.copy_abs()
Facundo Batista353750c2007-09-13 18:13:15 +00001017 else:
1018 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001019
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001020 if context is None:
1021 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001022 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001023
Facundo Batistae64acfa2007-12-17 14:18:42 +00001024 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001025 """Returns the absolute value of self.
1026
Facundo Batistae64acfa2007-12-17 14:18:42 +00001027 If the keyword argument 'round' is false, do not round. The
1028 expression self.__abs__(round=False) is equivalent to
1029 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001030 """
Facundo Batistae64acfa2007-12-17 14:18:42 +00001031 if not round:
1032 return self.copy_abs()
1033
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001034 if self._is_special:
1035 ans = self._check_nans(context=context)
1036 if ans:
1037 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001038
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001039 if self._sign:
1040 ans = self.__neg__(context=context)
1041 else:
1042 ans = self.__pos__(context=context)
1043
1044 return ans
1045
1046 def __add__(self, other, context=None):
1047 """Returns self + other.
1048
1049 -INF + INF (or the reverse) cause InvalidOperation errors.
1050 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001051 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001052 if other is NotImplemented:
1053 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001054
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055 if context is None:
1056 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001057
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001058 if self._is_special or other._is_special:
1059 ans = self._check_nans(other, context)
1060 if ans:
1061 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001062
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001063 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001064 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001065 if self._sign != other._sign and other._isinfinity():
1066 return context._raise_error(InvalidOperation, '-INF + INF')
1067 return Decimal(self)
1068 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001069 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001070
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001071 exp = min(self._exp, other._exp)
1072 negativezero = 0
1073 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +00001074 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001075 negativezero = 1
1076
1077 if not self and not other:
1078 sign = min(self._sign, other._sign)
1079 if negativezero:
1080 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001081 ans = _dec_from_triple(sign, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001082 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001083 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001084 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001085 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001086 ans = other._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001087 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001088 return ans
1089 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001090 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001091 ans = self._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001092 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001093 return ans
1094
1095 op1 = _WorkRep(self)
1096 op2 = _WorkRep(other)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001097 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001098
1099 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001100 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001101 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001102 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001103 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001104 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001105 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001106 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001107 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001108 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001109 if op1.sign == 1:
1110 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001111 op1.sign, op2.sign = op2.sign, op1.sign
1112 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001113 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001114 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001115 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001116 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001117 op1.sign, op2.sign = (0, 0)
1118 else:
1119 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001120 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001121
Raymond Hettinger17931de2004-10-27 06:21:46 +00001122 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001123 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001124 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001125 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001126
1127 result.exp = op1.exp
1128 ans = Decimal(result)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001129 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001130 return ans
1131
1132 __radd__ = __add__
1133
1134 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001135 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001136 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001137 if other is NotImplemented:
1138 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001139
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001140 if self._is_special or other._is_special:
1141 ans = self._check_nans(other, context=context)
1142 if ans:
1143 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001144
Facundo Batista353750c2007-09-13 18:13:15 +00001145 # self - other is computed as self + other.copy_negate()
1146 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001147
1148 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001149 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001150 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001151 if other is NotImplemented:
1152 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001153
Facundo Batista353750c2007-09-13 18:13:15 +00001154 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001155
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001156 def __mul__(self, other, context=None):
1157 """Return self * other.
1158
1159 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1160 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001161 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001162 if other is NotImplemented:
1163 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001164
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001165 if context is None:
1166 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001167
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001168 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001169
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001170 if self._is_special or other._is_special:
1171 ans = self._check_nans(other, context)
1172 if ans:
1173 return ans
1174
1175 if self._isinfinity():
1176 if not other:
1177 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1178 return Infsign[resultsign]
1179
1180 if other._isinfinity():
1181 if not self:
1182 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1183 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001184
1185 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001186
1187 # Special case for multiplying by zero
1188 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001189 ans = _dec_from_triple(resultsign, '0', resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001190 # Fixing in case the exponent is out of bounds
1191 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001192 return ans
1193
1194 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001195 if self._int == '1':
1196 ans = _dec_from_triple(resultsign, other._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001197 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001198 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001199 if other._int == '1':
1200 ans = _dec_from_triple(resultsign, self._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001201 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001202 return ans
1203
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001204 op1 = _WorkRep(self)
1205 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001206
Facundo Batista72bc54f2007-11-23 17:59:00 +00001207 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001208 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001209
1210 return ans
1211 __rmul__ = __mul__
1212
1213 def __div__(self, other, context=None):
1214 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001215 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001216 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001217 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001218
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001219 if context is None:
1220 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001221
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001222 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001223
1224 if self._is_special or other._is_special:
1225 ans = self._check_nans(other, context)
1226 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001227 return ans
1228
1229 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001230 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001231
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001232 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001233 return Infsign[sign]
1234
1235 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001236 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001237 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001238
1239 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001240 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001241 if not self:
1242 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001243 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001244
Facundo Batistacce8df22007-09-18 16:53:18 +00001245 if not self:
1246 exp = self._exp - other._exp
1247 coeff = 0
1248 else:
1249 # OK, so neither = 0, INF or NaN
1250 shift = len(other._int) - len(self._int) + context.prec + 1
1251 exp = self._exp - other._exp - shift
1252 op1 = _WorkRep(self)
1253 op2 = _WorkRep(other)
1254 if shift >= 0:
1255 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1256 else:
1257 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1258 if remainder:
1259 # result is not exact; adjust to ensure correct rounding
1260 if coeff % 5 == 0:
1261 coeff += 1
1262 else:
1263 # result is exact; get as close to ideal exponent as possible
1264 ideal_exp = self._exp - other._exp
1265 while exp < ideal_exp and coeff % 10 == 0:
1266 coeff //= 10
1267 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001268
Facundo Batista72bc54f2007-11-23 17:59:00 +00001269 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001270 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001271
Facundo Batistacce8df22007-09-18 16:53:18 +00001272 __truediv__ = __div__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001273
Facundo Batistacce8df22007-09-18 16:53:18 +00001274 def _divide(self, other, context):
1275 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001276
Facundo Batistacce8df22007-09-18 16:53:18 +00001277 Assumes that neither self nor other is a NaN, that self is not
1278 infinite and that other is nonzero.
1279 """
1280 sign = self._sign ^ other._sign
1281 if other._isinfinity():
1282 ideal_exp = self._exp
1283 else:
1284 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001285
Facundo Batistacce8df22007-09-18 16:53:18 +00001286 expdiff = self.adjusted() - other.adjusted()
1287 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001288 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001289 self._rescale(ideal_exp, context.rounding))
1290 if expdiff <= context.prec:
1291 op1 = _WorkRep(self)
1292 op2 = _WorkRep(other)
1293 if op1.exp >= op2.exp:
1294 op1.int *= 10**(op1.exp - op2.exp)
1295 else:
1296 op2.int *= 10**(op2.exp - op1.exp)
1297 q, r = divmod(op1.int, op2.int)
1298 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001299 return (_dec_from_triple(sign, str(q), 0),
1300 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001301
Facundo Batistacce8df22007-09-18 16:53:18 +00001302 # Here the quotient is too large to be representable
1303 ans = context._raise_error(DivisionImpossible,
1304 'quotient too large in //, % or divmod')
1305 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001306
1307 def __rdiv__(self, other, context=None):
1308 """Swaps self/other and returns __div__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001309 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001310 if other is NotImplemented:
1311 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001312 return other.__div__(self, context=context)
1313 __rtruediv__ = __rdiv__
1314
1315 def __divmod__(self, other, context=None):
1316 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001317 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001318 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001319 other = _convert_other(other)
1320 if other is NotImplemented:
1321 return other
1322
1323 if context is None:
1324 context = getcontext()
1325
1326 ans = self._check_nans(other, context)
1327 if ans:
1328 return (ans, ans)
1329
1330 sign = self._sign ^ other._sign
1331 if self._isinfinity():
1332 if other._isinfinity():
1333 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1334 return ans, ans
1335 else:
1336 return (Infsign[sign],
1337 context._raise_error(InvalidOperation, 'INF % x'))
1338
1339 if not other:
1340 if not self:
1341 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1342 return ans, ans
1343 else:
1344 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1345 context._raise_error(InvalidOperation, 'x % 0'))
1346
1347 quotient, remainder = self._divide(other, context)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001348 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001349 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001350
1351 def __rdivmod__(self, other, context=None):
1352 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001353 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001354 if other is NotImplemented:
1355 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001356 return other.__divmod__(self, context=context)
1357
1358 def __mod__(self, other, context=None):
1359 """
1360 self % other
1361 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001362 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001363 if other is NotImplemented:
1364 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001365
Facundo Batistacce8df22007-09-18 16:53:18 +00001366 if context is None:
1367 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001368
Facundo Batistacce8df22007-09-18 16:53:18 +00001369 ans = self._check_nans(other, context)
1370 if ans:
1371 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001372
Facundo Batistacce8df22007-09-18 16:53:18 +00001373 if self._isinfinity():
1374 return context._raise_error(InvalidOperation, 'INF % x')
1375 elif not other:
1376 if self:
1377 return context._raise_error(InvalidOperation, 'x % 0')
1378 else:
1379 return context._raise_error(DivisionUndefined, '0 % 0')
1380
1381 remainder = self._divide(other, context)[1]
Facundo Batistae64acfa2007-12-17 14:18:42 +00001382 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001383 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001384
1385 def __rmod__(self, other, context=None):
1386 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001387 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001388 if other is NotImplemented:
1389 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001390 return other.__mod__(self, context=context)
1391
1392 def remainder_near(self, other, context=None):
1393 """
1394 Remainder nearest to 0- abs(remainder-near) <= other/2
1395 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001396 if context is None:
1397 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001398
Facundo Batista353750c2007-09-13 18:13:15 +00001399 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001400
Facundo Batista353750c2007-09-13 18:13:15 +00001401 ans = self._check_nans(other, context)
1402 if ans:
1403 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001404
Facundo Batista353750c2007-09-13 18:13:15 +00001405 # self == +/-infinity -> InvalidOperation
1406 if self._isinfinity():
1407 return context._raise_error(InvalidOperation,
1408 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001409
Facundo Batista353750c2007-09-13 18:13:15 +00001410 # other == 0 -> either InvalidOperation or DivisionUndefined
1411 if not other:
1412 if self:
1413 return context._raise_error(InvalidOperation,
1414 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001415 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001416 return context._raise_error(DivisionUndefined,
1417 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001418
Facundo Batista353750c2007-09-13 18:13:15 +00001419 # other = +/-infinity -> remainder = self
1420 if other._isinfinity():
1421 ans = Decimal(self)
1422 return ans._fix(context)
1423
1424 # self = 0 -> remainder = self, with ideal exponent
1425 ideal_exponent = min(self._exp, other._exp)
1426 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001427 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001428 return ans._fix(context)
1429
1430 # catch most cases of large or small quotient
1431 expdiff = self.adjusted() - other.adjusted()
1432 if expdiff >= context.prec + 1:
1433 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001434 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001435 if expdiff <= -2:
1436 # expdiff <= -2 => abs(self/other) < 0.1
1437 ans = self._rescale(ideal_exponent, context.rounding)
1438 return ans._fix(context)
1439
1440 # adjust both arguments to have the same exponent, then divide
1441 op1 = _WorkRep(self)
1442 op2 = _WorkRep(other)
1443 if op1.exp >= op2.exp:
1444 op1.int *= 10**(op1.exp - op2.exp)
1445 else:
1446 op2.int *= 10**(op2.exp - op1.exp)
1447 q, r = divmod(op1.int, op2.int)
1448 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1449 # 10**ideal_exponent. Apply correction to ensure that
1450 # abs(remainder) <= abs(other)/2
1451 if 2*r + (q&1) > op2.int:
1452 r -= op2.int
1453 q += 1
1454
1455 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001456 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001457
1458 # result has same sign as self unless r is negative
1459 sign = self._sign
1460 if r < 0:
1461 sign = 1-sign
1462 r = -r
1463
Facundo Batista72bc54f2007-11-23 17:59:00 +00001464 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001465 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001466
1467 def __floordiv__(self, other, context=None):
1468 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001469 other = _convert_other(other)
1470 if other is NotImplemented:
1471 return other
1472
1473 if context is None:
1474 context = getcontext()
1475
1476 ans = self._check_nans(other, context)
1477 if ans:
1478 return ans
1479
1480 if self._isinfinity():
1481 if other._isinfinity():
1482 return context._raise_error(InvalidOperation, 'INF // INF')
1483 else:
1484 return Infsign[self._sign ^ other._sign]
1485
1486 if not other:
1487 if self:
1488 return context._raise_error(DivisionByZero, 'x // 0',
1489 self._sign ^ other._sign)
1490 else:
1491 return context._raise_error(DivisionUndefined, '0 // 0')
1492
1493 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001494
1495 def __rfloordiv__(self, other, context=None):
1496 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001497 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001498 if other is NotImplemented:
1499 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001500 return other.__floordiv__(self, context=context)
1501
1502 def __float__(self):
1503 """Float representation."""
1504 return float(str(self))
1505
1506 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001507 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001508 if self._is_special:
1509 if self._isnan():
1510 context = getcontext()
1511 return context._raise_error(InvalidContext)
1512 elif self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001513 raise OverflowError("Cannot convert infinity to long")
Facundo Batista353750c2007-09-13 18:13:15 +00001514 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001515 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001516 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001517 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001518 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001519
Raymond Hettinger5a053642008-01-24 19:05:29 +00001520 __trunc__ = __int__
1521
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001522 @property
1523 def real(self):
1524 return self
1525
1526 @property
1527 def imag(self):
1528 return Decimal(0)
1529
1530 def conjugate(self):
1531 return self
1532
1533 def __complex__(self):
1534 return complex(float(self))
1535
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001536 def __long__(self):
1537 """Converts to a long.
1538
1539 Equivalent to long(int(self))
1540 """
1541 return long(self.__int__())
1542
Facundo Batista353750c2007-09-13 18:13:15 +00001543 def _fix_nan(self, context):
1544 """Decapitate the payload of a NaN to fit the context"""
1545 payload = self._int
1546
1547 # maximum length of payload is precision if _clamp=0,
1548 # precision-1 if _clamp=1.
1549 max_payload_len = context.prec - context._clamp
1550 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001551 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1552 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001553 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001554
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001555 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001556 """Round if it is necessary to keep self within prec precision.
1557
1558 Rounds and fixes the exponent. Does not raise on a sNaN.
1559
1560 Arguments:
1561 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001562 context - context used.
1563 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001564
Facundo Batista353750c2007-09-13 18:13:15 +00001565 if self._is_special:
1566 if self._isnan():
1567 # decapitate payload if necessary
1568 return self._fix_nan(context)
1569 else:
1570 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001571 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001572
Facundo Batista353750c2007-09-13 18:13:15 +00001573 # if self is zero then exponent should be between Etiny and
1574 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1575 Etiny = context.Etiny()
1576 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001577 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001578 exp_max = [context.Emax, Etop][context._clamp]
1579 new_exp = min(max(self._exp, Etiny), exp_max)
1580 if new_exp != self._exp:
1581 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001582 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001583 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001584 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001585
1586 # exp_min is the smallest allowable exponent of the result,
1587 # equal to max(self.adjusted()-context.prec+1, Etiny)
1588 exp_min = len(self._int) + self._exp - context.prec
1589 if exp_min > Etop:
1590 # overflow: exp_min > Etop iff self.adjusted() > Emax
1591 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001592 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001593 return context._raise_error(Overflow, 'above Emax', self._sign)
1594 self_is_subnormal = exp_min < Etiny
1595 if self_is_subnormal:
1596 context._raise_error(Subnormal)
1597 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001598
Facundo Batista353750c2007-09-13 18:13:15 +00001599 # round if self has too many digits
1600 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001601 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001602 digits = len(self._int) + self._exp - exp_min
1603 if digits < 0:
1604 self = _dec_from_triple(self._sign, '1', exp_min-1)
1605 digits = 0
1606 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1607 changed = this_function(digits)
1608 coeff = self._int[:digits] or '0'
1609 if changed == 1:
1610 coeff = str(int(coeff)+1)
1611 ans = _dec_from_triple(self._sign, coeff, exp_min)
1612
1613 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001614 context._raise_error(Inexact)
1615 if self_is_subnormal:
1616 context._raise_error(Underflow)
1617 if not ans:
1618 # raise Clamped on underflow to 0
1619 context._raise_error(Clamped)
1620 elif len(ans._int) == context.prec+1:
1621 # we get here only if rescaling rounds the
1622 # cofficient up to exactly 10**context.prec
1623 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001624 ans = _dec_from_triple(ans._sign,
1625 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001626 else:
1627 # Inexact and Rounded have already been raised
1628 ans = context._raise_error(Overflow, 'above Emax',
1629 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001630 return ans
1631
Facundo Batista353750c2007-09-13 18:13:15 +00001632 # fold down if _clamp == 1 and self has too few digits
1633 if context._clamp == 1 and self._exp > Etop:
1634 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001635 self_padded = self._int + '0'*(self._exp - Etop)
1636 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001637
Facundo Batista353750c2007-09-13 18:13:15 +00001638 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001639 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001640
1641 _pick_rounding_function = {}
1642
Facundo Batista353750c2007-09-13 18:13:15 +00001643 # for each of the rounding functions below:
1644 # self is a finite, nonzero Decimal
1645 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001646 #
1647 # each function returns either -1, 0, or 1, as follows:
1648 # 1 indicates that self should be rounded up (away from zero)
1649 # 0 indicates that self should be truncated, and that all the
1650 # digits to be truncated are zeros (so the value is unchanged)
1651 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001652
1653 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001654 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001655 if _all_zeros(self._int, prec):
1656 return 0
1657 else:
1658 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001659
Facundo Batista353750c2007-09-13 18:13:15 +00001660 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001661 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001662 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001663
Facundo Batista353750c2007-09-13 18:13:15 +00001664 def _round_half_up(self, prec):
1665 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001666 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001667 return 1
1668 elif _all_zeros(self._int, prec):
1669 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001670 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001671 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001672
1673 def _round_half_down(self, prec):
1674 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001675 if _exact_half(self._int, prec):
1676 return -1
1677 else:
1678 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001679
1680 def _round_half_even(self, prec):
1681 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001682 if _exact_half(self._int, prec) and \
1683 (prec == 0 or self._int[prec-1] in '02468'):
1684 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001685 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001686 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001687
1688 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001689 """Rounds up (not away from 0 if negative.)"""
1690 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001691 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001692 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001693 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001694
Facundo Batista353750c2007-09-13 18:13:15 +00001695 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001696 """Rounds down (not towards 0 if negative)"""
1697 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001698 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001699 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001700 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001701
Facundo Batista353750c2007-09-13 18:13:15 +00001702 def _round_05up(self, prec):
1703 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001704 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001705 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001706 else:
1707 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001708
Facundo Batista353750c2007-09-13 18:13:15 +00001709 def fma(self, other, third, context=None):
1710 """Fused multiply-add.
1711
1712 Returns self*other+third with no rounding of the intermediate
1713 product self*other.
1714
1715 self and other are multiplied together, with no rounding of
1716 the result. The third operand is then added to the result,
1717 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001718 """
Facundo Batista353750c2007-09-13 18:13:15 +00001719
1720 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001721
1722 # compute product; raise InvalidOperation if either operand is
1723 # a signaling NaN or if the product is zero times infinity.
1724 if self._is_special or other._is_special:
1725 if context is None:
1726 context = getcontext()
1727 if self._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001728 return context._raise_error(InvalidOperation, 'sNaN', self)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001729 if other._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001730 return context._raise_error(InvalidOperation, 'sNaN', other)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001731 if self._exp == 'n':
1732 product = self
1733 elif other._exp == 'n':
1734 product = other
1735 elif self._exp == 'F':
1736 if not other:
1737 return context._raise_error(InvalidOperation,
1738 'INF * 0 in fma')
1739 product = Infsign[self._sign ^ other._sign]
1740 elif other._exp == 'F':
1741 if not self:
1742 return context._raise_error(InvalidOperation,
1743 '0 * INF in fma')
1744 product = Infsign[self._sign ^ other._sign]
1745 else:
1746 product = _dec_from_triple(self._sign ^ other._sign,
1747 str(int(self._int) * int(other._int)),
1748 self._exp + other._exp)
1749
Facundo Batista353750c2007-09-13 18:13:15 +00001750 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001751 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001752
Facundo Batista353750c2007-09-13 18:13:15 +00001753 def _power_modulo(self, other, modulo, context=None):
1754 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001755
Facundo Batista353750c2007-09-13 18:13:15 +00001756 # if can't convert other and modulo to Decimal, raise
1757 # TypeError; there's no point returning NotImplemented (no
1758 # equivalent of __rpow__ for three argument pow)
1759 other = _convert_other(other, raiseit=True)
1760 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001761
Facundo Batista353750c2007-09-13 18:13:15 +00001762 if context is None:
1763 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001764
Facundo Batista353750c2007-09-13 18:13:15 +00001765 # deal with NaNs: if there are any sNaNs then first one wins,
1766 # (i.e. behaviour for NaNs is identical to that of fma)
1767 self_is_nan = self._isnan()
1768 other_is_nan = other._isnan()
1769 modulo_is_nan = modulo._isnan()
1770 if self_is_nan or other_is_nan or modulo_is_nan:
1771 if self_is_nan == 2:
1772 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001773 self)
Facundo Batista353750c2007-09-13 18:13:15 +00001774 if other_is_nan == 2:
1775 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001776 other)
Facundo Batista353750c2007-09-13 18:13:15 +00001777 if modulo_is_nan == 2:
1778 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001779 modulo)
Facundo Batista353750c2007-09-13 18:13:15 +00001780 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001781 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001782 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001783 return other._fix_nan(context)
1784 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001785
Facundo Batista353750c2007-09-13 18:13:15 +00001786 # check inputs: we apply same restrictions as Python's pow()
1787 if not (self._isinteger() and
1788 other._isinteger() and
1789 modulo._isinteger()):
1790 return context._raise_error(InvalidOperation,
1791 'pow() 3rd argument not allowed '
1792 'unless all arguments are integers')
1793 if other < 0:
1794 return context._raise_error(InvalidOperation,
1795 'pow() 2nd argument cannot be '
1796 'negative when 3rd argument specified')
1797 if not modulo:
1798 return context._raise_error(InvalidOperation,
1799 'pow() 3rd argument cannot be 0')
1800
1801 # additional restriction for decimal: the modulus must be less
1802 # than 10**prec in absolute value
1803 if modulo.adjusted() >= context.prec:
1804 return context._raise_error(InvalidOperation,
1805 'insufficient precision: pow() 3rd '
1806 'argument must not have more than '
1807 'precision digits')
1808
1809 # define 0**0 == NaN, for consistency with two-argument pow
1810 # (even though it hurts!)
1811 if not other and not self:
1812 return context._raise_error(InvalidOperation,
1813 'at least one of pow() 1st argument '
1814 'and 2nd argument must be nonzero ;'
1815 '0**0 is not defined')
1816
1817 # compute sign of result
1818 if other._iseven():
1819 sign = 0
1820 else:
1821 sign = self._sign
1822
1823 # convert modulo to a Python integer, and self and other to
1824 # Decimal integers (i.e. force their exponents to be >= 0)
1825 modulo = abs(int(modulo))
1826 base = _WorkRep(self.to_integral_value())
1827 exponent = _WorkRep(other.to_integral_value())
1828
1829 # compute result using integer pow()
1830 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1831 for i in xrange(exponent.exp):
1832 base = pow(base, 10, modulo)
1833 base = pow(base, exponent.int, modulo)
1834
Facundo Batista72bc54f2007-11-23 17:59:00 +00001835 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001836
1837 def _power_exact(self, other, p):
1838 """Attempt to compute self**other exactly.
1839
1840 Given Decimals self and other and an integer p, attempt to
1841 compute an exact result for the power self**other, with p
1842 digits of precision. Return None if self**other is not
1843 exactly representable in p digits.
1844
1845 Assumes that elimination of special cases has already been
1846 performed: self and other must both be nonspecial; self must
1847 be positive and not numerically equal to 1; other must be
1848 nonzero. For efficiency, other._exp should not be too large,
1849 so that 10**abs(other._exp) is a feasible calculation."""
1850
1851 # In the comments below, we write x for the value of self and
1852 # y for the value of other. Write x = xc*10**xe and y =
1853 # yc*10**ye.
1854
1855 # The main purpose of this method is to identify the *failure*
1856 # of x**y to be exactly representable with as little effort as
1857 # possible. So we look for cheap and easy tests that
1858 # eliminate the possibility of x**y being exact. Only if all
1859 # these tests are passed do we go on to actually compute x**y.
1860
1861 # Here's the main idea. First normalize both x and y. We
1862 # express y as a rational m/n, with m and n relatively prime
1863 # and n>0. Then for x**y to be exactly representable (at
1864 # *any* precision), xc must be the nth power of a positive
1865 # integer and xe must be divisible by n. If m is negative
1866 # then additionally xc must be a power of either 2 or 5, hence
1867 # a power of 2**n or 5**n.
1868 #
1869 # There's a limit to how small |y| can be: if y=m/n as above
1870 # then:
1871 #
1872 # (1) if xc != 1 then for the result to be representable we
1873 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1874 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1875 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1876 # representable.
1877 #
1878 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1879 # |y| < 1/|xe| then the result is not representable.
1880 #
1881 # Note that since x is not equal to 1, at least one of (1) and
1882 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1883 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1884 #
1885 # There's also a limit to how large y can be, at least if it's
1886 # positive: the normalized result will have coefficient xc**y,
1887 # so if it's representable then xc**y < 10**p, and y <
1888 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1889 # not exactly representable.
1890
1891 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1892 # so |y| < 1/xe and the result is not representable.
1893 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1894 # < 1/nbits(xc).
1895
1896 x = _WorkRep(self)
1897 xc, xe = x.int, x.exp
1898 while xc % 10 == 0:
1899 xc //= 10
1900 xe += 1
1901
1902 y = _WorkRep(other)
1903 yc, ye = y.int, y.exp
1904 while yc % 10 == 0:
1905 yc //= 10
1906 ye += 1
1907
1908 # case where xc == 1: result is 10**(xe*y), with xe*y
1909 # required to be an integer
1910 if xc == 1:
1911 if ye >= 0:
1912 exponent = xe*yc*10**ye
1913 else:
1914 exponent, remainder = divmod(xe*yc, 10**-ye)
1915 if remainder:
1916 return None
1917 if y.sign == 1:
1918 exponent = -exponent
1919 # if other is a nonnegative integer, use ideal exponent
1920 if other._isinteger() and other._sign == 0:
1921 ideal_exponent = self._exp*int(other)
1922 zeros = min(exponent-ideal_exponent, p-1)
1923 else:
1924 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001925 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001926
1927 # case where y is negative: xc must be either a power
1928 # of 2 or a power of 5.
1929 if y.sign == 1:
1930 last_digit = xc % 10
1931 if last_digit in (2,4,6,8):
1932 # quick test for power of 2
1933 if xc & -xc != xc:
1934 return None
1935 # now xc is a power of 2; e is its exponent
1936 e = _nbits(xc)-1
1937 # find e*y and xe*y; both must be integers
1938 if ye >= 0:
1939 y_as_int = yc*10**ye
1940 e = e*y_as_int
1941 xe = xe*y_as_int
1942 else:
1943 ten_pow = 10**-ye
1944 e, remainder = divmod(e*yc, ten_pow)
1945 if remainder:
1946 return None
1947 xe, remainder = divmod(xe*yc, ten_pow)
1948 if remainder:
1949 return None
1950
1951 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1952 return None
1953 xc = 5**e
1954
1955 elif last_digit == 5:
1956 # e >= log_5(xc) if xc is a power of 5; we have
1957 # equality all the way up to xc=5**2658
1958 e = _nbits(xc)*28//65
1959 xc, remainder = divmod(5**e, xc)
1960 if remainder:
1961 return None
1962 while xc % 5 == 0:
1963 xc //= 5
1964 e -= 1
1965 if ye >= 0:
1966 y_as_integer = yc*10**ye
1967 e = e*y_as_integer
1968 xe = xe*y_as_integer
1969 else:
1970 ten_pow = 10**-ye
1971 e, remainder = divmod(e*yc, ten_pow)
1972 if remainder:
1973 return None
1974 xe, remainder = divmod(xe*yc, ten_pow)
1975 if remainder:
1976 return None
1977 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1978 return None
1979 xc = 2**e
1980 else:
1981 return None
1982
1983 if xc >= 10**p:
1984 return None
1985 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00001986 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00001987
1988 # now y is positive; find m and n such that y = m/n
1989 if ye >= 0:
1990 m, n = yc*10**ye, 1
1991 else:
1992 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1993 return None
1994 xc_bits = _nbits(xc)
1995 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1996 return None
1997 m, n = yc, 10**(-ye)
1998 while m % 2 == n % 2 == 0:
1999 m //= 2
2000 n //= 2
2001 while m % 5 == n % 5 == 0:
2002 m //= 5
2003 n //= 5
2004
2005 # compute nth root of xc*10**xe
2006 if n > 1:
2007 # if 1 < xc < 2**n then xc isn't an nth power
2008 if xc != 1 and xc_bits <= n:
2009 return None
2010
2011 xe, rem = divmod(xe, n)
2012 if rem != 0:
2013 return None
2014
2015 # compute nth root of xc using Newton's method
2016 a = 1L << -(-_nbits(xc)//n) # initial estimate
2017 while True:
2018 q, r = divmod(xc, a**(n-1))
2019 if a <= q:
2020 break
2021 else:
2022 a = (a*(n-1) + q)//n
2023 if not (a == q and r == 0):
2024 return None
2025 xc = a
2026
2027 # now xc*10**xe is the nth root of the original xc*10**xe
2028 # compute mth power of xc*10**xe
2029
2030 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2031 # 10**p and the result is not representable.
2032 if xc > 1 and m > p*100//_log10_lb(xc):
2033 return None
2034 xc = xc**m
2035 xe *= m
2036 if xc > 10**p:
2037 return None
2038
2039 # by this point the result *is* exactly representable
2040 # adjust the exponent to get as close as possible to the ideal
2041 # exponent, if necessary
2042 str_xc = str(xc)
2043 if other._isinteger() and other._sign == 0:
2044 ideal_exponent = self._exp*int(other)
2045 zeros = min(xe-ideal_exponent, p-len(str_xc))
2046 else:
2047 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002048 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00002049
2050 def __pow__(self, other, modulo=None, context=None):
2051 """Return self ** other [ % modulo].
2052
2053 With two arguments, compute self**other.
2054
2055 With three arguments, compute (self**other) % modulo. For the
2056 three argument form, the following restrictions on the
2057 arguments hold:
2058
2059 - all three arguments must be integral
2060 - other must be nonnegative
2061 - either self or other (or both) must be nonzero
2062 - modulo must be nonzero and must have at most p digits,
2063 where p is the context precision.
2064
2065 If any of these restrictions is violated the InvalidOperation
2066 flag is raised.
2067
2068 The result of pow(self, other, modulo) is identical to the
2069 result that would be obtained by computing (self**other) %
2070 modulo with unbounded precision, but is computed more
2071 efficiently. It is always exact.
2072 """
2073
2074 if modulo is not None:
2075 return self._power_modulo(other, modulo, context)
2076
2077 other = _convert_other(other)
2078 if other is NotImplemented:
2079 return other
2080
2081 if context is None:
2082 context = getcontext()
2083
2084 # either argument is a NaN => result is NaN
2085 ans = self._check_nans(other, context)
2086 if ans:
2087 return ans
2088
2089 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2090 if not other:
2091 if not self:
2092 return context._raise_error(InvalidOperation, '0 ** 0')
2093 else:
2094 return Dec_p1
2095
2096 # result has sign 1 iff self._sign is 1 and other is an odd integer
2097 result_sign = 0
2098 if self._sign == 1:
2099 if other._isinteger():
2100 if not other._iseven():
2101 result_sign = 1
2102 else:
2103 # -ve**noninteger = NaN
2104 # (-0)**noninteger = 0**noninteger
2105 if self:
2106 return context._raise_error(InvalidOperation,
2107 'x ** y with x negative and y not an integer')
2108 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002109 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002110
2111 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2112 if not self:
2113 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002114 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002115 else:
2116 return Infsign[result_sign]
2117
2118 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002119 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002120 if other._sign == 0:
2121 return Infsign[result_sign]
2122 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002123 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002124
Facundo Batista353750c2007-09-13 18:13:15 +00002125 # 1**other = 1, but the choice of exponent and the flags
2126 # depend on the exponent of self, and on whether other is a
2127 # positive integer, a negative integer, or neither
2128 if self == Dec_p1:
2129 if other._isinteger():
2130 # exp = max(self._exp*max(int(other), 0),
2131 # 1-context.prec) but evaluating int(other) directly
2132 # is dangerous until we know other is small (other
2133 # could be 1e999999999)
2134 if other._sign == 1:
2135 multiplier = 0
2136 elif other > context.prec:
2137 multiplier = context.prec
2138 else:
2139 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002140
Facundo Batista353750c2007-09-13 18:13:15 +00002141 exp = self._exp * multiplier
2142 if exp < 1-context.prec:
2143 exp = 1-context.prec
2144 context._raise_error(Rounded)
2145 else:
2146 context._raise_error(Inexact)
2147 context._raise_error(Rounded)
2148 exp = 1-context.prec
2149
Facundo Batista72bc54f2007-11-23 17:59:00 +00002150 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002151
2152 # compute adjusted exponent of self
2153 self_adj = self.adjusted()
2154
2155 # self ** infinity is infinity if self > 1, 0 if self < 1
2156 # self ** -infinity is infinity if self < 1, 0 if self > 1
2157 if other._isinfinity():
2158 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002159 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002160 else:
2161 return Infsign[result_sign]
2162
2163 # from here on, the result always goes through the call
2164 # to _fix at the end of this function.
2165 ans = None
2166
2167 # crude test to catch cases of extreme overflow/underflow. If
2168 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2169 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2170 # self**other >= 10**(Emax+1), so overflow occurs. The test
2171 # for underflow is similar.
2172 bound = self._log10_exp_bound() + other.adjusted()
2173 if (self_adj >= 0) == (other._sign == 0):
2174 # self > 1 and other +ve, or self < 1 and other -ve
2175 # possibility of overflow
2176 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002177 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002178 else:
2179 # self > 1 and other -ve, or self < 1 and other +ve
2180 # possibility of underflow to 0
2181 Etiny = context.Etiny()
2182 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002183 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002184
2185 # try for an exact result with precision +1
2186 if ans is None:
2187 ans = self._power_exact(other, context.prec + 1)
2188 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002189 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002190
2191 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2192 if ans is None:
2193 p = context.prec
2194 x = _WorkRep(self)
2195 xc, xe = x.int, x.exp
2196 y = _WorkRep(other)
2197 yc, ye = y.int, y.exp
2198 if y.sign == 1:
2199 yc = -yc
2200
2201 # compute correctly rounded result: start with precision +3,
2202 # then increase precision until result is unambiguously roundable
2203 extra = 3
2204 while True:
2205 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2206 if coeff % (5*10**(len(str(coeff))-p-1)):
2207 break
2208 extra += 3
2209
Facundo Batista72bc54f2007-11-23 17:59:00 +00002210 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002211
2212 # the specification says that for non-integer other we need to
2213 # raise Inexact, even when the result is actually exact. In
2214 # the same way, we need to raise Underflow here if the result
2215 # is subnormal. (The call to _fix will take care of raising
2216 # Rounded and Subnormal, as usual.)
2217 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002218 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002219 # pad with zeros up to length context.prec+1 if necessary
2220 if len(ans._int) <= context.prec:
2221 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002222 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2223 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002224 if ans.adjusted() < context.Emin:
2225 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002226
Facundo Batista353750c2007-09-13 18:13:15 +00002227 # unlike exp, ln and log10, the power function respects the
2228 # rounding mode; no need to use ROUND_HALF_EVEN here
2229 ans = ans._fix(context)
2230 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002231
2232 def __rpow__(self, other, context=None):
2233 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002234 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002235 if other is NotImplemented:
2236 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002237 return other.__pow__(self, context=context)
2238
2239 def normalize(self, context=None):
2240 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002241
Facundo Batista353750c2007-09-13 18:13:15 +00002242 if context is None:
2243 context = getcontext()
2244
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002245 if self._is_special:
2246 ans = self._check_nans(context=context)
2247 if ans:
2248 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002249
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002250 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002251 if dup._isinfinity():
2252 return dup
2253
2254 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002255 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002256 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002257 end = len(dup._int)
2258 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002259 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002260 exp += 1
2261 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002262 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002263
Facundo Batistabd2fe832007-09-13 18:42:09 +00002264 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002265 """Quantize self so its exponent is the same as that of exp.
2266
2267 Similar to self._rescale(exp._exp) but with error checking.
2268 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002269 exp = _convert_other(exp, raiseit=True)
2270
Facundo Batista353750c2007-09-13 18:13:15 +00002271 if context is None:
2272 context = getcontext()
2273 if rounding is None:
2274 rounding = context.rounding
2275
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002276 if self._is_special or exp._is_special:
2277 ans = self._check_nans(exp, context)
2278 if ans:
2279 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002280
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002281 if exp._isinfinity() or self._isinfinity():
2282 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002283 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002284 return context._raise_error(InvalidOperation,
2285 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002286
Facundo Batistabd2fe832007-09-13 18:42:09 +00002287 # if we're not watching exponents, do a simple rescale
2288 if not watchexp:
2289 ans = self._rescale(exp._exp, rounding)
2290 # raise Inexact and Rounded where appropriate
2291 if ans._exp > self._exp:
2292 context._raise_error(Rounded)
2293 if ans != self:
2294 context._raise_error(Inexact)
2295 return ans
2296
Facundo Batista353750c2007-09-13 18:13:15 +00002297 # exp._exp should be between Etiny and Emax
2298 if not (context.Etiny() <= exp._exp <= context.Emax):
2299 return context._raise_error(InvalidOperation,
2300 'target exponent out of bounds in quantize')
2301
2302 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002303 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002304 return ans._fix(context)
2305
2306 self_adjusted = self.adjusted()
2307 if self_adjusted > context.Emax:
2308 return context._raise_error(InvalidOperation,
2309 'exponent of quantize result too large for current context')
2310 if self_adjusted - exp._exp + 1 > context.prec:
2311 return context._raise_error(InvalidOperation,
2312 'quantize result has too many digits for current context')
2313
2314 ans = self._rescale(exp._exp, rounding)
2315 if ans.adjusted() > context.Emax:
2316 return context._raise_error(InvalidOperation,
2317 'exponent of quantize result too large for current context')
2318 if len(ans._int) > context.prec:
2319 return context._raise_error(InvalidOperation,
2320 'quantize result has too many digits for current context')
2321
2322 # raise appropriate flags
2323 if ans._exp > self._exp:
2324 context._raise_error(Rounded)
2325 if ans != self:
2326 context._raise_error(Inexact)
2327 if ans and ans.adjusted() < context.Emin:
2328 context._raise_error(Subnormal)
2329
2330 # call to fix takes care of any necessary folddown
2331 ans = ans._fix(context)
2332 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002333
2334 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002335 """Return True if self and other have the same exponent; otherwise
2336 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002337
Facundo Batista1a191df2007-10-02 17:01:24 +00002338 If either operand is a special value, the following rules are used:
2339 * return True if both operands are infinities
2340 * return True if both operands are NaNs
2341 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002342 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002343 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002344 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002345 return (self.is_nan() and other.is_nan() or
2346 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002347 return self._exp == other._exp
2348
Facundo Batista353750c2007-09-13 18:13:15 +00002349 def _rescale(self, exp, rounding):
2350 """Rescale self so that the exponent is exp, either by padding with zeros
2351 or by truncating digits, using the given rounding mode.
2352
2353 Specials are returned without change. This operation is
2354 quiet: it raises no flags, and uses no information from the
2355 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002356
2357 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002358 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002359 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002360 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002361 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002362 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002363 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002364
Facundo Batista353750c2007-09-13 18:13:15 +00002365 if self._exp >= exp:
2366 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002367 return _dec_from_triple(self._sign,
2368 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002369
Facundo Batista353750c2007-09-13 18:13:15 +00002370 # too many digits; round and lose data. If self.adjusted() <
2371 # exp-1, replace self by 10**(exp-1) before rounding
2372 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002373 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002374 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002375 digits = 0
2376 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002377 changed = this_function(digits)
2378 coeff = self._int[:digits] or '0'
2379 if changed == 1:
2380 coeff = str(int(coeff)+1)
2381 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002382
Facundo Batista353750c2007-09-13 18:13:15 +00002383 def to_integral_exact(self, rounding=None, context=None):
2384 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002385
Facundo Batista353750c2007-09-13 18:13:15 +00002386 If no rounding mode is specified, take the rounding mode from
2387 the context. This method raises the Rounded and Inexact flags
2388 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002389
Facundo Batista353750c2007-09-13 18:13:15 +00002390 See also: to_integral_value, which does exactly the same as
2391 this method except that it doesn't raise Inexact or Rounded.
2392 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002393 if self._is_special:
2394 ans = self._check_nans(context=context)
2395 if ans:
2396 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002397 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002398 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002399 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002400 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002401 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002402 if context is None:
2403 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002404 if rounding is None:
2405 rounding = context.rounding
2406 context._raise_error(Rounded)
2407 ans = self._rescale(0, rounding)
2408 if ans != self:
2409 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002410 return ans
2411
Facundo Batista353750c2007-09-13 18:13:15 +00002412 def to_integral_value(self, rounding=None, context=None):
2413 """Rounds to the nearest integer, without raising inexact, rounded."""
2414 if context is None:
2415 context = getcontext()
2416 if rounding is None:
2417 rounding = context.rounding
2418 if self._is_special:
2419 ans = self._check_nans(context=context)
2420 if ans:
2421 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002422 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002423 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002424 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002425 else:
2426 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002427
Facundo Batista353750c2007-09-13 18:13:15 +00002428 # the method name changed, but we provide also the old one, for compatibility
2429 to_integral = to_integral_value
2430
2431 def sqrt(self, context=None):
2432 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002433 if self._is_special:
2434 ans = self._check_nans(context=context)
2435 if ans:
2436 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002437
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002438 if self._isinfinity() and self._sign == 0:
2439 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002440
2441 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002442 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002443 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002444 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002445
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002446 if context is None:
2447 context = getcontext()
2448
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002449 if self._sign == 1:
2450 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2451
Facundo Batista353750c2007-09-13 18:13:15 +00002452 # At this point self represents a positive number. Let p be
2453 # the desired precision and express self in the form c*100**e
2454 # with c a positive real number and e an integer, c and e
2455 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2456 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2457 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2458 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2459 # the closest integer to sqrt(c) with the even integer chosen
2460 # in the case of a tie.
2461 #
2462 # To ensure correct rounding in all cases, we use the
2463 # following trick: we compute the square root to an extra
2464 # place (precision p+1 instead of precision p), rounding down.
2465 # Then, if the result is inexact and its last digit is 0 or 5,
2466 # we increase the last digit to 1 or 6 respectively; if it's
2467 # exact we leave the last digit alone. Now the final round to
2468 # p places (or fewer in the case of underflow) will round
2469 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002470
Facundo Batista353750c2007-09-13 18:13:15 +00002471 # use an extra digit of precision
2472 prec = context.prec+1
2473
2474 # write argument in the form c*100**e where e = self._exp//2
2475 # is the 'ideal' exponent, to be used if the square root is
2476 # exactly representable. l is the number of 'digits' of c in
2477 # base 100, so that 100**(l-1) <= c < 100**l.
2478 op = _WorkRep(self)
2479 e = op.exp >> 1
2480 if op.exp & 1:
2481 c = op.int * 10
2482 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002483 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002484 c = op.int
2485 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002486
Facundo Batista353750c2007-09-13 18:13:15 +00002487 # rescale so that c has exactly prec base 100 'digits'
2488 shift = prec-l
2489 if shift >= 0:
2490 c *= 100**shift
2491 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002492 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002493 c, remainder = divmod(c, 100**-shift)
2494 exact = not remainder
2495 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002496
Facundo Batista353750c2007-09-13 18:13:15 +00002497 # find n = floor(sqrt(c)) using Newton's method
2498 n = 10**prec
2499 while True:
2500 q = c//n
2501 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002502 break
Facundo Batista353750c2007-09-13 18:13:15 +00002503 else:
2504 n = n + q >> 1
2505 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002506
Facundo Batista353750c2007-09-13 18:13:15 +00002507 if exact:
2508 # result is exact; rescale to use ideal exponent e
2509 if shift >= 0:
2510 # assert n % 10**shift == 0
2511 n //= 10**shift
2512 else:
2513 n *= 10**-shift
2514 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002515 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002516 # result is not exact; fix last digit as described above
2517 if n % 5 == 0:
2518 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002519
Facundo Batista72bc54f2007-11-23 17:59:00 +00002520 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002521
Facundo Batista353750c2007-09-13 18:13:15 +00002522 # round, and fit to current context
2523 context = context._shallow_copy()
2524 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002525 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002526 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002527
Facundo Batista353750c2007-09-13 18:13:15 +00002528 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002529
2530 def max(self, other, context=None):
2531 """Returns the larger value.
2532
Facundo Batista353750c2007-09-13 18:13:15 +00002533 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002534 NaN (and signals if one is sNaN). Also rounds.
2535 """
Facundo Batista353750c2007-09-13 18:13:15 +00002536 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002537
Facundo Batista6c398da2007-09-17 17:30:13 +00002538 if context is None:
2539 context = getcontext()
2540
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002541 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002542 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002543 # number is always returned
2544 sn = self._isnan()
2545 on = other._isnan()
2546 if sn or on:
2547 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002548 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002549 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002550 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002551 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002552
Mark Dickinson2fc92632008-02-06 22:10:50 +00002553 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002554 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002555 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002556 # then an ordering is applied:
2557 #
Facundo Batista59c58842007-04-10 12:58:45 +00002558 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002559 # positive sign and min returns the operand with the negative sign
2560 #
Facundo Batista59c58842007-04-10 12:58:45 +00002561 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002562 # the result. This is exactly the ordering used in compare_total.
2563 c = self.compare_total(other)
2564
2565 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002566 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002567 else:
2568 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002569
Facundo Batistae64acfa2007-12-17 14:18:42 +00002570 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002571
2572 def min(self, other, context=None):
2573 """Returns the smaller value.
2574
Facundo Batista59c58842007-04-10 12:58:45 +00002575 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002576 NaN (and signals if one is sNaN). Also rounds.
2577 """
Facundo Batista353750c2007-09-13 18:13:15 +00002578 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002579
Facundo Batista6c398da2007-09-17 17:30:13 +00002580 if context is None:
2581 context = getcontext()
2582
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002583 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002584 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002585 # number is always returned
2586 sn = self._isnan()
2587 on = other._isnan()
2588 if sn or on:
2589 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002590 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002591 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002592 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002593 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002594
Mark Dickinson2fc92632008-02-06 22:10:50 +00002595 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002596 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002597 c = self.compare_total(other)
2598
2599 if c == -1:
2600 ans = self
2601 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002602 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002603
Facundo Batistae64acfa2007-12-17 14:18:42 +00002604 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002605
2606 def _isinteger(self):
2607 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002608 if self._is_special:
2609 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002610 if self._exp >= 0:
2611 return True
2612 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002613 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002614
2615 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002616 """Returns True if self is even. Assumes self is an integer."""
2617 if not self or self._exp > 0:
2618 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002619 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002620
2621 def adjusted(self):
2622 """Return the adjusted exponent of self"""
2623 try:
2624 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002625 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002626 except TypeError:
2627 return 0
2628
Facundo Batista353750c2007-09-13 18:13:15 +00002629 def canonical(self, context=None):
2630 """Returns the same Decimal object.
2631
2632 As we do not have different encodings for the same number, the
2633 received object already is in its canonical form.
2634 """
2635 return self
2636
2637 def compare_signal(self, other, context=None):
2638 """Compares self to the other operand numerically.
2639
2640 It's pretty much like compare(), but all NaNs signal, with signaling
2641 NaNs taking precedence over quiet NaNs.
2642 """
Mark Dickinson2fc92632008-02-06 22:10:50 +00002643 other = _convert_other(other, raiseit = True)
2644 ans = self._compare_check_nans(other, context)
2645 if ans:
2646 return ans
Facundo Batista353750c2007-09-13 18:13:15 +00002647 return self.compare(other, context=context)
2648
2649 def compare_total(self, other):
2650 """Compares self to other using the abstract representations.
2651
2652 This is not like the standard compare, which use their numerical
2653 value. Note that a total ordering is defined for all possible abstract
2654 representations.
2655 """
2656 # if one is negative and the other is positive, it's easy
2657 if self._sign and not other._sign:
2658 return Dec_n1
2659 if not self._sign and other._sign:
2660 return Dec_p1
2661 sign = self._sign
2662
2663 # let's handle both NaN types
2664 self_nan = self._isnan()
2665 other_nan = other._isnan()
2666 if self_nan or other_nan:
2667 if self_nan == other_nan:
2668 if self._int < other._int:
2669 if sign:
2670 return Dec_p1
2671 else:
2672 return Dec_n1
2673 if self._int > other._int:
2674 if sign:
2675 return Dec_n1
2676 else:
2677 return Dec_p1
2678 return Dec_0
2679
2680 if sign:
2681 if self_nan == 1:
2682 return Dec_n1
2683 if other_nan == 1:
2684 return Dec_p1
2685 if self_nan == 2:
2686 return Dec_n1
2687 if other_nan == 2:
2688 return Dec_p1
2689 else:
2690 if self_nan == 1:
2691 return Dec_p1
2692 if other_nan == 1:
2693 return Dec_n1
2694 if self_nan == 2:
2695 return Dec_p1
2696 if other_nan == 2:
2697 return Dec_n1
2698
2699 if self < other:
2700 return Dec_n1
2701 if self > other:
2702 return Dec_p1
2703
2704 if self._exp < other._exp:
2705 if sign:
2706 return Dec_p1
2707 else:
2708 return Dec_n1
2709 if self._exp > other._exp:
2710 if sign:
2711 return Dec_n1
2712 else:
2713 return Dec_p1
2714 return Dec_0
2715
2716
2717 def compare_total_mag(self, other):
2718 """Compares self to other using abstract repr., ignoring sign.
2719
2720 Like compare_total, but with operand's sign ignored and assumed to be 0.
2721 """
2722 s = self.copy_abs()
2723 o = other.copy_abs()
2724 return s.compare_total(o)
2725
2726 def copy_abs(self):
2727 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002728 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002729
2730 def copy_negate(self):
2731 """Returns a copy with the sign inverted."""
2732 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002733 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002734 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002735 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002736
2737 def copy_sign(self, other):
2738 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002739 return _dec_from_triple(other._sign, self._int,
2740 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002741
2742 def exp(self, context=None):
2743 """Returns e ** self."""
2744
2745 if context is None:
2746 context = getcontext()
2747
2748 # exp(NaN) = NaN
2749 ans = self._check_nans(context=context)
2750 if ans:
2751 return ans
2752
2753 # exp(-Infinity) = 0
2754 if self._isinfinity() == -1:
2755 return Dec_0
2756
2757 # exp(0) = 1
2758 if not self:
2759 return Dec_p1
2760
2761 # exp(Infinity) = Infinity
2762 if self._isinfinity() == 1:
2763 return Decimal(self)
2764
2765 # the result is now guaranteed to be inexact (the true
2766 # mathematical result is transcendental). There's no need to
2767 # raise Rounded and Inexact here---they'll always be raised as
2768 # a result of the call to _fix.
2769 p = context.prec
2770 adj = self.adjusted()
2771
2772 # we only need to do any computation for quite a small range
2773 # of adjusted exponents---for example, -29 <= adj <= 10 for
2774 # the default context. For smaller exponent the result is
2775 # indistinguishable from 1 at the given precision, while for
2776 # larger exponent the result either overflows or underflows.
2777 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2778 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002779 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002780 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2781 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002782 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002783 elif self._sign == 0 and adj < -p:
2784 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002785 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002786 elif self._sign == 1 and adj < -p-1:
2787 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002788 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002789 # general case
2790 else:
2791 op = _WorkRep(self)
2792 c, e = op.int, op.exp
2793 if op.sign == 1:
2794 c = -c
2795
2796 # compute correctly rounded result: increase precision by
2797 # 3 digits at a time until we get an unambiguously
2798 # roundable result
2799 extra = 3
2800 while True:
2801 coeff, exp = _dexp(c, e, p+extra)
2802 if coeff % (5*10**(len(str(coeff))-p-1)):
2803 break
2804 extra += 3
2805
Facundo Batista72bc54f2007-11-23 17:59:00 +00002806 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002807
2808 # at this stage, ans should round correctly with *any*
2809 # rounding mode, not just with ROUND_HALF_EVEN
2810 context = context._shallow_copy()
2811 rounding = context._set_rounding(ROUND_HALF_EVEN)
2812 ans = ans._fix(context)
2813 context.rounding = rounding
2814
2815 return ans
2816
2817 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002818 """Return True if self is canonical; otherwise return False.
2819
2820 Currently, the encoding of a Decimal instance is always
2821 canonical, so this method returns True for any Decimal.
2822 """
2823 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002824
2825 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002826 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002827
Facundo Batista1a191df2007-10-02 17:01:24 +00002828 A Decimal instance is considered finite if it is neither
2829 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002830 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002831 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002832
2833 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002834 """Return True if self is infinite; otherwise return False."""
2835 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002836
2837 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002838 """Return True if self is a qNaN or sNaN; otherwise return False."""
2839 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002840
2841 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002842 """Return True if self is a normal number; otherwise return False."""
2843 if self._is_special or not self:
2844 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002845 if context is None:
2846 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002847 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002848
2849 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002850 """Return True if self is a quiet NaN; otherwise return False."""
2851 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002852
2853 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002854 """Return True if self is negative; otherwise return False."""
2855 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002856
2857 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002858 """Return True if self is a signaling NaN; otherwise return False."""
2859 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002860
2861 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002862 """Return True if self is subnormal; otherwise return False."""
2863 if self._is_special or not self:
2864 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002865 if context is None:
2866 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002867 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002868
2869 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002870 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002871 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002872
2873 def _ln_exp_bound(self):
2874 """Compute a lower bound for the adjusted exponent of self.ln().
2875 In other words, compute r such that self.ln() >= 10**r. Assumes
2876 that self is finite and positive and that self != 1.
2877 """
2878
2879 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2880 adj = self._exp + len(self._int) - 1
2881 if adj >= 1:
2882 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2883 return len(str(adj*23//10)) - 1
2884 if adj <= -2:
2885 # argument <= 0.1
2886 return len(str((-1-adj)*23//10)) - 1
2887 op = _WorkRep(self)
2888 c, e = op.int, op.exp
2889 if adj == 0:
2890 # 1 < self < 10
2891 num = str(c-10**-e)
2892 den = str(c)
2893 return len(num) - len(den) - (num < den)
2894 # adj == -1, 0.1 <= self < 1
2895 return e + len(str(10**-e - c)) - 1
2896
2897
2898 def ln(self, context=None):
2899 """Returns the natural (base e) logarithm of self."""
2900
2901 if context is None:
2902 context = getcontext()
2903
2904 # ln(NaN) = NaN
2905 ans = self._check_nans(context=context)
2906 if ans:
2907 return ans
2908
2909 # ln(0.0) == -Infinity
2910 if not self:
2911 return negInf
2912
2913 # ln(Infinity) = Infinity
2914 if self._isinfinity() == 1:
2915 return Inf
2916
2917 # ln(1.0) == 0.0
2918 if self == Dec_p1:
2919 return Dec_0
2920
2921 # ln(negative) raises InvalidOperation
2922 if self._sign == 1:
2923 return context._raise_error(InvalidOperation,
2924 'ln of a negative value')
2925
2926 # result is irrational, so necessarily inexact
2927 op = _WorkRep(self)
2928 c, e = op.int, op.exp
2929 p = context.prec
2930
2931 # correctly rounded result: repeatedly increase precision by 3
2932 # until we get an unambiguously roundable result
2933 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2934 while True:
2935 coeff = _dlog(c, e, places)
2936 # assert len(str(abs(coeff)))-p >= 1
2937 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2938 break
2939 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002940 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002941
2942 context = context._shallow_copy()
2943 rounding = context._set_rounding(ROUND_HALF_EVEN)
2944 ans = ans._fix(context)
2945 context.rounding = rounding
2946 return ans
2947
2948 def _log10_exp_bound(self):
2949 """Compute a lower bound for the adjusted exponent of self.log10().
2950 In other words, find r such that self.log10() >= 10**r.
2951 Assumes that self is finite and positive and that self != 1.
2952 """
2953
2954 # For x >= 10 or x < 0.1 we only need a bound on the integer
2955 # part of log10(self), and this comes directly from the
2956 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2957 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2958 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2959
2960 adj = self._exp + len(self._int) - 1
2961 if adj >= 1:
2962 # self >= 10
2963 return len(str(adj))-1
2964 if adj <= -2:
2965 # self < 0.1
2966 return len(str(-1-adj))-1
2967 op = _WorkRep(self)
2968 c, e = op.int, op.exp
2969 if adj == 0:
2970 # 1 < self < 10
2971 num = str(c-10**-e)
2972 den = str(231*c)
2973 return len(num) - len(den) - (num < den) + 2
2974 # adj == -1, 0.1 <= self < 1
2975 num = str(10**-e-c)
2976 return len(num) + e - (num < "231") - 1
2977
2978 def log10(self, context=None):
2979 """Returns the base 10 logarithm of self."""
2980
2981 if context is None:
2982 context = getcontext()
2983
2984 # log10(NaN) = NaN
2985 ans = self._check_nans(context=context)
2986 if ans:
2987 return ans
2988
2989 # log10(0.0) == -Infinity
2990 if not self:
2991 return negInf
2992
2993 # log10(Infinity) = Infinity
2994 if self._isinfinity() == 1:
2995 return Inf
2996
2997 # log10(negative or -Infinity) raises InvalidOperation
2998 if self._sign == 1:
2999 return context._raise_error(InvalidOperation,
3000 'log10 of a negative value')
3001
3002 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00003003 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00003004 # answer may need rounding
3005 ans = Decimal(self._exp + len(self._int) - 1)
3006 else:
3007 # result is irrational, so necessarily inexact
3008 op = _WorkRep(self)
3009 c, e = op.int, op.exp
3010 p = context.prec
3011
3012 # correctly rounded result: repeatedly increase precision
3013 # until result is unambiguously roundable
3014 places = p-self._log10_exp_bound()+2
3015 while True:
3016 coeff = _dlog10(c, e, places)
3017 # assert len(str(abs(coeff)))-p >= 1
3018 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3019 break
3020 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003021 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003022
3023 context = context._shallow_copy()
3024 rounding = context._set_rounding(ROUND_HALF_EVEN)
3025 ans = ans._fix(context)
3026 context.rounding = rounding
3027 return ans
3028
3029 def logb(self, context=None):
3030 """ Returns the exponent of the magnitude of self's MSD.
3031
3032 The result is the integer which is the exponent of the magnitude
3033 of the most significant digit of self (as though it were truncated
3034 to a single digit while maintaining the value of that digit and
3035 without limiting the resulting exponent).
3036 """
3037 # logb(NaN) = NaN
3038 ans = self._check_nans(context=context)
3039 if ans:
3040 return ans
3041
3042 if context is None:
3043 context = getcontext()
3044
3045 # logb(+/-Inf) = +Inf
3046 if self._isinfinity():
3047 return Inf
3048
3049 # logb(0) = -Inf, DivisionByZero
3050 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00003051 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00003052
3053 # otherwise, simply return the adjusted exponent of self, as a
3054 # Decimal. Note that no attempt is made to fit the result
3055 # into the current context.
3056 return Decimal(self.adjusted())
3057
3058 def _islogical(self):
3059 """Return True if self is a logical operand.
3060
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00003061 For being logical, it must be a finite number with a sign of 0,
Facundo Batista353750c2007-09-13 18:13:15 +00003062 an exponent of 0, and a coefficient whose digits must all be
3063 either 0 or 1.
3064 """
3065 if self._sign != 0 or self._exp != 0:
3066 return False
3067 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003068 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00003069 return False
3070 return True
3071
3072 def _fill_logical(self, context, opa, opb):
3073 dif = context.prec - len(opa)
3074 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003075 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00003076 elif dif < 0:
3077 opa = opa[-context.prec:]
3078 dif = context.prec - len(opb)
3079 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003080 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00003081 elif dif < 0:
3082 opb = opb[-context.prec:]
3083 return opa, opb
3084
3085 def logical_and(self, other, context=None):
3086 """Applies an 'and' operation between self and other's digits."""
3087 if context is None:
3088 context = getcontext()
3089 if not self._islogical() or not other._islogical():
3090 return context._raise_error(InvalidOperation)
3091
3092 # fill to context.prec
3093 (opa, opb) = self._fill_logical(context, self._int, other._int)
3094
3095 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003096 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3097 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003098
3099 def logical_invert(self, context=None):
3100 """Invert all its digits."""
3101 if context is None:
3102 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003103 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3104 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003105
3106 def logical_or(self, other, context=None):
3107 """Applies an 'or' operation between self and other's digits."""
3108 if context is None:
3109 context = getcontext()
3110 if not self._islogical() or not other._islogical():
3111 return context._raise_error(InvalidOperation)
3112
3113 # fill to context.prec
3114 (opa, opb) = self._fill_logical(context, self._int, other._int)
3115
3116 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003117 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3118 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003119
3120 def logical_xor(self, other, context=None):
3121 """Applies an 'xor' operation between self and other's digits."""
3122 if context is None:
3123 context = getcontext()
3124 if not self._islogical() or not other._islogical():
3125 return context._raise_error(InvalidOperation)
3126
3127 # fill to context.prec
3128 (opa, opb) = self._fill_logical(context, self._int, other._int)
3129
3130 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003131 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3132 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003133
3134 def max_mag(self, other, context=None):
3135 """Compares the values numerically with their sign ignored."""
3136 other = _convert_other(other, raiseit=True)
3137
Facundo Batista6c398da2007-09-17 17:30:13 +00003138 if context is None:
3139 context = getcontext()
3140
Facundo Batista353750c2007-09-13 18:13:15 +00003141 if self._is_special or other._is_special:
3142 # If one operand is a quiet NaN and the other is number, then the
3143 # number is always returned
3144 sn = self._isnan()
3145 on = other._isnan()
3146 if sn or on:
3147 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003148 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003149 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003150 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003151 return self._check_nans(other, context)
3152
Mark Dickinson2fc92632008-02-06 22:10:50 +00003153 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003154 if c == 0:
3155 c = self.compare_total(other)
3156
3157 if c == -1:
3158 ans = other
3159 else:
3160 ans = self
3161
Facundo Batistae64acfa2007-12-17 14:18:42 +00003162 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003163
3164 def min_mag(self, other, context=None):
3165 """Compares the values numerically with their sign ignored."""
3166 other = _convert_other(other, raiseit=True)
3167
Facundo Batista6c398da2007-09-17 17:30:13 +00003168 if context is None:
3169 context = getcontext()
3170
Facundo Batista353750c2007-09-13 18:13:15 +00003171 if self._is_special or other._is_special:
3172 # If one operand is a quiet NaN and the other is number, then the
3173 # number is always returned
3174 sn = self._isnan()
3175 on = other._isnan()
3176 if sn or on:
3177 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003178 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003179 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003180 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003181 return self._check_nans(other, context)
3182
Mark Dickinson2fc92632008-02-06 22:10:50 +00003183 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003184 if c == 0:
3185 c = self.compare_total(other)
3186
3187 if c == -1:
3188 ans = self
3189 else:
3190 ans = other
3191
Facundo Batistae64acfa2007-12-17 14:18:42 +00003192 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003193
3194 def next_minus(self, context=None):
3195 """Returns the largest representable number smaller than itself."""
3196 if context is None:
3197 context = getcontext()
3198
3199 ans = self._check_nans(context=context)
3200 if ans:
3201 return ans
3202
3203 if self._isinfinity() == -1:
3204 return negInf
3205 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003206 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003207
3208 context = context.copy()
3209 context._set_rounding(ROUND_FLOOR)
3210 context._ignore_all_flags()
3211 new_self = self._fix(context)
3212 if new_self != self:
3213 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003214 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3215 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003216
3217 def next_plus(self, context=None):
3218 """Returns the smallest representable number larger than itself."""
3219 if context is None:
3220 context = getcontext()
3221
3222 ans = self._check_nans(context=context)
3223 if ans:
3224 return ans
3225
3226 if self._isinfinity() == 1:
3227 return Inf
3228 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003229 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003230
3231 context = context.copy()
3232 context._set_rounding(ROUND_CEILING)
3233 context._ignore_all_flags()
3234 new_self = self._fix(context)
3235 if new_self != self:
3236 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003237 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3238 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003239
3240 def next_toward(self, other, context=None):
3241 """Returns the number closest to self, in the direction towards other.
3242
3243 The result is the closest representable number to self
3244 (excluding self) that is in the direction towards other,
3245 unless both have the same value. If the two operands are
3246 numerically equal, then the result is a copy of self with the
3247 sign set to be the same as the sign of other.
3248 """
3249 other = _convert_other(other, raiseit=True)
3250
3251 if context is None:
3252 context = getcontext()
3253
3254 ans = self._check_nans(other, context)
3255 if ans:
3256 return ans
3257
Mark Dickinson2fc92632008-02-06 22:10:50 +00003258 comparison = self._cmp(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003259 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003260 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003261
3262 if comparison == -1:
3263 ans = self.next_plus(context)
3264 else: # comparison == 1
3265 ans = self.next_minus(context)
3266
3267 # decide which flags to raise using value of ans
3268 if ans._isinfinity():
3269 context._raise_error(Overflow,
3270 'Infinite result from next_toward',
3271 ans._sign)
3272 context._raise_error(Rounded)
3273 context._raise_error(Inexact)
3274 elif ans.adjusted() < context.Emin:
3275 context._raise_error(Underflow)
3276 context._raise_error(Subnormal)
3277 context._raise_error(Rounded)
3278 context._raise_error(Inexact)
3279 # if precision == 1 then we don't raise Clamped for a
3280 # result 0E-Etiny.
3281 if not ans:
3282 context._raise_error(Clamped)
3283
3284 return ans
3285
3286 def number_class(self, context=None):
3287 """Returns an indication of the class of self.
3288
3289 The class is one of the following strings:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00003290 sNaN
3291 NaN
Facundo Batista353750c2007-09-13 18:13:15 +00003292 -Infinity
3293 -Normal
3294 -Subnormal
3295 -Zero
3296 +Zero
3297 +Subnormal
3298 +Normal
3299 +Infinity
3300 """
3301 if self.is_snan():
3302 return "sNaN"
3303 if self.is_qnan():
3304 return "NaN"
3305 inf = self._isinfinity()
3306 if inf == 1:
3307 return "+Infinity"
3308 if inf == -1:
3309 return "-Infinity"
3310 if self.is_zero():
3311 if self._sign:
3312 return "-Zero"
3313 else:
3314 return "+Zero"
3315 if context is None:
3316 context = getcontext()
3317 if self.is_subnormal(context=context):
3318 if self._sign:
3319 return "-Subnormal"
3320 else:
3321 return "+Subnormal"
3322 # just a normal, regular, boring number, :)
3323 if self._sign:
3324 return "-Normal"
3325 else:
3326 return "+Normal"
3327
3328 def radix(self):
3329 """Just returns 10, as this is Decimal, :)"""
3330 return Decimal(10)
3331
3332 def rotate(self, other, context=None):
3333 """Returns a rotated copy of self, value-of-other times."""
3334 if context is None:
3335 context = getcontext()
3336
3337 ans = self._check_nans(other, context)
3338 if ans:
3339 return ans
3340
3341 if other._exp != 0:
3342 return context._raise_error(InvalidOperation)
3343 if not (-context.prec <= int(other) <= context.prec):
3344 return context._raise_error(InvalidOperation)
3345
3346 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003347 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003348
3349 # get values, pad if necessary
3350 torot = int(other)
3351 rotdig = self._int
3352 topad = context.prec - len(rotdig)
3353 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003354 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003355
3356 # let's rotate!
3357 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003358 return _dec_from_triple(self._sign,
3359 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003360
3361 def scaleb (self, other, context=None):
3362 """Returns self operand after adding the second value to its exp."""
3363 if context is None:
3364 context = getcontext()
3365
3366 ans = self._check_nans(other, context)
3367 if ans:
3368 return ans
3369
3370 if other._exp != 0:
3371 return context._raise_error(InvalidOperation)
3372 liminf = -2 * (context.Emax + context.prec)
3373 limsup = 2 * (context.Emax + context.prec)
3374 if not (liminf <= int(other) <= limsup):
3375 return context._raise_error(InvalidOperation)
3376
3377 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003378 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003379
Facundo Batista72bc54f2007-11-23 17:59:00 +00003380 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003381 d = d._fix(context)
3382 return d
3383
3384 def shift(self, other, context=None):
3385 """Returns a shifted copy of self, value-of-other times."""
3386 if context is None:
3387 context = getcontext()
3388
3389 ans = self._check_nans(other, context)
3390 if ans:
3391 return ans
3392
3393 if other._exp != 0:
3394 return context._raise_error(InvalidOperation)
3395 if not (-context.prec <= int(other) <= context.prec):
3396 return context._raise_error(InvalidOperation)
3397
3398 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003399 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003400
3401 # get values, pad if necessary
3402 torot = int(other)
3403 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003404 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003405 rotdig = self._int
3406 topad = context.prec - len(rotdig)
3407 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003408 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003409
3410 # let's shift!
3411 if torot < 0:
3412 rotated = rotdig[:torot]
3413 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003414 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003415 rotated = rotated[-context.prec:]
3416
Facundo Batista72bc54f2007-11-23 17:59:00 +00003417 return _dec_from_triple(self._sign,
3418 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003419
Facundo Batista59c58842007-04-10 12:58:45 +00003420 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003421 def __reduce__(self):
3422 return (self.__class__, (str(self),))
3423
3424 def __copy__(self):
3425 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003426 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003427 return self.__class__(str(self))
3428
3429 def __deepcopy__(self, memo):
3430 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003431 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003432 return self.__class__(str(self))
3433
Facundo Batista72bc54f2007-11-23 17:59:00 +00003434def _dec_from_triple(sign, coefficient, exponent, special=False):
3435 """Create a decimal instance directly, without any validation,
3436 normalization (e.g. removal of leading zeros) or argument
3437 conversion.
3438
3439 This function is for *internal use only*.
3440 """
3441
3442 self = object.__new__(Decimal)
3443 self._sign = sign
3444 self._int = coefficient
3445 self._exp = exponent
3446 self._is_special = special
3447
3448 return self
3449
Facundo Batista59c58842007-04-10 12:58:45 +00003450##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003451
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003452
3453# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003454rounding_functions = [name for name in Decimal.__dict__.keys()
3455 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003456for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003457 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003458 globalname = name[1:].upper()
3459 val = globals()[globalname]
3460 Decimal._pick_rounding_function[val] = name
3461
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003462del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003463
Nick Coghlanced12182006-09-02 03:54:17 +00003464class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003465 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003466
Nick Coghlanced12182006-09-02 03:54:17 +00003467 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003468 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003469 """
3470 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003471 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003472 def __enter__(self):
3473 self.saved_context = getcontext()
3474 setcontext(self.new_context)
3475 return self.new_context
3476 def __exit__(self, t, v, tb):
3477 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003478
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003479class Context(object):
3480 """Contains the context for a Decimal instance.
3481
3482 Contains:
3483 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003484 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003485 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003486 raised when it is caused. Otherwise, a value is
3487 substituted in.
3488 flags - When an exception is caused, flags[exception] is incremented.
3489 (Whether or not the trap_enabler is set)
3490 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003491 Emin - Minimum exponent
3492 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003493 capitals - If 1, 1*10^1 is printed as 1E+1.
3494 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003495 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003496 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003497
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003498 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003499 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003500 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003501 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003502 _ignored_flags=None):
3503 if flags is None:
3504 flags = []
3505 if _ignored_flags is None:
3506 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003507 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003508 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003509 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003510 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003511 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003512 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003513 for name, val in locals().items():
3514 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003515 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003516 else:
3517 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003518 del self.self
3519
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003520 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003521 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003522 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003523 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3524 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3525 % vars(self))
3526 names = [f.__name__ for f, v in self.flags.items() if v]
3527 s.append('flags=[' + ', '.join(names) + ']')
3528 names = [t.__name__ for t, v in self.traps.items() if v]
3529 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003530 return ', '.join(s) + ')'
3531
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003532 def clear_flags(self):
3533 """Reset all flags to zero"""
3534 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003535 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003536
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003537 def _shallow_copy(self):
3538 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003539 nc = Context(self.prec, self.rounding, self.traps,
3540 self.flags, self.Emin, self.Emax,
3541 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003542 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003543
3544 def copy(self):
3545 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003546 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003547 self.flags.copy(), self.Emin, self.Emax,
3548 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003549 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003550 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003551
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003552 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003553 """Handles an error
3554
3555 If the flag is in _ignored_flags, returns the default response.
3556 Otherwise, it increments the flag, then, if the corresponding
3557 trap_enabler is set, it reaises the exception. Otherwise, it returns
3558 the default value after incrementing the flag.
3559 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003560 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003561 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003562 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003563 return error().handle(self, *args)
3564
3565 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003566 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003567 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003568 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003569
3570 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003571 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003572 raise error, explanation
3573
3574 def _ignore_all_flags(self):
3575 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003576 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003577
3578 def _ignore_flags(self, *flags):
3579 """Ignore the flags, if they are raised"""
3580 # Do not mutate-- This way, copies of a context leave the original
3581 # alone.
3582 self._ignored_flags = (self._ignored_flags + list(flags))
3583 return list(flags)
3584
3585 def _regard_flags(self, *flags):
3586 """Stop ignoring the flags, if they are raised"""
3587 if flags and isinstance(flags[0], (tuple,list)):
3588 flags = flags[0]
3589 for flag in flags:
3590 self._ignored_flags.remove(flag)
3591
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003592 def __hash__(self):
3593 """A Context cannot be hashed."""
3594 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003595 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003596
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003597 def Etiny(self):
3598 """Returns Etiny (= Emin - prec + 1)"""
3599 return int(self.Emin - self.prec + 1)
3600
3601 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003602 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003603 return int(self.Emax - self.prec + 1)
3604
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003605 def _set_rounding(self, type):
3606 """Sets the rounding type.
3607
3608 Sets the rounding type, and returns the current (previous)
3609 rounding type. Often used like:
3610
3611 context = context.copy()
3612 # so you don't change the calling context
3613 # if an error occurs in the middle.
3614 rounding = context._set_rounding(ROUND_UP)
3615 val = self.__sub__(other, context=context)
3616 context._set_rounding(rounding)
3617
3618 This will make it round up for that operation.
3619 """
3620 rounding = self.rounding
3621 self.rounding= type
3622 return rounding
3623
Raymond Hettingerfed52962004-07-14 15:41:57 +00003624 def create_decimal(self, num='0'):
Mark Dickinson59bc20b2008-01-12 01:56:00 +00003625 """Creates a new Decimal instance but using self as context.
3626
3627 This method implements the to-number operation of the
3628 IBM Decimal specification."""
3629
3630 if isinstance(num, basestring) and num != num.strip():
3631 return self._raise_error(ConversionSyntax,
3632 "no trailing or leading whitespace is "
3633 "permitted.")
3634
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003635 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003636 if d._isnan() and len(d._int) > self.prec - self._clamp:
3637 return self._raise_error(ConversionSyntax,
3638 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003639 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003640
Facundo Batista59c58842007-04-10 12:58:45 +00003641 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003642 def abs(self, a):
3643 """Returns the absolute value of the operand.
3644
3645 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003646 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003647 the plus operation on the operand.
3648
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003649 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003650 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003651 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003652 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003653 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003654 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003655 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003656 Decimal("101.5")
3657 """
3658 return a.__abs__(context=self)
3659
3660 def add(self, a, b):
3661 """Return the sum of the two operands.
3662
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003663 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003664 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003665 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003666 Decimal("1.02E+4")
3667 """
3668 return a.__add__(b, context=self)
3669
3670 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003671 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003672
Facundo Batista353750c2007-09-13 18:13:15 +00003673 def canonical(self, a):
3674 """Returns the same Decimal object.
3675
3676 As we do not have different encodings for the same number, the
3677 received object already is in its canonical form.
3678
3679 >>> ExtendedContext.canonical(Decimal('2.50'))
3680 Decimal("2.50")
3681 """
3682 return a.canonical(context=self)
3683
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003684 def compare(self, a, b):
3685 """Compares values numerically.
3686
3687 If the signs of the operands differ, a value representing each operand
3688 ('-1' if the operand is less than zero, '0' if the operand is zero or
3689 negative zero, or '1' if the operand is greater than zero) is used in
3690 place of that operand for the comparison instead of the actual
3691 operand.
3692
3693 The comparison is then effected by subtracting the second operand from
3694 the first and then returning a value according to the result of the
3695 subtraction: '-1' if the result is less than zero, '0' if the result is
3696 zero or negative zero, or '1' if the result is greater than zero.
3697
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003698 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003699 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003700 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003701 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003702 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003703 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003704 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003705 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003706 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003707 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003708 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003709 Decimal("-1")
3710 """
3711 return a.compare(b, context=self)
3712
Facundo Batista353750c2007-09-13 18:13:15 +00003713 def compare_signal(self, a, b):
3714 """Compares the values of the two operands numerically.
3715
3716 It's pretty much like compare(), but all NaNs signal, with signaling
3717 NaNs taking precedence over quiet NaNs.
3718
3719 >>> c = ExtendedContext
3720 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3721 Decimal("-1")
3722 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3723 Decimal("0")
3724 >>> c.flags[InvalidOperation] = 0
3725 >>> print c.flags[InvalidOperation]
3726 0
3727 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3728 Decimal("NaN")
3729 >>> print c.flags[InvalidOperation]
3730 1
3731 >>> c.flags[InvalidOperation] = 0
3732 >>> print c.flags[InvalidOperation]
3733 0
3734 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3735 Decimal("NaN")
3736 >>> print c.flags[InvalidOperation]
3737 1
3738 """
3739 return a.compare_signal(b, context=self)
3740
3741 def compare_total(self, a, b):
3742 """Compares two operands using their abstract representation.
3743
3744 This is not like the standard compare, which use their numerical
3745 value. Note that a total ordering is defined for all possible abstract
3746 representations.
3747
3748 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3749 Decimal("-1")
3750 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3751 Decimal("-1")
3752 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3753 Decimal("-1")
3754 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3755 Decimal("0")
3756 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3757 Decimal("1")
3758 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3759 Decimal("-1")
3760 """
3761 return a.compare_total(b)
3762
3763 def compare_total_mag(self, a, b):
3764 """Compares two operands using their abstract representation ignoring sign.
3765
3766 Like compare_total, but with operand's sign ignored and assumed to be 0.
3767 """
3768 return a.compare_total_mag(b)
3769
3770 def copy_abs(self, a):
3771 """Returns a copy of the operand with the sign set to 0.
3772
3773 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3774 Decimal("2.1")
3775 >>> ExtendedContext.copy_abs(Decimal('-100'))
3776 Decimal("100")
3777 """
3778 return a.copy_abs()
3779
3780 def copy_decimal(self, a):
3781 """Returns a copy of the decimal objet.
3782
3783 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3784 Decimal("2.1")
3785 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3786 Decimal("-1.00")
3787 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003788 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003789
3790 def copy_negate(self, a):
3791 """Returns a copy of the operand with the sign inverted.
3792
3793 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3794 Decimal("-101.5")
3795 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3796 Decimal("101.5")
3797 """
3798 return a.copy_negate()
3799
3800 def copy_sign(self, a, b):
3801 """Copies the second operand's sign to the first one.
3802
3803 In detail, it returns a copy of the first operand with the sign
3804 equal to the sign of the second operand.
3805
3806 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3807 Decimal("1.50")
3808 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3809 Decimal("1.50")
3810 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3811 Decimal("-1.50")
3812 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3813 Decimal("-1.50")
3814 """
3815 return a.copy_sign(b)
3816
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003817 def divide(self, a, b):
3818 """Decimal division in a specified context.
3819
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003820 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003821 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003822 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003823 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003824 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003825 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003826 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003827 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003828 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003829 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003830 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003831 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003832 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003833 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003834 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003835 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003836 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003837 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003838 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003839 Decimal("1.20E+6")
3840 """
3841 return a.__div__(b, context=self)
3842
3843 def divide_int(self, a, b):
3844 """Divides two numbers and returns the integer part of the result.
3845
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003846 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003847 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003848 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003849 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003850 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003851 Decimal("3")
3852 """
3853 return a.__floordiv__(b, context=self)
3854
3855 def divmod(self, a, b):
3856 return a.__divmod__(b, context=self)
3857
Facundo Batista353750c2007-09-13 18:13:15 +00003858 def exp(self, a):
3859 """Returns e ** a.
3860
3861 >>> c = ExtendedContext.copy()
3862 >>> c.Emin = -999
3863 >>> c.Emax = 999
3864 >>> c.exp(Decimal('-Infinity'))
3865 Decimal("0")
3866 >>> c.exp(Decimal('-1'))
3867 Decimal("0.367879441")
3868 >>> c.exp(Decimal('0'))
3869 Decimal("1")
3870 >>> c.exp(Decimal('1'))
3871 Decimal("2.71828183")
3872 >>> c.exp(Decimal('0.693147181'))
3873 Decimal("2.00000000")
3874 >>> c.exp(Decimal('+Infinity'))
3875 Decimal("Infinity")
3876 """
3877 return a.exp(context=self)
3878
3879 def fma(self, a, b, c):
3880 """Returns a multiplied by b, plus c.
3881
3882 The first two operands are multiplied together, using multiply,
3883 the third operand is then added to the result of that
3884 multiplication, using add, all with only one final rounding.
3885
3886 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3887 Decimal("22")
3888 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3889 Decimal("-8")
3890 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3891 Decimal("1.38435736E+12")
3892 """
3893 return a.fma(b, c, context=self)
3894
3895 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003896 """Return True if the operand is canonical; otherwise return False.
3897
3898 Currently, the encoding of a Decimal instance is always
3899 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00003900
3901 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003902 True
Facundo Batista353750c2007-09-13 18:13:15 +00003903 """
Facundo Batista1a191df2007-10-02 17:01:24 +00003904 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00003905
3906 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003907 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003908
Facundo Batista1a191df2007-10-02 17:01:24 +00003909 A Decimal instance is considered finite if it is neither
3910 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00003911
3912 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003913 True
Facundo Batista353750c2007-09-13 18:13:15 +00003914 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003915 True
Facundo Batista353750c2007-09-13 18:13:15 +00003916 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003917 True
Facundo Batista353750c2007-09-13 18:13:15 +00003918 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003919 False
Facundo Batista353750c2007-09-13 18:13:15 +00003920 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003921 False
Facundo Batista353750c2007-09-13 18:13:15 +00003922 """
3923 return a.is_finite()
3924
3925 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003926 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003927
3928 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003929 False
Facundo Batista353750c2007-09-13 18:13:15 +00003930 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003931 True
Facundo Batista353750c2007-09-13 18:13:15 +00003932 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003933 False
Facundo Batista353750c2007-09-13 18:13:15 +00003934 """
3935 return a.is_infinite()
3936
3937 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003938 """Return True if the operand is a qNaN or sNaN;
3939 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003940
3941 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003942 False
Facundo Batista353750c2007-09-13 18:13:15 +00003943 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003944 True
Facundo Batista353750c2007-09-13 18:13:15 +00003945 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003946 True
Facundo Batista353750c2007-09-13 18:13:15 +00003947 """
3948 return a.is_nan()
3949
3950 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003951 """Return True if the operand is a normal number;
3952 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003953
3954 >>> c = ExtendedContext.copy()
3955 >>> c.Emin = -999
3956 >>> c.Emax = 999
3957 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003958 True
Facundo Batista353750c2007-09-13 18:13:15 +00003959 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003960 False
Facundo Batista353750c2007-09-13 18:13:15 +00003961 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003962 False
Facundo Batista353750c2007-09-13 18:13:15 +00003963 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003964 False
Facundo Batista353750c2007-09-13 18:13:15 +00003965 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003966 False
Facundo Batista353750c2007-09-13 18:13:15 +00003967 """
3968 return a.is_normal(context=self)
3969
3970 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003971 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003972
3973 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003974 False
Facundo Batista353750c2007-09-13 18:13:15 +00003975 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003976 True
Facundo Batista353750c2007-09-13 18:13:15 +00003977 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003978 False
Facundo Batista353750c2007-09-13 18:13:15 +00003979 """
3980 return a.is_qnan()
3981
3982 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003983 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003984
3985 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003986 False
Facundo Batista353750c2007-09-13 18:13:15 +00003987 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003988 True
Facundo Batista353750c2007-09-13 18:13:15 +00003989 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003990 True
Facundo Batista353750c2007-09-13 18:13:15 +00003991 """
3992 return a.is_signed()
3993
3994 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003995 """Return True if the operand is a signaling NaN;
3996 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003997
3998 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003999 False
Facundo Batista353750c2007-09-13 18:13:15 +00004000 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004001 False
Facundo Batista353750c2007-09-13 18:13:15 +00004002 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004003 True
Facundo Batista353750c2007-09-13 18:13:15 +00004004 """
4005 return a.is_snan()
4006
4007 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004008 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004009
4010 >>> c = ExtendedContext.copy()
4011 >>> c.Emin = -999
4012 >>> c.Emax = 999
4013 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004014 False
Facundo Batista353750c2007-09-13 18:13:15 +00004015 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004016 True
Facundo Batista353750c2007-09-13 18:13:15 +00004017 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004018 False
Facundo Batista353750c2007-09-13 18:13:15 +00004019 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004020 False
Facundo Batista353750c2007-09-13 18:13:15 +00004021 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004022 False
Facundo Batista353750c2007-09-13 18:13:15 +00004023 """
4024 return a.is_subnormal(context=self)
4025
4026 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004027 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004028
4029 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004030 True
Facundo Batista353750c2007-09-13 18:13:15 +00004031 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004032 False
Facundo Batista353750c2007-09-13 18:13:15 +00004033 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004034 True
Facundo Batista353750c2007-09-13 18:13:15 +00004035 """
4036 return a.is_zero()
4037
4038 def ln(self, a):
4039 """Returns the natural (base e) logarithm of the operand.
4040
4041 >>> c = ExtendedContext.copy()
4042 >>> c.Emin = -999
4043 >>> c.Emax = 999
4044 >>> c.ln(Decimal('0'))
4045 Decimal("-Infinity")
4046 >>> c.ln(Decimal('1.000'))
4047 Decimal("0")
4048 >>> c.ln(Decimal('2.71828183'))
4049 Decimal("1.00000000")
4050 >>> c.ln(Decimal('10'))
4051 Decimal("2.30258509")
4052 >>> c.ln(Decimal('+Infinity'))
4053 Decimal("Infinity")
4054 """
4055 return a.ln(context=self)
4056
4057 def log10(self, a):
4058 """Returns the base 10 logarithm of the operand.
4059
4060 >>> c = ExtendedContext.copy()
4061 >>> c.Emin = -999
4062 >>> c.Emax = 999
4063 >>> c.log10(Decimal('0'))
4064 Decimal("-Infinity")
4065 >>> c.log10(Decimal('0.001'))
4066 Decimal("-3")
4067 >>> c.log10(Decimal('1.000'))
4068 Decimal("0")
4069 >>> c.log10(Decimal('2'))
4070 Decimal("0.301029996")
4071 >>> c.log10(Decimal('10'))
4072 Decimal("1")
4073 >>> c.log10(Decimal('70'))
4074 Decimal("1.84509804")
4075 >>> c.log10(Decimal('+Infinity'))
4076 Decimal("Infinity")
4077 """
4078 return a.log10(context=self)
4079
4080 def logb(self, a):
4081 """ Returns the exponent of the magnitude of the operand's MSD.
4082
4083 The result is the integer which is the exponent of the magnitude
4084 of the most significant digit of the operand (as though the
4085 operand were truncated to a single digit while maintaining the
4086 value of that digit and without limiting the resulting exponent).
4087
4088 >>> ExtendedContext.logb(Decimal('250'))
4089 Decimal("2")
4090 >>> ExtendedContext.logb(Decimal('2.50'))
4091 Decimal("0")
4092 >>> ExtendedContext.logb(Decimal('0.03'))
4093 Decimal("-2")
4094 >>> ExtendedContext.logb(Decimal('0'))
4095 Decimal("-Infinity")
4096 """
4097 return a.logb(context=self)
4098
4099 def logical_and(self, a, b):
4100 """Applies the logical operation 'and' between each operand's digits.
4101
4102 The operands must be both logical numbers.
4103
4104 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4105 Decimal("0")
4106 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4107 Decimal("0")
4108 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4109 Decimal("0")
4110 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4111 Decimal("1")
4112 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4113 Decimal("1000")
4114 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4115 Decimal("10")
4116 """
4117 return a.logical_and(b, context=self)
4118
4119 def logical_invert(self, a):
4120 """Invert all the digits in the operand.
4121
4122 The operand must be a logical number.
4123
4124 >>> ExtendedContext.logical_invert(Decimal('0'))
4125 Decimal("111111111")
4126 >>> ExtendedContext.logical_invert(Decimal('1'))
4127 Decimal("111111110")
4128 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4129 Decimal("0")
4130 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4131 Decimal("10101010")
4132 """
4133 return a.logical_invert(context=self)
4134
4135 def logical_or(self, a, b):
4136 """Applies the logical operation 'or' between each operand's digits.
4137
4138 The operands must be both logical numbers.
4139
4140 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4141 Decimal("0")
4142 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4143 Decimal("1")
4144 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4145 Decimal("1")
4146 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4147 Decimal("1")
4148 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4149 Decimal("1110")
4150 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4151 Decimal("1110")
4152 """
4153 return a.logical_or(b, context=self)
4154
4155 def logical_xor(self, a, b):
4156 """Applies the logical operation 'xor' between each operand's digits.
4157
4158 The operands must be both logical numbers.
4159
4160 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4161 Decimal("0")
4162 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4163 Decimal("1")
4164 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4165 Decimal("1")
4166 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4167 Decimal("0")
4168 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4169 Decimal("110")
4170 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4171 Decimal("1101")
4172 """
4173 return a.logical_xor(b, context=self)
4174
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004175 def max(self, a,b):
4176 """max compares two values numerically and returns the maximum.
4177
4178 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004179 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004180 operation. If they are numerically equal then the left-hand operand
4181 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004182 infinity) of the two operands is chosen as the result.
4183
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004184 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004185 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004186 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004187 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004188 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004189 Decimal("1")
4190 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4191 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004192 """
4193 return a.max(b, context=self)
4194
Facundo Batista353750c2007-09-13 18:13:15 +00004195 def max_mag(self, a, b):
4196 """Compares the values numerically with their sign ignored."""
4197 return a.max_mag(b, context=self)
4198
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004199 def min(self, a,b):
4200 """min compares two values numerically and returns the minimum.
4201
4202 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004203 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004204 operation. If they are numerically equal then the left-hand operand
4205 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004206 infinity) of the two operands is chosen as the result.
4207
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004208 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004209 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004210 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004211 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004212 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004213 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004214 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4215 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004216 """
4217 return a.min(b, context=self)
4218
Facundo Batista353750c2007-09-13 18:13:15 +00004219 def min_mag(self, a, b):
4220 """Compares the values numerically with their sign ignored."""
4221 return a.min_mag(b, context=self)
4222
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004223 def minus(self, a):
4224 """Minus corresponds to unary prefix minus in Python.
4225
4226 The operation is evaluated using the same rules as subtract; the
4227 operation minus(a) is calculated as subtract('0', a) where the '0'
4228 has the same exponent as the operand.
4229
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004230 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004231 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004232 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004233 Decimal("1.3")
4234 """
4235 return a.__neg__(context=self)
4236
4237 def multiply(self, a, b):
4238 """multiply multiplies two operands.
4239
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004240 If either operand is a special value then the general rules apply.
4241 Otherwise, the operands are multiplied together ('long multiplication'),
4242 resulting in a number which may be as long as the sum of the lengths
4243 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004244
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004245 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004246 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004247 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004248 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004249 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004250 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004251 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004252 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004253 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004254 Decimal("4.28135971E+11")
4255 """
4256 return a.__mul__(b, context=self)
4257
Facundo Batista353750c2007-09-13 18:13:15 +00004258 def next_minus(self, a):
4259 """Returns the largest representable number smaller than a.
4260
4261 >>> c = ExtendedContext.copy()
4262 >>> c.Emin = -999
4263 >>> c.Emax = 999
4264 >>> ExtendedContext.next_minus(Decimal('1'))
4265 Decimal("0.999999999")
4266 >>> c.next_minus(Decimal('1E-1007'))
4267 Decimal("0E-1007")
4268 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4269 Decimal("-1.00000004")
4270 >>> c.next_minus(Decimal('Infinity'))
4271 Decimal("9.99999999E+999")
4272 """
4273 return a.next_minus(context=self)
4274
4275 def next_plus(self, a):
4276 """Returns the smallest representable number larger than a.
4277
4278 >>> c = ExtendedContext.copy()
4279 >>> c.Emin = -999
4280 >>> c.Emax = 999
4281 >>> ExtendedContext.next_plus(Decimal('1'))
4282 Decimal("1.00000001")
4283 >>> c.next_plus(Decimal('-1E-1007'))
4284 Decimal("-0E-1007")
4285 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4286 Decimal("-1.00000002")
4287 >>> c.next_plus(Decimal('-Infinity'))
4288 Decimal("-9.99999999E+999")
4289 """
4290 return a.next_plus(context=self)
4291
4292 def next_toward(self, a, b):
4293 """Returns the number closest to a, in direction towards b.
4294
4295 The result is the closest representable number from the first
4296 operand (but not the first operand) that is in the direction
4297 towards the second operand, unless the operands have the same
4298 value.
4299
4300 >>> c = ExtendedContext.copy()
4301 >>> c.Emin = -999
4302 >>> c.Emax = 999
4303 >>> c.next_toward(Decimal('1'), Decimal('2'))
4304 Decimal("1.00000001")
4305 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4306 Decimal("-0E-1007")
4307 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4308 Decimal("-1.00000002")
4309 >>> c.next_toward(Decimal('1'), Decimal('0'))
4310 Decimal("0.999999999")
4311 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4312 Decimal("0E-1007")
4313 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4314 Decimal("-1.00000004")
4315 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4316 Decimal("-0.00")
4317 """
4318 return a.next_toward(b, context=self)
4319
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004320 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004321 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004322
4323 Essentially a plus operation with all trailing zeros removed from the
4324 result.
4325
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004326 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004327 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004328 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004329 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004330 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004331 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004332 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004333 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004334 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004335 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004336 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004337 Decimal("0")
4338 """
4339 return a.normalize(context=self)
4340
Facundo Batista353750c2007-09-13 18:13:15 +00004341 def number_class(self, a):
4342 """Returns an indication of the class of the operand.
4343
4344 The class is one of the following strings:
4345 -sNaN
4346 -NaN
4347 -Infinity
4348 -Normal
4349 -Subnormal
4350 -Zero
4351 +Zero
4352 +Subnormal
4353 +Normal
4354 +Infinity
4355
4356 >>> c = Context(ExtendedContext)
4357 >>> c.Emin = -999
4358 >>> c.Emax = 999
4359 >>> c.number_class(Decimal('Infinity'))
4360 '+Infinity'
4361 >>> c.number_class(Decimal('1E-10'))
4362 '+Normal'
4363 >>> c.number_class(Decimal('2.50'))
4364 '+Normal'
4365 >>> c.number_class(Decimal('0.1E-999'))
4366 '+Subnormal'
4367 >>> c.number_class(Decimal('0'))
4368 '+Zero'
4369 >>> c.number_class(Decimal('-0'))
4370 '-Zero'
4371 >>> c.number_class(Decimal('-0.1E-999'))
4372 '-Subnormal'
4373 >>> c.number_class(Decimal('-1E-10'))
4374 '-Normal'
4375 >>> c.number_class(Decimal('-2.50'))
4376 '-Normal'
4377 >>> c.number_class(Decimal('-Infinity'))
4378 '-Infinity'
4379 >>> c.number_class(Decimal('NaN'))
4380 'NaN'
4381 >>> c.number_class(Decimal('-NaN'))
4382 'NaN'
4383 >>> c.number_class(Decimal('sNaN'))
4384 'sNaN'
4385 """
4386 return a.number_class(context=self)
4387
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004388 def plus(self, a):
4389 """Plus corresponds to unary prefix plus in Python.
4390
4391 The operation is evaluated using the same rules as add; the
4392 operation plus(a) is calculated as add('0', a) where the '0'
4393 has the same exponent as the operand.
4394
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004395 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004396 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004397 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004398 Decimal("-1.3")
4399 """
4400 return a.__pos__(context=self)
4401
4402 def power(self, a, b, modulo=None):
4403 """Raises a to the power of b, to modulo if given.
4404
Facundo Batista353750c2007-09-13 18:13:15 +00004405 With two arguments, compute a**b. If a is negative then b
4406 must be integral. The result will be inexact unless b is
4407 integral and the result is finite and can be expressed exactly
4408 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004409
Facundo Batista353750c2007-09-13 18:13:15 +00004410 With three arguments, compute (a**b) % modulo. For the
4411 three argument form, the following restrictions on the
4412 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004413
Facundo Batista353750c2007-09-13 18:13:15 +00004414 - all three arguments must be integral
4415 - b must be nonnegative
4416 - at least one of a or b must be nonzero
4417 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004418
Facundo Batista353750c2007-09-13 18:13:15 +00004419 The result of pow(a, b, modulo) is identical to the result
4420 that would be obtained by computing (a**b) % modulo with
4421 unbounded precision, but is computed more efficiently. It is
4422 always exact.
4423
4424 >>> c = ExtendedContext.copy()
4425 >>> c.Emin = -999
4426 >>> c.Emax = 999
4427 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004428 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004429 >>> c.power(Decimal('-2'), Decimal('3'))
4430 Decimal("-8")
4431 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004432 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004433 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004434 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004435 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4436 Decimal("2.00000000")
4437 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004438 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004439 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004440 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004441 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004442 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004443 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004444 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004445 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004446 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004447 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004448 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004449 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004450 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004451 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004452 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004453
4454 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4455 Decimal("11")
4456 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4457 Decimal("-11")
4458 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4459 Decimal("1")
4460 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4461 Decimal("11")
4462 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4463 Decimal("11729830")
4464 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4465 Decimal("-0")
4466 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4467 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004468 """
4469 return a.__pow__(b, modulo, context=self)
4470
4471 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004472 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004473
4474 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004475 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004476 exponent is being increased), multiplied by a positive power of ten (if
4477 the exponent is being decreased), or is unchanged (if the exponent is
4478 already equal to that of the right-hand operand).
4479
4480 Unlike other operations, if the length of the coefficient after the
4481 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004482 operation condition is raised. This guarantees that, unless there is
4483 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004484 equal to that of the right-hand operand.
4485
4486 Also unlike other operations, quantize will never raise Underflow, even
4487 if the result is subnormal and inexact.
4488
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004489 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004490 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004491 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004492 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004493 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004494 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004495 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004496 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004497 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004498 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004499 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004500 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004501 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004502 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004503 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004504 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004505 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004506 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004507 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004508 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004509 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004510 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004511 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004512 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004513 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004514 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004515 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004516 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004517 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004518 Decimal("2E+2")
4519 """
4520 return a.quantize(b, context=self)
4521
Facundo Batista353750c2007-09-13 18:13:15 +00004522 def radix(self):
4523 """Just returns 10, as this is Decimal, :)
4524
4525 >>> ExtendedContext.radix()
4526 Decimal("10")
4527 """
4528 return Decimal(10)
4529
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004530 def remainder(self, a, b):
4531 """Returns the remainder from integer division.
4532
4533 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004534 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004535 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004536 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004537
4538 This operation will fail under the same conditions as integer division
4539 (that is, if integer division on the same two operands would fail, the
4540 remainder cannot be calculated).
4541
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004542 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004543 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004544 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004545 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004546 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004547 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004548 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004549 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004550 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004551 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004552 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004553 Decimal("1.0")
4554 """
4555 return a.__mod__(b, context=self)
4556
4557 def remainder_near(self, a, b):
4558 """Returns to be "a - b * n", where n is the integer nearest the exact
4559 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004560 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004561 sign of a.
4562
4563 This operation will fail under the same conditions as integer division
4564 (that is, if integer division on the same two operands would fail, the
4565 remainder cannot be calculated).
4566
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004567 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004568 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004569 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004570 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004571 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004572 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004573 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004574 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004575 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004576 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004577 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004578 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004579 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004580 Decimal("-0.3")
4581 """
4582 return a.remainder_near(b, context=self)
4583
Facundo Batista353750c2007-09-13 18:13:15 +00004584 def rotate(self, a, b):
4585 """Returns a rotated copy of a, b times.
4586
4587 The coefficient of the result is a rotated copy of the digits in
4588 the coefficient of the first operand. The number of places of
4589 rotation is taken from the absolute value of the second operand,
4590 with the rotation being to the left if the second operand is
4591 positive or to the right otherwise.
4592
4593 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4594 Decimal("400000003")
4595 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4596 Decimal("12")
4597 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4598 Decimal("891234567")
4599 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4600 Decimal("123456789")
4601 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4602 Decimal("345678912")
4603 """
4604 return a.rotate(b, context=self)
4605
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004606 def same_quantum(self, a, b):
4607 """Returns True if the two operands have the same exponent.
4608
4609 The result is never affected by either the sign or the coefficient of
4610 either operand.
4611
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004612 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004613 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004614 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004615 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004616 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004617 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004618 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004619 True
4620 """
4621 return a.same_quantum(b)
4622
Facundo Batista353750c2007-09-13 18:13:15 +00004623 def scaleb (self, a, b):
4624 """Returns the first operand after adding the second value its exp.
4625
4626 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4627 Decimal("0.0750")
4628 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4629 Decimal("7.50")
4630 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4631 Decimal("7.50E+3")
4632 """
4633 return a.scaleb (b, context=self)
4634
4635 def shift(self, a, b):
4636 """Returns a shifted copy of a, b times.
4637
4638 The coefficient of the result is a shifted copy of the digits
4639 in the coefficient of the first operand. The number of places
4640 to shift is taken from the absolute value of the second operand,
4641 with the shift being to the left if the second operand is
4642 positive or to the right otherwise. Digits shifted into the
4643 coefficient are zeros.
4644
4645 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4646 Decimal("400000000")
4647 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4648 Decimal("0")
4649 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4650 Decimal("1234567")
4651 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4652 Decimal("123456789")
4653 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4654 Decimal("345678900")
4655 """
4656 return a.shift(b, context=self)
4657
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004658 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004659 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004660
4661 If the result must be inexact, it is rounded using the round-half-even
4662 algorithm.
4663
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004664 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004665 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004666 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004667 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004668 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004669 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004670 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004671 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004672 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004673 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004674 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004675 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004676 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004677 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004678 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004679 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004680 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004681 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004682 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004683 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004684 """
4685 return a.sqrt(context=self)
4686
4687 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004688 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004689
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004690 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004691 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004692 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004693 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004694 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004695 Decimal("-0.77")
4696 """
4697 return a.__sub__(b, context=self)
4698
4699 def to_eng_string(self, a):
4700 """Converts a number to a string, using scientific notation.
4701
4702 The operation is not affected by the context.
4703 """
4704 return a.to_eng_string(context=self)
4705
4706 def to_sci_string(self, a):
4707 """Converts a number to a string, using scientific notation.
4708
4709 The operation is not affected by the context.
4710 """
4711 return a.__str__(context=self)
4712
Facundo Batista353750c2007-09-13 18:13:15 +00004713 def to_integral_exact(self, a):
4714 """Rounds to an integer.
4715
4716 When the operand has a negative exponent, the result is the same
4717 as using the quantize() operation using the given operand as the
4718 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4719 of the operand as the precision setting; Inexact and Rounded flags
4720 are allowed in this operation. The rounding mode is taken from the
4721 context.
4722
4723 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4724 Decimal("2")
4725 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4726 Decimal("100")
4727 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4728 Decimal("100")
4729 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4730 Decimal("102")
4731 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4732 Decimal("-102")
4733 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4734 Decimal("1.0E+6")
4735 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4736 Decimal("7.89E+77")
4737 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4738 Decimal("-Infinity")
4739 """
4740 return a.to_integral_exact(context=self)
4741
4742 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004743 """Rounds to an integer.
4744
4745 When the operand has a negative exponent, the result is the same
4746 as using the quantize() operation using the given operand as the
4747 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4748 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004749 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004750
Facundo Batista353750c2007-09-13 18:13:15 +00004751 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004752 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004753 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004754 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004755 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004756 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004757 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004758 Decimal("102")
Facundo Batista353750c2007-09-13 18:13:15 +00004759 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004760 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004761 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004762 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004763 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004764 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004765 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004766 Decimal("-Infinity")
4767 """
Facundo Batista353750c2007-09-13 18:13:15 +00004768 return a.to_integral_value(context=self)
4769
4770 # the method name changed, but we provide also the old one, for compatibility
4771 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004772
4773class _WorkRep(object):
4774 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004775 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004776 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004777 # exp: None, int, or string
4778
4779 def __init__(self, value=None):
4780 if value is None:
4781 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004782 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004783 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004784 elif isinstance(value, Decimal):
4785 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004786 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004787 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004788 else:
4789 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004790 self.sign = value[0]
4791 self.int = value[1]
4792 self.exp = value[2]
4793
4794 def __repr__(self):
4795 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4796
4797 __str__ = __repr__
4798
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004799
4800
Facundo Batistae64acfa2007-12-17 14:18:42 +00004801def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004802 """Normalizes op1, op2 to have the same exp and length of coefficient.
4803
4804 Done during addition.
4805 """
Facundo Batista353750c2007-09-13 18:13:15 +00004806 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004807 tmp = op2
4808 other = op1
4809 else:
4810 tmp = op1
4811 other = op2
4812
Facundo Batista353750c2007-09-13 18:13:15 +00004813 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4814 # Then adding 10**exp to tmp has the same effect (after rounding)
4815 # as adding any positive quantity smaller than 10**exp; similarly
4816 # for subtraction. So if other is smaller than 10**exp we replace
4817 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00004818 tmp_len = len(str(tmp.int))
4819 other_len = len(str(other.int))
4820 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4821 if other_len + other.exp - 1 < exp:
4822 other.int = 1
4823 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004824
Facundo Batista353750c2007-09-13 18:13:15 +00004825 tmp.int *= 10 ** (tmp.exp - other.exp)
4826 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004827 return op1, op2
4828
Facundo Batista353750c2007-09-13 18:13:15 +00004829##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4830
4831# This function from Tim Peters was taken from here:
4832# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4833# The correction being in the function definition is for speed, and
4834# the whole function is not resolved with math.log because of avoiding
4835# the use of floats.
4836def _nbits(n, correction = {
4837 '0': 4, '1': 3, '2': 2, '3': 2,
4838 '4': 1, '5': 1, '6': 1, '7': 1,
4839 '8': 0, '9': 0, 'a': 0, 'b': 0,
4840 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4841 """Number of bits in binary representation of the positive integer n,
4842 or 0 if n == 0.
4843 """
4844 if n < 0:
4845 raise ValueError("The argument to _nbits should be nonnegative.")
4846 hex_n = "%x" % n
4847 return 4*len(hex_n) - correction[hex_n[0]]
4848
4849def _sqrt_nearest(n, a):
4850 """Closest integer to the square root of the positive integer n. a is
4851 an initial approximation to the square root. Any positive integer
4852 will do for a, but the closer a is to the square root of n the
4853 faster convergence will be.
4854
4855 """
4856 if n <= 0 or a <= 0:
4857 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4858
4859 b=0
4860 while a != b:
4861 b, a = a, a--n//a>>1
4862 return a
4863
4864def _rshift_nearest(x, shift):
4865 """Given an integer x and a nonnegative integer shift, return closest
4866 integer to x / 2**shift; use round-to-even in case of a tie.
4867
4868 """
4869 b, q = 1L << shift, x >> shift
4870 return q + (2*(x & (b-1)) + (q&1) > b)
4871
4872def _div_nearest(a, b):
4873 """Closest integer to a/b, a and b positive integers; rounds to even
4874 in the case of a tie.
4875
4876 """
4877 q, r = divmod(a, b)
4878 return q + (2*r + (q&1) > b)
4879
4880def _ilog(x, M, L = 8):
4881 """Integer approximation to M*log(x/M), with absolute error boundable
4882 in terms only of x/M.
4883
4884 Given positive integers x and M, return an integer approximation to
4885 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4886 between the approximation and the exact result is at most 22. For
4887 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4888 both cases these are upper bounds on the error; it will usually be
4889 much smaller."""
4890
4891 # The basic algorithm is the following: let log1p be the function
4892 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4893 # the reduction
4894 #
4895 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4896 #
4897 # repeatedly until the argument to log1p is small (< 2**-L in
4898 # absolute value). For small y we can use the Taylor series
4899 # expansion
4900 #
4901 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4902 #
4903 # truncating at T such that y**T is small enough. The whole
4904 # computation is carried out in a form of fixed-point arithmetic,
4905 # with a real number z being represented by an integer
4906 # approximation to z*M. To avoid loss of precision, the y below
4907 # is actually an integer approximation to 2**R*y*M, where R is the
4908 # number of reductions performed so far.
4909
4910 y = x-M
4911 # argument reduction; R = number of reductions performed
4912 R = 0
4913 while (R <= L and long(abs(y)) << L-R >= M or
4914 R > L and abs(y) >> R-L >= M):
4915 y = _div_nearest(long(M*y) << 1,
4916 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4917 R += 1
4918
4919 # Taylor series with T terms
4920 T = -int(-10*len(str(M))//(3*L))
4921 yshift = _rshift_nearest(y, R)
4922 w = _div_nearest(M, T)
4923 for k in xrange(T-1, 0, -1):
4924 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4925
4926 return _div_nearest(w*y, M)
4927
4928def _dlog10(c, e, p):
4929 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4930 approximation to 10**p * log10(c*10**e), with an absolute error of
4931 at most 1. Assumes that c*10**e is not exactly 1."""
4932
4933 # increase precision by 2; compensate for this by dividing
4934 # final result by 100
4935 p += 2
4936
4937 # write c*10**e as d*10**f with either:
4938 # f >= 0 and 1 <= d <= 10, or
4939 # f <= 0 and 0.1 <= d <= 1.
4940 # Thus for c*10**e close to 1, f = 0
4941 l = len(str(c))
4942 f = e+l - (e+l >= 1)
4943
4944 if p > 0:
4945 M = 10**p
4946 k = e+p-f
4947 if k >= 0:
4948 c *= 10**k
4949 else:
4950 c = _div_nearest(c, 10**-k)
4951
4952 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004953 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004954 log_d = _div_nearest(log_d*M, log_10)
4955 log_tenpower = f*M # exact
4956 else:
4957 log_d = 0 # error < 2.31
4958 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4959
4960 return _div_nearest(log_tenpower+log_d, 100)
4961
4962def _dlog(c, e, p):
4963 """Given integers c, e and p with c > 0, compute an integer
4964 approximation to 10**p * log(c*10**e), with an absolute error of
4965 at most 1. Assumes that c*10**e is not exactly 1."""
4966
4967 # Increase precision by 2. The precision increase is compensated
4968 # for at the end with a division by 100.
4969 p += 2
4970
4971 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4972 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4973 # as 10**p * log(d) + 10**p*f * log(10).
4974 l = len(str(c))
4975 f = e+l - (e+l >= 1)
4976
4977 # compute approximation to 10**p*log(d), with error < 27
4978 if p > 0:
4979 k = e+p-f
4980 if k >= 0:
4981 c *= 10**k
4982 else:
4983 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4984
4985 # _ilog magnifies existing error in c by a factor of at most 10
4986 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4987 else:
4988 # p <= 0: just approximate the whole thing by 0; error < 2.31
4989 log_d = 0
4990
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004991 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00004992 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004993 extra = len(str(abs(f)))-1
4994 if p + extra >= 0:
4995 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4996 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4997 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00004998 else:
4999 f_log_ten = 0
5000 else:
5001 f_log_ten = 0
5002
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005003 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005004 return _div_nearest(f_log_ten + log_d, 100)
5005
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005006class _Log10Memoize(object):
5007 """Class to compute, store, and allow retrieval of, digits of the
5008 constant log(10) = 2.302585.... This constant is needed by
5009 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5010 def __init__(self):
5011 self.digits = "23025850929940456840179914546843642076011014886"
5012
5013 def getdigits(self, p):
5014 """Given an integer p >= 0, return floor(10**p)*log(10).
5015
5016 For example, self.getdigits(3) returns 2302.
5017 """
5018 # digits are stored as a string, for quick conversion to
5019 # integer in the case that we've already computed enough
5020 # digits; the stored digits should always be correct
5021 # (truncated, not rounded to nearest).
5022 if p < 0:
5023 raise ValueError("p should be nonnegative")
5024
5025 if p >= len(self.digits):
5026 # compute p+3, p+6, p+9, ... digits; continue until at
5027 # least one of the extra digits is nonzero
5028 extra = 3
5029 while True:
5030 # compute p+extra digits, correct to within 1ulp
5031 M = 10**(p+extra+2)
5032 digits = str(_div_nearest(_ilog(10*M, M), 100))
5033 if digits[-extra:] != '0'*extra:
5034 break
5035 extra += 3
5036 # keep all reliable digits so far; remove trailing zeros
5037 # and next nonzero digit
5038 self.digits = digits.rstrip('0')[:-1]
5039 return int(self.digits[:p+1])
5040
5041_log10_digits = _Log10Memoize().getdigits
5042
Facundo Batista353750c2007-09-13 18:13:15 +00005043def _iexp(x, M, L=8):
5044 """Given integers x and M, M > 0, such that x/M is small in absolute
5045 value, compute an integer approximation to M*exp(x/M). For 0 <=
5046 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5047 is usually much smaller)."""
5048
5049 # Algorithm: to compute exp(z) for a real number z, first divide z
5050 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5051 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5052 # series
5053 #
5054 # expm1(x) = x + x**2/2! + x**3/3! + ...
5055 #
5056 # Now use the identity
5057 #
5058 # expm1(2x) = expm1(x)*(expm1(x)+2)
5059 #
5060 # R times to compute the sequence expm1(z/2**R),
5061 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5062
5063 # Find R such that x/2**R/M <= 2**-L
5064 R = _nbits((long(x)<<L)//M)
5065
5066 # Taylor series. (2**L)**T > M
5067 T = -int(-10*len(str(M))//(3*L))
5068 y = _div_nearest(x, T)
5069 Mshift = long(M)<<R
5070 for i in xrange(T-1, 0, -1):
5071 y = _div_nearest(x*(Mshift + y), Mshift * i)
5072
5073 # Expansion
5074 for k in xrange(R-1, -1, -1):
5075 Mshift = long(M)<<(k+2)
5076 y = _div_nearest(y*(y+Mshift), Mshift)
5077
5078 return M+y
5079
5080def _dexp(c, e, p):
5081 """Compute an approximation to exp(c*10**e), with p decimal places of
5082 precision.
5083
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005084 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005085
5086 10**(p-1) <= d <= 10**p, and
5087 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5088
5089 In other words, d*10**f is an approximation to exp(c*10**e) with p
5090 digits of precision, and with an error in d of at most 1. This is
5091 almost, but not quite, the same as the error being < 1ulp: when d
5092 = 10**(p-1) the error could be up to 10 ulp."""
5093
5094 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5095 p += 2
5096
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005097 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005098 extra = max(0, e + len(str(c)) - 1)
5099 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005100
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005101 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005102 # rounding down
5103 shift = e+q
5104 if shift >= 0:
5105 cshift = c*10**shift
5106 else:
5107 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005108 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005109
5110 # reduce remainder back to original precision
5111 rem = _div_nearest(rem, 10**extra)
5112
5113 # error in result of _iexp < 120; error after division < 0.62
5114 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5115
5116def _dpower(xc, xe, yc, ye, p):
5117 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5118 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5119
5120 10**(p-1) <= c <= 10**p, and
5121 (c-1)*10**e < x**y < (c+1)*10**e
5122
5123 in other words, c*10**e is an approximation to x**y with p digits
5124 of precision, and with an error in c of at most 1. (This is
5125 almost, but not quite, the same as the error being < 1ulp: when c
5126 == 10**(p-1) we can only guarantee error < 10ulp.)
5127
5128 We assume that: x is positive and not equal to 1, and y is nonzero.
5129 """
5130
5131 # Find b such that 10**(b-1) <= |y| <= 10**b
5132 b = len(str(abs(yc))) + ye
5133
5134 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5135 lxc = _dlog(xc, xe, p+b+1)
5136
5137 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5138 shift = ye-b
5139 if shift >= 0:
5140 pc = lxc*yc*10**shift
5141 else:
5142 pc = _div_nearest(lxc*yc, 10**-shift)
5143
5144 if pc == 0:
5145 # we prefer a result that isn't exactly 1; this makes it
5146 # easier to compute a correctly rounded result in __pow__
5147 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5148 coeff, exp = 10**(p-1)+1, 1-p
5149 else:
5150 coeff, exp = 10**p-1, -p
5151 else:
5152 coeff, exp = _dexp(pc, -(p+1), p+1)
5153 coeff = _div_nearest(coeff, 10)
5154 exp += 1
5155
5156 return coeff, exp
5157
5158def _log10_lb(c, correction = {
5159 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5160 '6': 23, '7': 16, '8': 10, '9': 5}):
5161 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5162 if c <= 0:
5163 raise ValueError("The argument to _log10_lb should be nonnegative.")
5164 str_c = str(c)
5165 return 100*len(str_c) - correction[str_c[0]]
5166
Facundo Batista59c58842007-04-10 12:58:45 +00005167##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005168
Facundo Batista353750c2007-09-13 18:13:15 +00005169def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005170 """Convert other to Decimal.
5171
5172 Verifies that it's ok to use in an implicit construction.
5173 """
5174 if isinstance(other, Decimal):
5175 return other
5176 if isinstance(other, (int, long)):
5177 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005178 if raiseit:
5179 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005180 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005181
Facundo Batista59c58842007-04-10 12:58:45 +00005182##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005183
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005184# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005185# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005186
5187DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005188 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005189 traps=[DivisionByZero, Overflow, InvalidOperation],
5190 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005191 Emax=999999999,
5192 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005193 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005194)
5195
5196# Pre-made alternate contexts offered by the specification
5197# Don't change these; the user should be able to select these
5198# contexts and be able to reproduce results from other implementations
5199# of the spec.
5200
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005201BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005202 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005203 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5204 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005205)
5206
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005207ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005208 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005209 traps=[],
5210 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005211)
5212
5213
Facundo Batista72bc54f2007-11-23 17:59:00 +00005214##### crud for parsing strings #############################################
5215import re
5216
5217# Regular expression used for parsing numeric strings. Additional
5218# comments:
5219#
5220# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5221# whitespace. But note that the specification disallows whitespace in
5222# a numeric string.
5223#
5224# 2. For finite numbers (not infinities and NaNs) the body of the
5225# number between the optional sign and the optional exponent must have
5226# at least one decimal digit, possibly after the decimal point. The
5227# lookahead expression '(?=\d|\.\d)' checks this.
5228#
5229# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5230# other meaning for \d than the numbers [0-9].
5231
5232import re
5233_parser = re.compile(r""" # A numeric string consists of:
5234# \s*
5235 (?P<sign>[-+])? # an optional sign, followed by either...
5236 (
5237 (?=\d|\.\d) # ...a number (with at least one digit)
5238 (?P<int>\d*) # consisting of a (possibly empty) integer part
5239 (\.(?P<frac>\d*))? # followed by an optional fractional part
5240 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5241 |
5242 Inf(inity)? # ...an infinity, or...
5243 |
5244 (?P<signal>s)? # ...an (optionally signaling)
5245 NaN # NaN
5246 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5247 )
5248# \s*
Mark Dickinson59bc20b2008-01-12 01:56:00 +00005249 \Z
Facundo Batista72bc54f2007-11-23 17:59:00 +00005250""", re.VERBOSE | re.IGNORECASE).match
5251
Facundo Batista2ec74152007-12-03 17:55:00 +00005252_all_zeros = re.compile('0*$').match
5253_exact_half = re.compile('50*$').match
Facundo Batista72bc54f2007-11-23 17:59:00 +00005254del re
5255
5256
Facundo Batista59c58842007-04-10 12:58:45 +00005257##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005258
Facundo Batista59c58842007-04-10 12:58:45 +00005259# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005260Inf = Decimal('Inf')
5261negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005262NaN = Decimal('NaN')
5263Dec_0 = Decimal(0)
5264Dec_p1 = Decimal(1)
5265Dec_n1 = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005266
Facundo Batista59c58842007-04-10 12:58:45 +00005267# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005268Infsign = (Inf, negInf)
5269
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005270
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005271
5272if __name__ == '__main__':
5273 import doctest, sys
5274 doctest.testmod(sys.modules[__name__])