blob: 4f23d33d0de2eb66c25b55b98133e2e6fbe84ccf [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 Hettinger7c85fa42004-07-01 11:01:35 +00001522 def __long__(self):
1523 """Converts to a long.
1524
1525 Equivalent to long(int(self))
1526 """
1527 return long(self.__int__())
1528
Facundo Batista353750c2007-09-13 18:13:15 +00001529 def _fix_nan(self, context):
1530 """Decapitate the payload of a NaN to fit the context"""
1531 payload = self._int
1532
1533 # maximum length of payload is precision if _clamp=0,
1534 # precision-1 if _clamp=1.
1535 max_payload_len = context.prec - context._clamp
1536 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001537 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1538 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001539 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001540
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001541 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001542 """Round if it is necessary to keep self within prec precision.
1543
1544 Rounds and fixes the exponent. Does not raise on a sNaN.
1545
1546 Arguments:
1547 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001548 context - context used.
1549 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001550
Facundo Batista353750c2007-09-13 18:13:15 +00001551 if self._is_special:
1552 if self._isnan():
1553 # decapitate payload if necessary
1554 return self._fix_nan(context)
1555 else:
1556 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001557 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001558
Facundo Batista353750c2007-09-13 18:13:15 +00001559 # if self is zero then exponent should be between Etiny and
1560 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1561 Etiny = context.Etiny()
1562 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001563 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001564 exp_max = [context.Emax, Etop][context._clamp]
1565 new_exp = min(max(self._exp, Etiny), exp_max)
1566 if new_exp != self._exp:
1567 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001568 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001569 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001570 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001571
1572 # exp_min is the smallest allowable exponent of the result,
1573 # equal to max(self.adjusted()-context.prec+1, Etiny)
1574 exp_min = len(self._int) + self._exp - context.prec
1575 if exp_min > Etop:
1576 # overflow: exp_min > Etop iff self.adjusted() > Emax
1577 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001578 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001579 return context._raise_error(Overflow, 'above Emax', self._sign)
1580 self_is_subnormal = exp_min < Etiny
1581 if self_is_subnormal:
1582 context._raise_error(Subnormal)
1583 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001584
Facundo Batista353750c2007-09-13 18:13:15 +00001585 # round if self has too many digits
1586 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001587 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001588 digits = len(self._int) + self._exp - exp_min
1589 if digits < 0:
1590 self = _dec_from_triple(self._sign, '1', exp_min-1)
1591 digits = 0
1592 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1593 changed = this_function(digits)
1594 coeff = self._int[:digits] or '0'
1595 if changed == 1:
1596 coeff = str(int(coeff)+1)
1597 ans = _dec_from_triple(self._sign, coeff, exp_min)
1598
1599 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001600 context._raise_error(Inexact)
1601 if self_is_subnormal:
1602 context._raise_error(Underflow)
1603 if not ans:
1604 # raise Clamped on underflow to 0
1605 context._raise_error(Clamped)
1606 elif len(ans._int) == context.prec+1:
1607 # we get here only if rescaling rounds the
1608 # cofficient up to exactly 10**context.prec
1609 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001610 ans = _dec_from_triple(ans._sign,
1611 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001612 else:
1613 # Inexact and Rounded have already been raised
1614 ans = context._raise_error(Overflow, 'above Emax',
1615 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001616 return ans
1617
Facundo Batista353750c2007-09-13 18:13:15 +00001618 # fold down if _clamp == 1 and self has too few digits
1619 if context._clamp == 1 and self._exp > Etop:
1620 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001621 self_padded = self._int + '0'*(self._exp - Etop)
1622 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001623
Facundo Batista353750c2007-09-13 18:13:15 +00001624 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001625 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001626
1627 _pick_rounding_function = {}
1628
Facundo Batista353750c2007-09-13 18:13:15 +00001629 # for each of the rounding functions below:
1630 # self is a finite, nonzero Decimal
1631 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001632 #
1633 # each function returns either -1, 0, or 1, as follows:
1634 # 1 indicates that self should be rounded up (away from zero)
1635 # 0 indicates that self should be truncated, and that all the
1636 # digits to be truncated are zeros (so the value is unchanged)
1637 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001638
1639 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001640 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001641 if _all_zeros(self._int, prec):
1642 return 0
1643 else:
1644 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001645
Facundo Batista353750c2007-09-13 18:13:15 +00001646 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001647 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001648 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001649
Facundo Batista353750c2007-09-13 18:13:15 +00001650 def _round_half_up(self, prec):
1651 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001652 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001653 return 1
1654 elif _all_zeros(self._int, prec):
1655 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001656 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001657 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001658
1659 def _round_half_down(self, prec):
1660 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001661 if _exact_half(self._int, prec):
1662 return -1
1663 else:
1664 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001665
1666 def _round_half_even(self, prec):
1667 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001668 if _exact_half(self._int, prec) and \
1669 (prec == 0 or self._int[prec-1] in '02468'):
1670 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001671 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001672 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001673
1674 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001675 """Rounds up (not away from 0 if negative.)"""
1676 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001677 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001678 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001679 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001680
Facundo Batista353750c2007-09-13 18:13:15 +00001681 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001682 """Rounds down (not towards 0 if negative)"""
1683 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001684 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001685 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001686 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001687
Facundo Batista353750c2007-09-13 18:13:15 +00001688 def _round_05up(self, prec):
1689 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001690 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001691 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001692 else:
1693 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001694
Facundo Batista353750c2007-09-13 18:13:15 +00001695 def fma(self, other, third, context=None):
1696 """Fused multiply-add.
1697
1698 Returns self*other+third with no rounding of the intermediate
1699 product self*other.
1700
1701 self and other are multiplied together, with no rounding of
1702 the result. The third operand is then added to the result,
1703 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001704 """
Facundo Batista353750c2007-09-13 18:13:15 +00001705
1706 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001707
1708 # compute product; raise InvalidOperation if either operand is
1709 # a signaling NaN or if the product is zero times infinity.
1710 if self._is_special or other._is_special:
1711 if context is None:
1712 context = getcontext()
1713 if self._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001714 return context._raise_error(InvalidOperation, 'sNaN', self)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001715 if other._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001716 return context._raise_error(InvalidOperation, 'sNaN', other)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001717 if self._exp == 'n':
1718 product = self
1719 elif other._exp == 'n':
1720 product = other
1721 elif self._exp == 'F':
1722 if not other:
1723 return context._raise_error(InvalidOperation,
1724 'INF * 0 in fma')
1725 product = Infsign[self._sign ^ other._sign]
1726 elif other._exp == 'F':
1727 if not self:
1728 return context._raise_error(InvalidOperation,
1729 '0 * INF in fma')
1730 product = Infsign[self._sign ^ other._sign]
1731 else:
1732 product = _dec_from_triple(self._sign ^ other._sign,
1733 str(int(self._int) * int(other._int)),
1734 self._exp + other._exp)
1735
Facundo Batista353750c2007-09-13 18:13:15 +00001736 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001737 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001738
Facundo Batista353750c2007-09-13 18:13:15 +00001739 def _power_modulo(self, other, modulo, context=None):
1740 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001741
Facundo Batista353750c2007-09-13 18:13:15 +00001742 # if can't convert other and modulo to Decimal, raise
1743 # TypeError; there's no point returning NotImplemented (no
1744 # equivalent of __rpow__ for three argument pow)
1745 other = _convert_other(other, raiseit=True)
1746 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001747
Facundo Batista353750c2007-09-13 18:13:15 +00001748 if context is None:
1749 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001750
Facundo Batista353750c2007-09-13 18:13:15 +00001751 # deal with NaNs: if there are any sNaNs then first one wins,
1752 # (i.e. behaviour for NaNs is identical to that of fma)
1753 self_is_nan = self._isnan()
1754 other_is_nan = other._isnan()
1755 modulo_is_nan = modulo._isnan()
1756 if self_is_nan or other_is_nan or modulo_is_nan:
1757 if self_is_nan == 2:
1758 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001759 self)
Facundo Batista353750c2007-09-13 18:13:15 +00001760 if other_is_nan == 2:
1761 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001762 other)
Facundo Batista353750c2007-09-13 18:13:15 +00001763 if modulo_is_nan == 2:
1764 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001765 modulo)
Facundo Batista353750c2007-09-13 18:13:15 +00001766 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001767 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001768 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001769 return other._fix_nan(context)
1770 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001771
Facundo Batista353750c2007-09-13 18:13:15 +00001772 # check inputs: we apply same restrictions as Python's pow()
1773 if not (self._isinteger() and
1774 other._isinteger() and
1775 modulo._isinteger()):
1776 return context._raise_error(InvalidOperation,
1777 'pow() 3rd argument not allowed '
1778 'unless all arguments are integers')
1779 if other < 0:
1780 return context._raise_error(InvalidOperation,
1781 'pow() 2nd argument cannot be '
1782 'negative when 3rd argument specified')
1783 if not modulo:
1784 return context._raise_error(InvalidOperation,
1785 'pow() 3rd argument cannot be 0')
1786
1787 # additional restriction for decimal: the modulus must be less
1788 # than 10**prec in absolute value
1789 if modulo.adjusted() >= context.prec:
1790 return context._raise_error(InvalidOperation,
1791 'insufficient precision: pow() 3rd '
1792 'argument must not have more than '
1793 'precision digits')
1794
1795 # define 0**0 == NaN, for consistency with two-argument pow
1796 # (even though it hurts!)
1797 if not other and not self:
1798 return context._raise_error(InvalidOperation,
1799 'at least one of pow() 1st argument '
1800 'and 2nd argument must be nonzero ;'
1801 '0**0 is not defined')
1802
1803 # compute sign of result
1804 if other._iseven():
1805 sign = 0
1806 else:
1807 sign = self._sign
1808
1809 # convert modulo to a Python integer, and self and other to
1810 # Decimal integers (i.e. force their exponents to be >= 0)
1811 modulo = abs(int(modulo))
1812 base = _WorkRep(self.to_integral_value())
1813 exponent = _WorkRep(other.to_integral_value())
1814
1815 # compute result using integer pow()
1816 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1817 for i in xrange(exponent.exp):
1818 base = pow(base, 10, modulo)
1819 base = pow(base, exponent.int, modulo)
1820
Facundo Batista72bc54f2007-11-23 17:59:00 +00001821 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001822
1823 def _power_exact(self, other, p):
1824 """Attempt to compute self**other exactly.
1825
1826 Given Decimals self and other and an integer p, attempt to
1827 compute an exact result for the power self**other, with p
1828 digits of precision. Return None if self**other is not
1829 exactly representable in p digits.
1830
1831 Assumes that elimination of special cases has already been
1832 performed: self and other must both be nonspecial; self must
1833 be positive and not numerically equal to 1; other must be
1834 nonzero. For efficiency, other._exp should not be too large,
1835 so that 10**abs(other._exp) is a feasible calculation."""
1836
1837 # In the comments below, we write x for the value of self and
1838 # y for the value of other. Write x = xc*10**xe and y =
1839 # yc*10**ye.
1840
1841 # The main purpose of this method is to identify the *failure*
1842 # of x**y to be exactly representable with as little effort as
1843 # possible. So we look for cheap and easy tests that
1844 # eliminate the possibility of x**y being exact. Only if all
1845 # these tests are passed do we go on to actually compute x**y.
1846
1847 # Here's the main idea. First normalize both x and y. We
1848 # express y as a rational m/n, with m and n relatively prime
1849 # and n>0. Then for x**y to be exactly representable (at
1850 # *any* precision), xc must be the nth power of a positive
1851 # integer and xe must be divisible by n. If m is negative
1852 # then additionally xc must be a power of either 2 or 5, hence
1853 # a power of 2**n or 5**n.
1854 #
1855 # There's a limit to how small |y| can be: if y=m/n as above
1856 # then:
1857 #
1858 # (1) if xc != 1 then for the result to be representable we
1859 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1860 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1861 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1862 # representable.
1863 #
1864 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1865 # |y| < 1/|xe| then the result is not representable.
1866 #
1867 # Note that since x is not equal to 1, at least one of (1) and
1868 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1869 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1870 #
1871 # There's also a limit to how large y can be, at least if it's
1872 # positive: the normalized result will have coefficient xc**y,
1873 # so if it's representable then xc**y < 10**p, and y <
1874 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1875 # not exactly representable.
1876
1877 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1878 # so |y| < 1/xe and the result is not representable.
1879 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1880 # < 1/nbits(xc).
1881
1882 x = _WorkRep(self)
1883 xc, xe = x.int, x.exp
1884 while xc % 10 == 0:
1885 xc //= 10
1886 xe += 1
1887
1888 y = _WorkRep(other)
1889 yc, ye = y.int, y.exp
1890 while yc % 10 == 0:
1891 yc //= 10
1892 ye += 1
1893
1894 # case where xc == 1: result is 10**(xe*y), with xe*y
1895 # required to be an integer
1896 if xc == 1:
1897 if ye >= 0:
1898 exponent = xe*yc*10**ye
1899 else:
1900 exponent, remainder = divmod(xe*yc, 10**-ye)
1901 if remainder:
1902 return None
1903 if y.sign == 1:
1904 exponent = -exponent
1905 # if other is a nonnegative integer, use ideal exponent
1906 if other._isinteger() and other._sign == 0:
1907 ideal_exponent = self._exp*int(other)
1908 zeros = min(exponent-ideal_exponent, p-1)
1909 else:
1910 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001911 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001912
1913 # case where y is negative: xc must be either a power
1914 # of 2 or a power of 5.
1915 if y.sign == 1:
1916 last_digit = xc % 10
1917 if last_digit in (2,4,6,8):
1918 # quick test for power of 2
1919 if xc & -xc != xc:
1920 return None
1921 # now xc is a power of 2; e is its exponent
1922 e = _nbits(xc)-1
1923 # find e*y and xe*y; both must be integers
1924 if ye >= 0:
1925 y_as_int = yc*10**ye
1926 e = e*y_as_int
1927 xe = xe*y_as_int
1928 else:
1929 ten_pow = 10**-ye
1930 e, remainder = divmod(e*yc, ten_pow)
1931 if remainder:
1932 return None
1933 xe, remainder = divmod(xe*yc, ten_pow)
1934 if remainder:
1935 return None
1936
1937 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1938 return None
1939 xc = 5**e
1940
1941 elif last_digit == 5:
1942 # e >= log_5(xc) if xc is a power of 5; we have
1943 # equality all the way up to xc=5**2658
1944 e = _nbits(xc)*28//65
1945 xc, remainder = divmod(5**e, xc)
1946 if remainder:
1947 return None
1948 while xc % 5 == 0:
1949 xc //= 5
1950 e -= 1
1951 if ye >= 0:
1952 y_as_integer = yc*10**ye
1953 e = e*y_as_integer
1954 xe = xe*y_as_integer
1955 else:
1956 ten_pow = 10**-ye
1957 e, remainder = divmod(e*yc, ten_pow)
1958 if remainder:
1959 return None
1960 xe, remainder = divmod(xe*yc, ten_pow)
1961 if remainder:
1962 return None
1963 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1964 return None
1965 xc = 2**e
1966 else:
1967 return None
1968
1969 if xc >= 10**p:
1970 return None
1971 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00001972 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00001973
1974 # now y is positive; find m and n such that y = m/n
1975 if ye >= 0:
1976 m, n = yc*10**ye, 1
1977 else:
1978 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1979 return None
1980 xc_bits = _nbits(xc)
1981 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1982 return None
1983 m, n = yc, 10**(-ye)
1984 while m % 2 == n % 2 == 0:
1985 m //= 2
1986 n //= 2
1987 while m % 5 == n % 5 == 0:
1988 m //= 5
1989 n //= 5
1990
1991 # compute nth root of xc*10**xe
1992 if n > 1:
1993 # if 1 < xc < 2**n then xc isn't an nth power
1994 if xc != 1 and xc_bits <= n:
1995 return None
1996
1997 xe, rem = divmod(xe, n)
1998 if rem != 0:
1999 return None
2000
2001 # compute nth root of xc using Newton's method
2002 a = 1L << -(-_nbits(xc)//n) # initial estimate
2003 while True:
2004 q, r = divmod(xc, a**(n-1))
2005 if a <= q:
2006 break
2007 else:
2008 a = (a*(n-1) + q)//n
2009 if not (a == q and r == 0):
2010 return None
2011 xc = a
2012
2013 # now xc*10**xe is the nth root of the original xc*10**xe
2014 # compute mth power of xc*10**xe
2015
2016 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2017 # 10**p and the result is not representable.
2018 if xc > 1 and m > p*100//_log10_lb(xc):
2019 return None
2020 xc = xc**m
2021 xe *= m
2022 if xc > 10**p:
2023 return None
2024
2025 # by this point the result *is* exactly representable
2026 # adjust the exponent to get as close as possible to the ideal
2027 # exponent, if necessary
2028 str_xc = str(xc)
2029 if other._isinteger() and other._sign == 0:
2030 ideal_exponent = self._exp*int(other)
2031 zeros = min(xe-ideal_exponent, p-len(str_xc))
2032 else:
2033 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002034 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00002035
2036 def __pow__(self, other, modulo=None, context=None):
2037 """Return self ** other [ % modulo].
2038
2039 With two arguments, compute self**other.
2040
2041 With three arguments, compute (self**other) % modulo. For the
2042 three argument form, the following restrictions on the
2043 arguments hold:
2044
2045 - all three arguments must be integral
2046 - other must be nonnegative
2047 - either self or other (or both) must be nonzero
2048 - modulo must be nonzero and must have at most p digits,
2049 where p is the context precision.
2050
2051 If any of these restrictions is violated the InvalidOperation
2052 flag is raised.
2053
2054 The result of pow(self, other, modulo) is identical to the
2055 result that would be obtained by computing (self**other) %
2056 modulo with unbounded precision, but is computed more
2057 efficiently. It is always exact.
2058 """
2059
2060 if modulo is not None:
2061 return self._power_modulo(other, modulo, context)
2062
2063 other = _convert_other(other)
2064 if other is NotImplemented:
2065 return other
2066
2067 if context is None:
2068 context = getcontext()
2069
2070 # either argument is a NaN => result is NaN
2071 ans = self._check_nans(other, context)
2072 if ans:
2073 return ans
2074
2075 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2076 if not other:
2077 if not self:
2078 return context._raise_error(InvalidOperation, '0 ** 0')
2079 else:
2080 return Dec_p1
2081
2082 # result has sign 1 iff self._sign is 1 and other is an odd integer
2083 result_sign = 0
2084 if self._sign == 1:
2085 if other._isinteger():
2086 if not other._iseven():
2087 result_sign = 1
2088 else:
2089 # -ve**noninteger = NaN
2090 # (-0)**noninteger = 0**noninteger
2091 if self:
2092 return context._raise_error(InvalidOperation,
2093 'x ** y with x negative and y not an integer')
2094 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002095 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002096
2097 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2098 if not self:
2099 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002100 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002101 else:
2102 return Infsign[result_sign]
2103
2104 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002105 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002106 if other._sign == 0:
2107 return Infsign[result_sign]
2108 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002109 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002110
Facundo Batista353750c2007-09-13 18:13:15 +00002111 # 1**other = 1, but the choice of exponent and the flags
2112 # depend on the exponent of self, and on whether other is a
2113 # positive integer, a negative integer, or neither
2114 if self == Dec_p1:
2115 if other._isinteger():
2116 # exp = max(self._exp*max(int(other), 0),
2117 # 1-context.prec) but evaluating int(other) directly
2118 # is dangerous until we know other is small (other
2119 # could be 1e999999999)
2120 if other._sign == 1:
2121 multiplier = 0
2122 elif other > context.prec:
2123 multiplier = context.prec
2124 else:
2125 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002126
Facundo Batista353750c2007-09-13 18:13:15 +00002127 exp = self._exp * multiplier
2128 if exp < 1-context.prec:
2129 exp = 1-context.prec
2130 context._raise_error(Rounded)
2131 else:
2132 context._raise_error(Inexact)
2133 context._raise_error(Rounded)
2134 exp = 1-context.prec
2135
Facundo Batista72bc54f2007-11-23 17:59:00 +00002136 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002137
2138 # compute adjusted exponent of self
2139 self_adj = self.adjusted()
2140
2141 # self ** infinity is infinity if self > 1, 0 if self < 1
2142 # self ** -infinity is infinity if self < 1, 0 if self > 1
2143 if other._isinfinity():
2144 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002145 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002146 else:
2147 return Infsign[result_sign]
2148
2149 # from here on, the result always goes through the call
2150 # to _fix at the end of this function.
2151 ans = None
2152
2153 # crude test to catch cases of extreme overflow/underflow. If
2154 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2155 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2156 # self**other >= 10**(Emax+1), so overflow occurs. The test
2157 # for underflow is similar.
2158 bound = self._log10_exp_bound() + other.adjusted()
2159 if (self_adj >= 0) == (other._sign == 0):
2160 # self > 1 and other +ve, or self < 1 and other -ve
2161 # possibility of overflow
2162 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002163 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002164 else:
2165 # self > 1 and other -ve, or self < 1 and other +ve
2166 # possibility of underflow to 0
2167 Etiny = context.Etiny()
2168 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002169 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002170
2171 # try for an exact result with precision +1
2172 if ans is None:
2173 ans = self._power_exact(other, context.prec + 1)
2174 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002175 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002176
2177 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2178 if ans is None:
2179 p = context.prec
2180 x = _WorkRep(self)
2181 xc, xe = x.int, x.exp
2182 y = _WorkRep(other)
2183 yc, ye = y.int, y.exp
2184 if y.sign == 1:
2185 yc = -yc
2186
2187 # compute correctly rounded result: start with precision +3,
2188 # then increase precision until result is unambiguously roundable
2189 extra = 3
2190 while True:
2191 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2192 if coeff % (5*10**(len(str(coeff))-p-1)):
2193 break
2194 extra += 3
2195
Facundo Batista72bc54f2007-11-23 17:59:00 +00002196 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002197
2198 # the specification says that for non-integer other we need to
2199 # raise Inexact, even when the result is actually exact. In
2200 # the same way, we need to raise Underflow here if the result
2201 # is subnormal. (The call to _fix will take care of raising
2202 # Rounded and Subnormal, as usual.)
2203 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002204 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002205 # pad with zeros up to length context.prec+1 if necessary
2206 if len(ans._int) <= context.prec:
2207 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002208 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2209 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002210 if ans.adjusted() < context.Emin:
2211 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002212
Facundo Batista353750c2007-09-13 18:13:15 +00002213 # unlike exp, ln and log10, the power function respects the
2214 # rounding mode; no need to use ROUND_HALF_EVEN here
2215 ans = ans._fix(context)
2216 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002217
2218 def __rpow__(self, other, context=None):
2219 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002220 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002221 if other is NotImplemented:
2222 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002223 return other.__pow__(self, context=context)
2224
2225 def normalize(self, context=None):
2226 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002227
Facundo Batista353750c2007-09-13 18:13:15 +00002228 if context is None:
2229 context = getcontext()
2230
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002231 if self._is_special:
2232 ans = self._check_nans(context=context)
2233 if ans:
2234 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002235
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002236 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002237 if dup._isinfinity():
2238 return dup
2239
2240 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002241 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002242 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002243 end = len(dup._int)
2244 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002245 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002246 exp += 1
2247 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002248 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002249
Facundo Batistabd2fe832007-09-13 18:42:09 +00002250 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002251 """Quantize self so its exponent is the same as that of exp.
2252
2253 Similar to self._rescale(exp._exp) but with error checking.
2254 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002255 exp = _convert_other(exp, raiseit=True)
2256
Facundo Batista353750c2007-09-13 18:13:15 +00002257 if context is None:
2258 context = getcontext()
2259 if rounding is None:
2260 rounding = context.rounding
2261
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002262 if self._is_special or exp._is_special:
2263 ans = self._check_nans(exp, context)
2264 if ans:
2265 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002266
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002267 if exp._isinfinity() or self._isinfinity():
2268 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002269 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002270 return context._raise_error(InvalidOperation,
2271 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002272
Facundo Batistabd2fe832007-09-13 18:42:09 +00002273 # if we're not watching exponents, do a simple rescale
2274 if not watchexp:
2275 ans = self._rescale(exp._exp, rounding)
2276 # raise Inexact and Rounded where appropriate
2277 if ans._exp > self._exp:
2278 context._raise_error(Rounded)
2279 if ans != self:
2280 context._raise_error(Inexact)
2281 return ans
2282
Facundo Batista353750c2007-09-13 18:13:15 +00002283 # exp._exp should be between Etiny and Emax
2284 if not (context.Etiny() <= exp._exp <= context.Emax):
2285 return context._raise_error(InvalidOperation,
2286 'target exponent out of bounds in quantize')
2287
2288 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002289 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002290 return ans._fix(context)
2291
2292 self_adjusted = self.adjusted()
2293 if self_adjusted > context.Emax:
2294 return context._raise_error(InvalidOperation,
2295 'exponent of quantize result too large for current context')
2296 if self_adjusted - exp._exp + 1 > context.prec:
2297 return context._raise_error(InvalidOperation,
2298 'quantize result has too many digits for current context')
2299
2300 ans = self._rescale(exp._exp, rounding)
2301 if ans.adjusted() > context.Emax:
2302 return context._raise_error(InvalidOperation,
2303 'exponent of quantize result too large for current context')
2304 if len(ans._int) > context.prec:
2305 return context._raise_error(InvalidOperation,
2306 'quantize result has too many digits for current context')
2307
2308 # raise appropriate flags
2309 if ans._exp > self._exp:
2310 context._raise_error(Rounded)
2311 if ans != self:
2312 context._raise_error(Inexact)
2313 if ans and ans.adjusted() < context.Emin:
2314 context._raise_error(Subnormal)
2315
2316 # call to fix takes care of any necessary folddown
2317 ans = ans._fix(context)
2318 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002319
2320 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002321 """Return True if self and other have the same exponent; otherwise
2322 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002323
Facundo Batista1a191df2007-10-02 17:01:24 +00002324 If either operand is a special value, the following rules are used:
2325 * return True if both operands are infinities
2326 * return True if both operands are NaNs
2327 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002328 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002329 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002330 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002331 return (self.is_nan() and other.is_nan() or
2332 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002333 return self._exp == other._exp
2334
Facundo Batista353750c2007-09-13 18:13:15 +00002335 def _rescale(self, exp, rounding):
2336 """Rescale self so that the exponent is exp, either by padding with zeros
2337 or by truncating digits, using the given rounding mode.
2338
2339 Specials are returned without change. This operation is
2340 quiet: it raises no flags, and uses no information from the
2341 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002342
2343 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002344 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002345 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002346 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002347 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002348 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002349 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002350
Facundo Batista353750c2007-09-13 18:13:15 +00002351 if self._exp >= exp:
2352 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002353 return _dec_from_triple(self._sign,
2354 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002355
Facundo Batista353750c2007-09-13 18:13:15 +00002356 # too many digits; round and lose data. If self.adjusted() <
2357 # exp-1, replace self by 10**(exp-1) before rounding
2358 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002359 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002360 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002361 digits = 0
2362 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002363 changed = this_function(digits)
2364 coeff = self._int[:digits] or '0'
2365 if changed == 1:
2366 coeff = str(int(coeff)+1)
2367 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002368
Facundo Batista353750c2007-09-13 18:13:15 +00002369 def to_integral_exact(self, rounding=None, context=None):
2370 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002371
Facundo Batista353750c2007-09-13 18:13:15 +00002372 If no rounding mode is specified, take the rounding mode from
2373 the context. This method raises the Rounded and Inexact flags
2374 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002375
Facundo Batista353750c2007-09-13 18:13:15 +00002376 See also: to_integral_value, which does exactly the same as
2377 this method except that it doesn't raise Inexact or Rounded.
2378 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002379 if self._is_special:
2380 ans = self._check_nans(context=context)
2381 if ans:
2382 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002383 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002384 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002385 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002386 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002387 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002388 if context is None:
2389 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002390 if rounding is None:
2391 rounding = context.rounding
2392 context._raise_error(Rounded)
2393 ans = self._rescale(0, rounding)
2394 if ans != self:
2395 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002396 return ans
2397
Facundo Batista353750c2007-09-13 18:13:15 +00002398 def to_integral_value(self, rounding=None, context=None):
2399 """Rounds to the nearest integer, without raising inexact, rounded."""
2400 if context is None:
2401 context = getcontext()
2402 if rounding is None:
2403 rounding = context.rounding
2404 if self._is_special:
2405 ans = self._check_nans(context=context)
2406 if ans:
2407 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002408 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002409 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002410 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002411 else:
2412 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002413
Facundo Batista353750c2007-09-13 18:13:15 +00002414 # the method name changed, but we provide also the old one, for compatibility
2415 to_integral = to_integral_value
2416
2417 def sqrt(self, context=None):
2418 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002419 if self._is_special:
2420 ans = self._check_nans(context=context)
2421 if ans:
2422 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002423
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002424 if self._isinfinity() and self._sign == 0:
2425 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002426
2427 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002428 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002429 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002430 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002431
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002432 if context is None:
2433 context = getcontext()
2434
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002435 if self._sign == 1:
2436 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2437
Facundo Batista353750c2007-09-13 18:13:15 +00002438 # At this point self represents a positive number. Let p be
2439 # the desired precision and express self in the form c*100**e
2440 # with c a positive real number and e an integer, c and e
2441 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2442 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2443 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2444 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2445 # the closest integer to sqrt(c) with the even integer chosen
2446 # in the case of a tie.
2447 #
2448 # To ensure correct rounding in all cases, we use the
2449 # following trick: we compute the square root to an extra
2450 # place (precision p+1 instead of precision p), rounding down.
2451 # Then, if the result is inexact and its last digit is 0 or 5,
2452 # we increase the last digit to 1 or 6 respectively; if it's
2453 # exact we leave the last digit alone. Now the final round to
2454 # p places (or fewer in the case of underflow) will round
2455 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002456
Facundo Batista353750c2007-09-13 18:13:15 +00002457 # use an extra digit of precision
2458 prec = context.prec+1
2459
2460 # write argument in the form c*100**e where e = self._exp//2
2461 # is the 'ideal' exponent, to be used if the square root is
2462 # exactly representable. l is the number of 'digits' of c in
2463 # base 100, so that 100**(l-1) <= c < 100**l.
2464 op = _WorkRep(self)
2465 e = op.exp >> 1
2466 if op.exp & 1:
2467 c = op.int * 10
2468 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002469 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002470 c = op.int
2471 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002472
Facundo Batista353750c2007-09-13 18:13:15 +00002473 # rescale so that c has exactly prec base 100 'digits'
2474 shift = prec-l
2475 if shift >= 0:
2476 c *= 100**shift
2477 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002478 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002479 c, remainder = divmod(c, 100**-shift)
2480 exact = not remainder
2481 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002482
Facundo Batista353750c2007-09-13 18:13:15 +00002483 # find n = floor(sqrt(c)) using Newton's method
2484 n = 10**prec
2485 while True:
2486 q = c//n
2487 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002488 break
Facundo Batista353750c2007-09-13 18:13:15 +00002489 else:
2490 n = n + q >> 1
2491 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002492
Facundo Batista353750c2007-09-13 18:13:15 +00002493 if exact:
2494 # result is exact; rescale to use ideal exponent e
2495 if shift >= 0:
2496 # assert n % 10**shift == 0
2497 n //= 10**shift
2498 else:
2499 n *= 10**-shift
2500 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002501 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002502 # result is not exact; fix last digit as described above
2503 if n % 5 == 0:
2504 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002505
Facundo Batista72bc54f2007-11-23 17:59:00 +00002506 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002507
Facundo Batista353750c2007-09-13 18:13:15 +00002508 # round, and fit to current context
2509 context = context._shallow_copy()
2510 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002511 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002512 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002513
Facundo Batista353750c2007-09-13 18:13:15 +00002514 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002515
2516 def max(self, other, context=None):
2517 """Returns the larger value.
2518
Facundo Batista353750c2007-09-13 18:13:15 +00002519 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002520 NaN (and signals if one is sNaN). Also rounds.
2521 """
Facundo Batista353750c2007-09-13 18:13:15 +00002522 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002523
Facundo Batista6c398da2007-09-17 17:30:13 +00002524 if context is None:
2525 context = getcontext()
2526
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002527 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002528 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002529 # number is always returned
2530 sn = self._isnan()
2531 on = other._isnan()
2532 if sn or on:
2533 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002534 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002535 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002536 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002537 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002538
Mark Dickinson2fc92632008-02-06 22:10:50 +00002539 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002540 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002541 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002542 # then an ordering is applied:
2543 #
Facundo Batista59c58842007-04-10 12:58:45 +00002544 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002545 # positive sign and min returns the operand with the negative sign
2546 #
Facundo Batista59c58842007-04-10 12:58:45 +00002547 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002548 # the result. This is exactly the ordering used in compare_total.
2549 c = self.compare_total(other)
2550
2551 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002552 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002553 else:
2554 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002555
Facundo Batistae64acfa2007-12-17 14:18:42 +00002556 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002557
2558 def min(self, other, context=None):
2559 """Returns the smaller value.
2560
Facundo Batista59c58842007-04-10 12:58:45 +00002561 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002562 NaN (and signals if one is sNaN). Also rounds.
2563 """
Facundo Batista353750c2007-09-13 18:13:15 +00002564 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002565
Facundo Batista6c398da2007-09-17 17:30:13 +00002566 if context is None:
2567 context = getcontext()
2568
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002569 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002570 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002571 # number is always returned
2572 sn = self._isnan()
2573 on = other._isnan()
2574 if sn or on:
2575 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002576 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002577 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002578 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002579 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002580
Mark Dickinson2fc92632008-02-06 22:10:50 +00002581 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002582 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002583 c = self.compare_total(other)
2584
2585 if c == -1:
2586 ans = self
2587 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002588 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002589
Facundo Batistae64acfa2007-12-17 14:18:42 +00002590 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002591
2592 def _isinteger(self):
2593 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002594 if self._is_special:
2595 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002596 if self._exp >= 0:
2597 return True
2598 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002599 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002600
2601 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002602 """Returns True if self is even. Assumes self is an integer."""
2603 if not self or self._exp > 0:
2604 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002605 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002606
2607 def adjusted(self):
2608 """Return the adjusted exponent of self"""
2609 try:
2610 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002611 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002612 except TypeError:
2613 return 0
2614
Facundo Batista353750c2007-09-13 18:13:15 +00002615 def canonical(self, context=None):
2616 """Returns the same Decimal object.
2617
2618 As we do not have different encodings for the same number, the
2619 received object already is in its canonical form.
2620 """
2621 return self
2622
2623 def compare_signal(self, other, context=None):
2624 """Compares self to the other operand numerically.
2625
2626 It's pretty much like compare(), but all NaNs signal, with signaling
2627 NaNs taking precedence over quiet NaNs.
2628 """
Mark Dickinson2fc92632008-02-06 22:10:50 +00002629 other = _convert_other(other, raiseit = True)
2630 ans = self._compare_check_nans(other, context)
2631 if ans:
2632 return ans
Facundo Batista353750c2007-09-13 18:13:15 +00002633 return self.compare(other, context=context)
2634
2635 def compare_total(self, other):
2636 """Compares self to other using the abstract representations.
2637
2638 This is not like the standard compare, which use their numerical
2639 value. Note that a total ordering is defined for all possible abstract
2640 representations.
2641 """
2642 # if one is negative and the other is positive, it's easy
2643 if self._sign and not other._sign:
2644 return Dec_n1
2645 if not self._sign and other._sign:
2646 return Dec_p1
2647 sign = self._sign
2648
2649 # let's handle both NaN types
2650 self_nan = self._isnan()
2651 other_nan = other._isnan()
2652 if self_nan or other_nan:
2653 if self_nan == other_nan:
2654 if self._int < other._int:
2655 if sign:
2656 return Dec_p1
2657 else:
2658 return Dec_n1
2659 if self._int > other._int:
2660 if sign:
2661 return Dec_n1
2662 else:
2663 return Dec_p1
2664 return Dec_0
2665
2666 if sign:
2667 if self_nan == 1:
2668 return Dec_n1
2669 if other_nan == 1:
2670 return Dec_p1
2671 if self_nan == 2:
2672 return Dec_n1
2673 if other_nan == 2:
2674 return Dec_p1
2675 else:
2676 if self_nan == 1:
2677 return Dec_p1
2678 if other_nan == 1:
2679 return Dec_n1
2680 if self_nan == 2:
2681 return Dec_p1
2682 if other_nan == 2:
2683 return Dec_n1
2684
2685 if self < other:
2686 return Dec_n1
2687 if self > other:
2688 return Dec_p1
2689
2690 if self._exp < other._exp:
2691 if sign:
2692 return Dec_p1
2693 else:
2694 return Dec_n1
2695 if self._exp > other._exp:
2696 if sign:
2697 return Dec_n1
2698 else:
2699 return Dec_p1
2700 return Dec_0
2701
2702
2703 def compare_total_mag(self, other):
2704 """Compares self to other using abstract repr., ignoring sign.
2705
2706 Like compare_total, but with operand's sign ignored and assumed to be 0.
2707 """
2708 s = self.copy_abs()
2709 o = other.copy_abs()
2710 return s.compare_total(o)
2711
2712 def copy_abs(self):
2713 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002714 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002715
2716 def copy_negate(self):
2717 """Returns a copy with the sign inverted."""
2718 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002719 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002720 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002721 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002722
2723 def copy_sign(self, other):
2724 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002725 return _dec_from_triple(other._sign, self._int,
2726 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002727
2728 def exp(self, context=None):
2729 """Returns e ** self."""
2730
2731 if context is None:
2732 context = getcontext()
2733
2734 # exp(NaN) = NaN
2735 ans = self._check_nans(context=context)
2736 if ans:
2737 return ans
2738
2739 # exp(-Infinity) = 0
2740 if self._isinfinity() == -1:
2741 return Dec_0
2742
2743 # exp(0) = 1
2744 if not self:
2745 return Dec_p1
2746
2747 # exp(Infinity) = Infinity
2748 if self._isinfinity() == 1:
2749 return Decimal(self)
2750
2751 # the result is now guaranteed to be inexact (the true
2752 # mathematical result is transcendental). There's no need to
2753 # raise Rounded and Inexact here---they'll always be raised as
2754 # a result of the call to _fix.
2755 p = context.prec
2756 adj = self.adjusted()
2757
2758 # we only need to do any computation for quite a small range
2759 # of adjusted exponents---for example, -29 <= adj <= 10 for
2760 # the default context. For smaller exponent the result is
2761 # indistinguishable from 1 at the given precision, while for
2762 # larger exponent the result either overflows or underflows.
2763 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2764 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002765 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002766 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2767 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002768 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002769 elif self._sign == 0 and adj < -p:
2770 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002771 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002772 elif self._sign == 1 and adj < -p-1:
2773 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002774 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002775 # general case
2776 else:
2777 op = _WorkRep(self)
2778 c, e = op.int, op.exp
2779 if op.sign == 1:
2780 c = -c
2781
2782 # compute correctly rounded result: increase precision by
2783 # 3 digits at a time until we get an unambiguously
2784 # roundable result
2785 extra = 3
2786 while True:
2787 coeff, exp = _dexp(c, e, p+extra)
2788 if coeff % (5*10**(len(str(coeff))-p-1)):
2789 break
2790 extra += 3
2791
Facundo Batista72bc54f2007-11-23 17:59:00 +00002792 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002793
2794 # at this stage, ans should round correctly with *any*
2795 # rounding mode, not just with ROUND_HALF_EVEN
2796 context = context._shallow_copy()
2797 rounding = context._set_rounding(ROUND_HALF_EVEN)
2798 ans = ans._fix(context)
2799 context.rounding = rounding
2800
2801 return ans
2802
2803 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002804 """Return True if self is canonical; otherwise return False.
2805
2806 Currently, the encoding of a Decimal instance is always
2807 canonical, so this method returns True for any Decimal.
2808 """
2809 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002810
2811 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002812 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002813
Facundo Batista1a191df2007-10-02 17:01:24 +00002814 A Decimal instance is considered finite if it is neither
2815 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002816 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002817 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002818
2819 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002820 """Return True if self is infinite; otherwise return False."""
2821 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002822
2823 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002824 """Return True if self is a qNaN or sNaN; otherwise return False."""
2825 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002826
2827 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002828 """Return True if self is a normal number; otherwise return False."""
2829 if self._is_special or not self:
2830 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002831 if context is None:
2832 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002833 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002834
2835 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002836 """Return True if self is a quiet NaN; otherwise return False."""
2837 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002838
2839 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002840 """Return True if self is negative; otherwise return False."""
2841 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002842
2843 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002844 """Return True if self is a signaling NaN; otherwise return False."""
2845 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002846
2847 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002848 """Return True if self is subnormal; otherwise return False."""
2849 if self._is_special or not self:
2850 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002851 if context is None:
2852 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002853 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002854
2855 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002856 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002857 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002858
2859 def _ln_exp_bound(self):
2860 """Compute a lower bound for the adjusted exponent of self.ln().
2861 In other words, compute r such that self.ln() >= 10**r. Assumes
2862 that self is finite and positive and that self != 1.
2863 """
2864
2865 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2866 adj = self._exp + len(self._int) - 1
2867 if adj >= 1:
2868 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2869 return len(str(adj*23//10)) - 1
2870 if adj <= -2:
2871 # argument <= 0.1
2872 return len(str((-1-adj)*23//10)) - 1
2873 op = _WorkRep(self)
2874 c, e = op.int, op.exp
2875 if adj == 0:
2876 # 1 < self < 10
2877 num = str(c-10**-e)
2878 den = str(c)
2879 return len(num) - len(den) - (num < den)
2880 # adj == -1, 0.1 <= self < 1
2881 return e + len(str(10**-e - c)) - 1
2882
2883
2884 def ln(self, context=None):
2885 """Returns the natural (base e) logarithm of self."""
2886
2887 if context is None:
2888 context = getcontext()
2889
2890 # ln(NaN) = NaN
2891 ans = self._check_nans(context=context)
2892 if ans:
2893 return ans
2894
2895 # ln(0.0) == -Infinity
2896 if not self:
2897 return negInf
2898
2899 # ln(Infinity) = Infinity
2900 if self._isinfinity() == 1:
2901 return Inf
2902
2903 # ln(1.0) == 0.0
2904 if self == Dec_p1:
2905 return Dec_0
2906
2907 # ln(negative) raises InvalidOperation
2908 if self._sign == 1:
2909 return context._raise_error(InvalidOperation,
2910 'ln of a negative value')
2911
2912 # result is irrational, so necessarily inexact
2913 op = _WorkRep(self)
2914 c, e = op.int, op.exp
2915 p = context.prec
2916
2917 # correctly rounded result: repeatedly increase precision by 3
2918 # until we get an unambiguously roundable result
2919 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2920 while True:
2921 coeff = _dlog(c, e, places)
2922 # assert len(str(abs(coeff)))-p >= 1
2923 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2924 break
2925 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002926 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002927
2928 context = context._shallow_copy()
2929 rounding = context._set_rounding(ROUND_HALF_EVEN)
2930 ans = ans._fix(context)
2931 context.rounding = rounding
2932 return ans
2933
2934 def _log10_exp_bound(self):
2935 """Compute a lower bound for the adjusted exponent of self.log10().
2936 In other words, find r such that self.log10() >= 10**r.
2937 Assumes that self is finite and positive and that self != 1.
2938 """
2939
2940 # For x >= 10 or x < 0.1 we only need a bound on the integer
2941 # part of log10(self), and this comes directly from the
2942 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2943 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2944 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2945
2946 adj = self._exp + len(self._int) - 1
2947 if adj >= 1:
2948 # self >= 10
2949 return len(str(adj))-1
2950 if adj <= -2:
2951 # self < 0.1
2952 return len(str(-1-adj))-1
2953 op = _WorkRep(self)
2954 c, e = op.int, op.exp
2955 if adj == 0:
2956 # 1 < self < 10
2957 num = str(c-10**-e)
2958 den = str(231*c)
2959 return len(num) - len(den) - (num < den) + 2
2960 # adj == -1, 0.1 <= self < 1
2961 num = str(10**-e-c)
2962 return len(num) + e - (num < "231") - 1
2963
2964 def log10(self, context=None):
2965 """Returns the base 10 logarithm of self."""
2966
2967 if context is None:
2968 context = getcontext()
2969
2970 # log10(NaN) = NaN
2971 ans = self._check_nans(context=context)
2972 if ans:
2973 return ans
2974
2975 # log10(0.0) == -Infinity
2976 if not self:
2977 return negInf
2978
2979 # log10(Infinity) = Infinity
2980 if self._isinfinity() == 1:
2981 return Inf
2982
2983 # log10(negative or -Infinity) raises InvalidOperation
2984 if self._sign == 1:
2985 return context._raise_error(InvalidOperation,
2986 'log10 of a negative value')
2987
2988 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00002989 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00002990 # answer may need rounding
2991 ans = Decimal(self._exp + len(self._int) - 1)
2992 else:
2993 # result is irrational, so necessarily inexact
2994 op = _WorkRep(self)
2995 c, e = op.int, op.exp
2996 p = context.prec
2997
2998 # correctly rounded result: repeatedly increase precision
2999 # until result is unambiguously roundable
3000 places = p-self._log10_exp_bound()+2
3001 while True:
3002 coeff = _dlog10(c, e, places)
3003 # assert len(str(abs(coeff)))-p >= 1
3004 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3005 break
3006 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003007 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003008
3009 context = context._shallow_copy()
3010 rounding = context._set_rounding(ROUND_HALF_EVEN)
3011 ans = ans._fix(context)
3012 context.rounding = rounding
3013 return ans
3014
3015 def logb(self, context=None):
3016 """ Returns the exponent of the magnitude of self's MSD.
3017
3018 The result is the integer which is the exponent of the magnitude
3019 of the most significant digit of self (as though it were truncated
3020 to a single digit while maintaining the value of that digit and
3021 without limiting the resulting exponent).
3022 """
3023 # logb(NaN) = NaN
3024 ans = self._check_nans(context=context)
3025 if ans:
3026 return ans
3027
3028 if context is None:
3029 context = getcontext()
3030
3031 # logb(+/-Inf) = +Inf
3032 if self._isinfinity():
3033 return Inf
3034
3035 # logb(0) = -Inf, DivisionByZero
3036 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00003037 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00003038
3039 # otherwise, simply return the adjusted exponent of self, as a
3040 # Decimal. Note that no attempt is made to fit the result
3041 # into the current context.
3042 return Decimal(self.adjusted())
3043
3044 def _islogical(self):
3045 """Return True if self is a logical operand.
3046
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00003047 For being logical, it must be a finite number with a sign of 0,
Facundo Batista353750c2007-09-13 18:13:15 +00003048 an exponent of 0, and a coefficient whose digits must all be
3049 either 0 or 1.
3050 """
3051 if self._sign != 0 or self._exp != 0:
3052 return False
3053 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003054 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00003055 return False
3056 return True
3057
3058 def _fill_logical(self, context, opa, opb):
3059 dif = context.prec - len(opa)
3060 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003061 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00003062 elif dif < 0:
3063 opa = opa[-context.prec:]
3064 dif = context.prec - len(opb)
3065 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003066 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00003067 elif dif < 0:
3068 opb = opb[-context.prec:]
3069 return opa, opb
3070
3071 def logical_and(self, other, context=None):
3072 """Applies an 'and' operation between self and other's digits."""
3073 if context is None:
3074 context = getcontext()
3075 if not self._islogical() or not other._islogical():
3076 return context._raise_error(InvalidOperation)
3077
3078 # fill to context.prec
3079 (opa, opb) = self._fill_logical(context, self._int, other._int)
3080
3081 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003082 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3083 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003084
3085 def logical_invert(self, context=None):
3086 """Invert all its digits."""
3087 if context is None:
3088 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003089 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3090 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003091
3092 def logical_or(self, other, context=None):
3093 """Applies an 'or' operation between self and other's digits."""
3094 if context is None:
3095 context = getcontext()
3096 if not self._islogical() or not other._islogical():
3097 return context._raise_error(InvalidOperation)
3098
3099 # fill to context.prec
3100 (opa, opb) = self._fill_logical(context, self._int, other._int)
3101
3102 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003103 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3104 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003105
3106 def logical_xor(self, other, context=None):
3107 """Applies an 'xor' 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 max_mag(self, other, context=None):
3121 """Compares the values numerically with their sign ignored."""
3122 other = _convert_other(other, raiseit=True)
3123
Facundo Batista6c398da2007-09-17 17:30:13 +00003124 if context is None:
3125 context = getcontext()
3126
Facundo Batista353750c2007-09-13 18:13:15 +00003127 if self._is_special or other._is_special:
3128 # If one operand is a quiet NaN and the other is number, then the
3129 # number is always returned
3130 sn = self._isnan()
3131 on = other._isnan()
3132 if sn or on:
3133 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003134 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003135 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003136 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003137 return self._check_nans(other, context)
3138
Mark Dickinson2fc92632008-02-06 22:10:50 +00003139 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003140 if c == 0:
3141 c = self.compare_total(other)
3142
3143 if c == -1:
3144 ans = other
3145 else:
3146 ans = self
3147
Facundo Batistae64acfa2007-12-17 14:18:42 +00003148 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003149
3150 def min_mag(self, other, context=None):
3151 """Compares the values numerically with their sign ignored."""
3152 other = _convert_other(other, raiseit=True)
3153
Facundo Batista6c398da2007-09-17 17:30:13 +00003154 if context is None:
3155 context = getcontext()
3156
Facundo Batista353750c2007-09-13 18:13:15 +00003157 if self._is_special or other._is_special:
3158 # If one operand is a quiet NaN and the other is number, then the
3159 # number is always returned
3160 sn = self._isnan()
3161 on = other._isnan()
3162 if sn or on:
3163 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003164 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003165 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003166 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003167 return self._check_nans(other, context)
3168
Mark Dickinson2fc92632008-02-06 22:10:50 +00003169 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003170 if c == 0:
3171 c = self.compare_total(other)
3172
3173 if c == -1:
3174 ans = self
3175 else:
3176 ans = other
3177
Facundo Batistae64acfa2007-12-17 14:18:42 +00003178 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003179
3180 def next_minus(self, context=None):
3181 """Returns the largest representable number smaller than itself."""
3182 if context is None:
3183 context = getcontext()
3184
3185 ans = self._check_nans(context=context)
3186 if ans:
3187 return ans
3188
3189 if self._isinfinity() == -1:
3190 return negInf
3191 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003192 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003193
3194 context = context.copy()
3195 context._set_rounding(ROUND_FLOOR)
3196 context._ignore_all_flags()
3197 new_self = self._fix(context)
3198 if new_self != self:
3199 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003200 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3201 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003202
3203 def next_plus(self, context=None):
3204 """Returns the smallest representable number larger than itself."""
3205 if context is None:
3206 context = getcontext()
3207
3208 ans = self._check_nans(context=context)
3209 if ans:
3210 return ans
3211
3212 if self._isinfinity() == 1:
3213 return Inf
3214 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003215 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003216
3217 context = context.copy()
3218 context._set_rounding(ROUND_CEILING)
3219 context._ignore_all_flags()
3220 new_self = self._fix(context)
3221 if new_self != self:
3222 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003223 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3224 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003225
3226 def next_toward(self, other, context=None):
3227 """Returns the number closest to self, in the direction towards other.
3228
3229 The result is the closest representable number to self
3230 (excluding self) that is in the direction towards other,
3231 unless both have the same value. If the two operands are
3232 numerically equal, then the result is a copy of self with the
3233 sign set to be the same as the sign of other.
3234 """
3235 other = _convert_other(other, raiseit=True)
3236
3237 if context is None:
3238 context = getcontext()
3239
3240 ans = self._check_nans(other, context)
3241 if ans:
3242 return ans
3243
Mark Dickinson2fc92632008-02-06 22:10:50 +00003244 comparison = self._cmp(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003245 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003246 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003247
3248 if comparison == -1:
3249 ans = self.next_plus(context)
3250 else: # comparison == 1
3251 ans = self.next_minus(context)
3252
3253 # decide which flags to raise using value of ans
3254 if ans._isinfinity():
3255 context._raise_error(Overflow,
3256 'Infinite result from next_toward',
3257 ans._sign)
3258 context._raise_error(Rounded)
3259 context._raise_error(Inexact)
3260 elif ans.adjusted() < context.Emin:
3261 context._raise_error(Underflow)
3262 context._raise_error(Subnormal)
3263 context._raise_error(Rounded)
3264 context._raise_error(Inexact)
3265 # if precision == 1 then we don't raise Clamped for a
3266 # result 0E-Etiny.
3267 if not ans:
3268 context._raise_error(Clamped)
3269
3270 return ans
3271
3272 def number_class(self, context=None):
3273 """Returns an indication of the class of self.
3274
3275 The class is one of the following strings:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00003276 sNaN
3277 NaN
Facundo Batista353750c2007-09-13 18:13:15 +00003278 -Infinity
3279 -Normal
3280 -Subnormal
3281 -Zero
3282 +Zero
3283 +Subnormal
3284 +Normal
3285 +Infinity
3286 """
3287 if self.is_snan():
3288 return "sNaN"
3289 if self.is_qnan():
3290 return "NaN"
3291 inf = self._isinfinity()
3292 if inf == 1:
3293 return "+Infinity"
3294 if inf == -1:
3295 return "-Infinity"
3296 if self.is_zero():
3297 if self._sign:
3298 return "-Zero"
3299 else:
3300 return "+Zero"
3301 if context is None:
3302 context = getcontext()
3303 if self.is_subnormal(context=context):
3304 if self._sign:
3305 return "-Subnormal"
3306 else:
3307 return "+Subnormal"
3308 # just a normal, regular, boring number, :)
3309 if self._sign:
3310 return "-Normal"
3311 else:
3312 return "+Normal"
3313
3314 def radix(self):
3315 """Just returns 10, as this is Decimal, :)"""
3316 return Decimal(10)
3317
3318 def rotate(self, other, context=None):
3319 """Returns a rotated copy of self, value-of-other times."""
3320 if context is None:
3321 context = getcontext()
3322
3323 ans = self._check_nans(other, context)
3324 if ans:
3325 return ans
3326
3327 if other._exp != 0:
3328 return context._raise_error(InvalidOperation)
3329 if not (-context.prec <= int(other) <= context.prec):
3330 return context._raise_error(InvalidOperation)
3331
3332 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003333 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003334
3335 # get values, pad if necessary
3336 torot = int(other)
3337 rotdig = self._int
3338 topad = context.prec - len(rotdig)
3339 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003340 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003341
3342 # let's rotate!
3343 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003344 return _dec_from_triple(self._sign,
3345 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003346
3347 def scaleb (self, other, context=None):
3348 """Returns self operand after adding the second value to its exp."""
3349 if context is None:
3350 context = getcontext()
3351
3352 ans = self._check_nans(other, context)
3353 if ans:
3354 return ans
3355
3356 if other._exp != 0:
3357 return context._raise_error(InvalidOperation)
3358 liminf = -2 * (context.Emax + context.prec)
3359 limsup = 2 * (context.Emax + context.prec)
3360 if not (liminf <= int(other) <= limsup):
3361 return context._raise_error(InvalidOperation)
3362
3363 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003364 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003365
Facundo Batista72bc54f2007-11-23 17:59:00 +00003366 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003367 d = d._fix(context)
3368 return d
3369
3370 def shift(self, other, context=None):
3371 """Returns a shifted copy of self, value-of-other times."""
3372 if context is None:
3373 context = getcontext()
3374
3375 ans = self._check_nans(other, context)
3376 if ans:
3377 return ans
3378
3379 if other._exp != 0:
3380 return context._raise_error(InvalidOperation)
3381 if not (-context.prec <= int(other) <= context.prec):
3382 return context._raise_error(InvalidOperation)
3383
3384 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003385 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003386
3387 # get values, pad if necessary
3388 torot = int(other)
3389 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003390 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003391 rotdig = self._int
3392 topad = context.prec - len(rotdig)
3393 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003394 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003395
3396 # let's shift!
3397 if torot < 0:
3398 rotated = rotdig[:torot]
3399 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003400 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003401 rotated = rotated[-context.prec:]
3402
Facundo Batista72bc54f2007-11-23 17:59:00 +00003403 return _dec_from_triple(self._sign,
3404 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003405
Facundo Batista59c58842007-04-10 12:58:45 +00003406 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003407 def __reduce__(self):
3408 return (self.__class__, (str(self),))
3409
3410 def __copy__(self):
3411 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003412 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003413 return self.__class__(str(self))
3414
3415 def __deepcopy__(self, memo):
3416 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003417 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003418 return self.__class__(str(self))
3419
Facundo Batista72bc54f2007-11-23 17:59:00 +00003420def _dec_from_triple(sign, coefficient, exponent, special=False):
3421 """Create a decimal instance directly, without any validation,
3422 normalization (e.g. removal of leading zeros) or argument
3423 conversion.
3424
3425 This function is for *internal use only*.
3426 """
3427
3428 self = object.__new__(Decimal)
3429 self._sign = sign
3430 self._int = coefficient
3431 self._exp = exponent
3432 self._is_special = special
3433
3434 return self
3435
Facundo Batista59c58842007-04-10 12:58:45 +00003436##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003437
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003438
3439# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003440rounding_functions = [name for name in Decimal.__dict__.keys()
3441 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003442for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003443 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003444 globalname = name[1:].upper()
3445 val = globals()[globalname]
3446 Decimal._pick_rounding_function[val] = name
3447
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003448del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003449
Nick Coghlanced12182006-09-02 03:54:17 +00003450class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003451 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003452
Nick Coghlanced12182006-09-02 03:54:17 +00003453 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003454 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003455 """
3456 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003457 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003458 def __enter__(self):
3459 self.saved_context = getcontext()
3460 setcontext(self.new_context)
3461 return self.new_context
3462 def __exit__(self, t, v, tb):
3463 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003464
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003465class Context(object):
3466 """Contains the context for a Decimal instance.
3467
3468 Contains:
3469 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003470 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003471 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003472 raised when it is caused. Otherwise, a value is
3473 substituted in.
3474 flags - When an exception is caused, flags[exception] is incremented.
3475 (Whether or not the trap_enabler is set)
3476 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003477 Emin - Minimum exponent
3478 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003479 capitals - If 1, 1*10^1 is printed as 1E+1.
3480 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003481 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003482 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003483
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003484 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003485 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003486 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003487 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003488 _ignored_flags=None):
3489 if flags is None:
3490 flags = []
3491 if _ignored_flags is None:
3492 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003493 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003494 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003495 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003496 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003497 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003498 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003499 for name, val in locals().items():
3500 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003501 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003502 else:
3503 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003504 del self.self
3505
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003506 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003507 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003508 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003509 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3510 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3511 % vars(self))
3512 names = [f.__name__ for f, v in self.flags.items() if v]
3513 s.append('flags=[' + ', '.join(names) + ']')
3514 names = [t.__name__ for t, v in self.traps.items() if v]
3515 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003516 return ', '.join(s) + ')'
3517
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003518 def clear_flags(self):
3519 """Reset all flags to zero"""
3520 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003521 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003522
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003523 def _shallow_copy(self):
3524 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003525 nc = Context(self.prec, self.rounding, self.traps,
3526 self.flags, self.Emin, self.Emax,
3527 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003528 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003529
3530 def copy(self):
3531 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003532 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003533 self.flags.copy(), self.Emin, self.Emax,
3534 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003535 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003536 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003537
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003538 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003539 """Handles an error
3540
3541 If the flag is in _ignored_flags, returns the default response.
3542 Otherwise, it increments the flag, then, if the corresponding
3543 trap_enabler is set, it reaises the exception. Otherwise, it returns
3544 the default value after incrementing the flag.
3545 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003546 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003547 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003548 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003549 return error().handle(self, *args)
3550
3551 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003552 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003553 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003554 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003555
3556 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003557 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003558 raise error, explanation
3559
3560 def _ignore_all_flags(self):
3561 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003562 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003563
3564 def _ignore_flags(self, *flags):
3565 """Ignore the flags, if they are raised"""
3566 # Do not mutate-- This way, copies of a context leave the original
3567 # alone.
3568 self._ignored_flags = (self._ignored_flags + list(flags))
3569 return list(flags)
3570
3571 def _regard_flags(self, *flags):
3572 """Stop ignoring the flags, if they are raised"""
3573 if flags and isinstance(flags[0], (tuple,list)):
3574 flags = flags[0]
3575 for flag in flags:
3576 self._ignored_flags.remove(flag)
3577
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003578 def __hash__(self):
3579 """A Context cannot be hashed."""
3580 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003581 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003582
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003583 def Etiny(self):
3584 """Returns Etiny (= Emin - prec + 1)"""
3585 return int(self.Emin - self.prec + 1)
3586
3587 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003588 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003589 return int(self.Emax - self.prec + 1)
3590
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003591 def _set_rounding(self, type):
3592 """Sets the rounding type.
3593
3594 Sets the rounding type, and returns the current (previous)
3595 rounding type. Often used like:
3596
3597 context = context.copy()
3598 # so you don't change the calling context
3599 # if an error occurs in the middle.
3600 rounding = context._set_rounding(ROUND_UP)
3601 val = self.__sub__(other, context=context)
3602 context._set_rounding(rounding)
3603
3604 This will make it round up for that operation.
3605 """
3606 rounding = self.rounding
3607 self.rounding= type
3608 return rounding
3609
Raymond Hettingerfed52962004-07-14 15:41:57 +00003610 def create_decimal(self, num='0'):
Mark Dickinson59bc20b2008-01-12 01:56:00 +00003611 """Creates a new Decimal instance but using self as context.
3612
3613 This method implements the to-number operation of the
3614 IBM Decimal specification."""
3615
3616 if isinstance(num, basestring) and num != num.strip():
3617 return self._raise_error(ConversionSyntax,
3618 "no trailing or leading whitespace is "
3619 "permitted.")
3620
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003621 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003622 if d._isnan() and len(d._int) > self.prec - self._clamp:
3623 return self._raise_error(ConversionSyntax,
3624 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003625 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003626
Facundo Batista59c58842007-04-10 12:58:45 +00003627 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003628 def abs(self, a):
3629 """Returns the absolute value of the operand.
3630
3631 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003632 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003633 the plus operation on the operand.
3634
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003635 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003636 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003637 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003638 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003639 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003640 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003641 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003642 Decimal("101.5")
3643 """
3644 return a.__abs__(context=self)
3645
3646 def add(self, a, b):
3647 """Return the sum of the two operands.
3648
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003649 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003650 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003651 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003652 Decimal("1.02E+4")
3653 """
3654 return a.__add__(b, context=self)
3655
3656 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003657 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003658
Facundo Batista353750c2007-09-13 18:13:15 +00003659 def canonical(self, a):
3660 """Returns the same Decimal object.
3661
3662 As we do not have different encodings for the same number, the
3663 received object already is in its canonical form.
3664
3665 >>> ExtendedContext.canonical(Decimal('2.50'))
3666 Decimal("2.50")
3667 """
3668 return a.canonical(context=self)
3669
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003670 def compare(self, a, b):
3671 """Compares values numerically.
3672
3673 If the signs of the operands differ, a value representing each operand
3674 ('-1' if the operand is less than zero, '0' if the operand is zero or
3675 negative zero, or '1' if the operand is greater than zero) is used in
3676 place of that operand for the comparison instead of the actual
3677 operand.
3678
3679 The comparison is then effected by subtracting the second operand from
3680 the first and then returning a value according to the result of the
3681 subtraction: '-1' if the result is less than zero, '0' if the result is
3682 zero or negative zero, or '1' if the result is greater than zero.
3683
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003684 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003685 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003686 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003687 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003688 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003689 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003690 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003691 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003692 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003693 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003694 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003695 Decimal("-1")
3696 """
3697 return a.compare(b, context=self)
3698
Facundo Batista353750c2007-09-13 18:13:15 +00003699 def compare_signal(self, a, b):
3700 """Compares the values of the two operands numerically.
3701
3702 It's pretty much like compare(), but all NaNs signal, with signaling
3703 NaNs taking precedence over quiet NaNs.
3704
3705 >>> c = ExtendedContext
3706 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3707 Decimal("-1")
3708 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3709 Decimal("0")
3710 >>> c.flags[InvalidOperation] = 0
3711 >>> print c.flags[InvalidOperation]
3712 0
3713 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3714 Decimal("NaN")
3715 >>> print c.flags[InvalidOperation]
3716 1
3717 >>> c.flags[InvalidOperation] = 0
3718 >>> print c.flags[InvalidOperation]
3719 0
3720 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3721 Decimal("NaN")
3722 >>> print c.flags[InvalidOperation]
3723 1
3724 """
3725 return a.compare_signal(b, context=self)
3726
3727 def compare_total(self, a, b):
3728 """Compares two operands using their abstract representation.
3729
3730 This is not like the standard compare, which use their numerical
3731 value. Note that a total ordering is defined for all possible abstract
3732 representations.
3733
3734 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3735 Decimal("-1")
3736 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3737 Decimal("-1")
3738 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3739 Decimal("-1")
3740 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3741 Decimal("0")
3742 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3743 Decimal("1")
3744 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3745 Decimal("-1")
3746 """
3747 return a.compare_total(b)
3748
3749 def compare_total_mag(self, a, b):
3750 """Compares two operands using their abstract representation ignoring sign.
3751
3752 Like compare_total, but with operand's sign ignored and assumed to be 0.
3753 """
3754 return a.compare_total_mag(b)
3755
3756 def copy_abs(self, a):
3757 """Returns a copy of the operand with the sign set to 0.
3758
3759 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3760 Decimal("2.1")
3761 >>> ExtendedContext.copy_abs(Decimal('-100'))
3762 Decimal("100")
3763 """
3764 return a.copy_abs()
3765
3766 def copy_decimal(self, a):
3767 """Returns a copy of the decimal objet.
3768
3769 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3770 Decimal("2.1")
3771 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3772 Decimal("-1.00")
3773 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003774 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003775
3776 def copy_negate(self, a):
3777 """Returns a copy of the operand with the sign inverted.
3778
3779 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3780 Decimal("-101.5")
3781 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3782 Decimal("101.5")
3783 """
3784 return a.copy_negate()
3785
3786 def copy_sign(self, a, b):
3787 """Copies the second operand's sign to the first one.
3788
3789 In detail, it returns a copy of the first operand with the sign
3790 equal to the sign of the second operand.
3791
3792 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3793 Decimal("1.50")
3794 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3795 Decimal("1.50")
3796 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3797 Decimal("-1.50")
3798 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3799 Decimal("-1.50")
3800 """
3801 return a.copy_sign(b)
3802
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003803 def divide(self, a, b):
3804 """Decimal division in a specified context.
3805
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003806 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003807 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003808 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003809 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003810 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003811 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003812 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003813 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003814 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003815 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003816 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003817 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003818 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003819 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003820 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003821 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003822 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003823 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003824 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003825 Decimal("1.20E+6")
3826 """
3827 return a.__div__(b, context=self)
3828
3829 def divide_int(self, a, b):
3830 """Divides two numbers and returns the integer part of the result.
3831
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003832 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003833 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003834 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003835 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003836 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003837 Decimal("3")
3838 """
3839 return a.__floordiv__(b, context=self)
3840
3841 def divmod(self, a, b):
3842 return a.__divmod__(b, context=self)
3843
Facundo Batista353750c2007-09-13 18:13:15 +00003844 def exp(self, a):
3845 """Returns e ** a.
3846
3847 >>> c = ExtendedContext.copy()
3848 >>> c.Emin = -999
3849 >>> c.Emax = 999
3850 >>> c.exp(Decimal('-Infinity'))
3851 Decimal("0")
3852 >>> c.exp(Decimal('-1'))
3853 Decimal("0.367879441")
3854 >>> c.exp(Decimal('0'))
3855 Decimal("1")
3856 >>> c.exp(Decimal('1'))
3857 Decimal("2.71828183")
3858 >>> c.exp(Decimal('0.693147181'))
3859 Decimal("2.00000000")
3860 >>> c.exp(Decimal('+Infinity'))
3861 Decimal("Infinity")
3862 """
3863 return a.exp(context=self)
3864
3865 def fma(self, a, b, c):
3866 """Returns a multiplied by b, plus c.
3867
3868 The first two operands are multiplied together, using multiply,
3869 the third operand is then added to the result of that
3870 multiplication, using add, all with only one final rounding.
3871
3872 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3873 Decimal("22")
3874 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3875 Decimal("-8")
3876 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3877 Decimal("1.38435736E+12")
3878 """
3879 return a.fma(b, c, context=self)
3880
3881 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003882 """Return True if the operand is canonical; otherwise return False.
3883
3884 Currently, the encoding of a Decimal instance is always
3885 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00003886
3887 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003888 True
Facundo Batista353750c2007-09-13 18:13:15 +00003889 """
Facundo Batista1a191df2007-10-02 17:01:24 +00003890 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00003891
3892 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003893 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003894
Facundo Batista1a191df2007-10-02 17:01:24 +00003895 A Decimal instance is considered finite if it is neither
3896 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00003897
3898 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003899 True
Facundo Batista353750c2007-09-13 18:13:15 +00003900 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003901 True
Facundo Batista353750c2007-09-13 18:13:15 +00003902 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003903 True
Facundo Batista353750c2007-09-13 18:13:15 +00003904 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003905 False
Facundo Batista353750c2007-09-13 18:13:15 +00003906 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003907 False
Facundo Batista353750c2007-09-13 18:13:15 +00003908 """
3909 return a.is_finite()
3910
3911 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003912 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003913
3914 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003915 False
Facundo Batista353750c2007-09-13 18:13:15 +00003916 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003917 True
Facundo Batista353750c2007-09-13 18:13:15 +00003918 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003919 False
Facundo Batista353750c2007-09-13 18:13:15 +00003920 """
3921 return a.is_infinite()
3922
3923 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003924 """Return True if the operand is a qNaN or sNaN;
3925 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003926
3927 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003928 False
Facundo Batista353750c2007-09-13 18:13:15 +00003929 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003930 True
Facundo Batista353750c2007-09-13 18:13:15 +00003931 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003932 True
Facundo Batista353750c2007-09-13 18:13:15 +00003933 """
3934 return a.is_nan()
3935
3936 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003937 """Return True if the operand is a normal number;
3938 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003939
3940 >>> c = ExtendedContext.copy()
3941 >>> c.Emin = -999
3942 >>> c.Emax = 999
3943 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003944 True
Facundo Batista353750c2007-09-13 18:13:15 +00003945 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003946 False
Facundo Batista353750c2007-09-13 18:13:15 +00003947 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003948 False
Facundo Batista353750c2007-09-13 18:13:15 +00003949 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003950 False
Facundo Batista353750c2007-09-13 18:13:15 +00003951 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003952 False
Facundo Batista353750c2007-09-13 18:13:15 +00003953 """
3954 return a.is_normal(context=self)
3955
3956 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003957 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003958
3959 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003960 False
Facundo Batista353750c2007-09-13 18:13:15 +00003961 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003962 True
Facundo Batista353750c2007-09-13 18:13:15 +00003963 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003964 False
Facundo Batista353750c2007-09-13 18:13:15 +00003965 """
3966 return a.is_qnan()
3967
3968 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003969 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003970
3971 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003972 False
Facundo Batista353750c2007-09-13 18:13:15 +00003973 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003974 True
Facundo Batista353750c2007-09-13 18:13:15 +00003975 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003976 True
Facundo Batista353750c2007-09-13 18:13:15 +00003977 """
3978 return a.is_signed()
3979
3980 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003981 """Return True if the operand is a signaling NaN;
3982 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003983
3984 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003985 False
Facundo Batista353750c2007-09-13 18:13:15 +00003986 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003987 False
Facundo Batista353750c2007-09-13 18:13:15 +00003988 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003989 True
Facundo Batista353750c2007-09-13 18:13:15 +00003990 """
3991 return a.is_snan()
3992
3993 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003994 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003995
3996 >>> c = ExtendedContext.copy()
3997 >>> c.Emin = -999
3998 >>> c.Emax = 999
3999 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004000 False
Facundo Batista353750c2007-09-13 18:13:15 +00004001 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004002 True
Facundo Batista353750c2007-09-13 18:13:15 +00004003 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004004 False
Facundo Batista353750c2007-09-13 18:13:15 +00004005 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004006 False
Facundo Batista353750c2007-09-13 18:13:15 +00004007 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004008 False
Facundo Batista353750c2007-09-13 18:13:15 +00004009 """
4010 return a.is_subnormal(context=self)
4011
4012 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004013 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004014
4015 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004016 True
Facundo Batista353750c2007-09-13 18:13:15 +00004017 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004018 False
Facundo Batista353750c2007-09-13 18:13:15 +00004019 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004020 True
Facundo Batista353750c2007-09-13 18:13:15 +00004021 """
4022 return a.is_zero()
4023
4024 def ln(self, a):
4025 """Returns the natural (base e) logarithm of the operand.
4026
4027 >>> c = ExtendedContext.copy()
4028 >>> c.Emin = -999
4029 >>> c.Emax = 999
4030 >>> c.ln(Decimal('0'))
4031 Decimal("-Infinity")
4032 >>> c.ln(Decimal('1.000'))
4033 Decimal("0")
4034 >>> c.ln(Decimal('2.71828183'))
4035 Decimal("1.00000000")
4036 >>> c.ln(Decimal('10'))
4037 Decimal("2.30258509")
4038 >>> c.ln(Decimal('+Infinity'))
4039 Decimal("Infinity")
4040 """
4041 return a.ln(context=self)
4042
4043 def log10(self, a):
4044 """Returns the base 10 logarithm of the operand.
4045
4046 >>> c = ExtendedContext.copy()
4047 >>> c.Emin = -999
4048 >>> c.Emax = 999
4049 >>> c.log10(Decimal('0'))
4050 Decimal("-Infinity")
4051 >>> c.log10(Decimal('0.001'))
4052 Decimal("-3")
4053 >>> c.log10(Decimal('1.000'))
4054 Decimal("0")
4055 >>> c.log10(Decimal('2'))
4056 Decimal("0.301029996")
4057 >>> c.log10(Decimal('10'))
4058 Decimal("1")
4059 >>> c.log10(Decimal('70'))
4060 Decimal("1.84509804")
4061 >>> c.log10(Decimal('+Infinity'))
4062 Decimal("Infinity")
4063 """
4064 return a.log10(context=self)
4065
4066 def logb(self, a):
4067 """ Returns the exponent of the magnitude of the operand's MSD.
4068
4069 The result is the integer which is the exponent of the magnitude
4070 of the most significant digit of the operand (as though the
4071 operand were truncated to a single digit while maintaining the
4072 value of that digit and without limiting the resulting exponent).
4073
4074 >>> ExtendedContext.logb(Decimal('250'))
4075 Decimal("2")
4076 >>> ExtendedContext.logb(Decimal('2.50'))
4077 Decimal("0")
4078 >>> ExtendedContext.logb(Decimal('0.03'))
4079 Decimal("-2")
4080 >>> ExtendedContext.logb(Decimal('0'))
4081 Decimal("-Infinity")
4082 """
4083 return a.logb(context=self)
4084
4085 def logical_and(self, a, b):
4086 """Applies the logical operation 'and' between each operand's digits.
4087
4088 The operands must be both logical numbers.
4089
4090 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4091 Decimal("0")
4092 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4093 Decimal("0")
4094 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4095 Decimal("0")
4096 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4097 Decimal("1")
4098 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4099 Decimal("1000")
4100 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4101 Decimal("10")
4102 """
4103 return a.logical_and(b, context=self)
4104
4105 def logical_invert(self, a):
4106 """Invert all the digits in the operand.
4107
4108 The operand must be a logical number.
4109
4110 >>> ExtendedContext.logical_invert(Decimal('0'))
4111 Decimal("111111111")
4112 >>> ExtendedContext.logical_invert(Decimal('1'))
4113 Decimal("111111110")
4114 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4115 Decimal("0")
4116 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4117 Decimal("10101010")
4118 """
4119 return a.logical_invert(context=self)
4120
4121 def logical_or(self, a, b):
4122 """Applies the logical operation 'or' between each operand's digits.
4123
4124 The operands must be both logical numbers.
4125
4126 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4127 Decimal("0")
4128 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4129 Decimal("1")
4130 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4131 Decimal("1")
4132 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4133 Decimal("1")
4134 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4135 Decimal("1110")
4136 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4137 Decimal("1110")
4138 """
4139 return a.logical_or(b, context=self)
4140
4141 def logical_xor(self, a, b):
4142 """Applies the logical operation 'xor' between each operand's digits.
4143
4144 The operands must be both logical numbers.
4145
4146 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4147 Decimal("0")
4148 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4149 Decimal("1")
4150 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4151 Decimal("1")
4152 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4153 Decimal("0")
4154 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4155 Decimal("110")
4156 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4157 Decimal("1101")
4158 """
4159 return a.logical_xor(b, context=self)
4160
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004161 def max(self, a,b):
4162 """max compares two values numerically and returns the maximum.
4163
4164 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004165 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004166 operation. If they are numerically equal then the left-hand operand
4167 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004168 infinity) of the two operands is chosen as the result.
4169
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004170 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004171 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004172 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004173 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004174 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004175 Decimal("1")
4176 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4177 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004178 """
4179 return a.max(b, context=self)
4180
Facundo Batista353750c2007-09-13 18:13:15 +00004181 def max_mag(self, a, b):
4182 """Compares the values numerically with their sign ignored."""
4183 return a.max_mag(b, context=self)
4184
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004185 def min(self, a,b):
4186 """min compares two values numerically and returns the minimum.
4187
4188 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004189 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004190 operation. If they are numerically equal then the left-hand operand
4191 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004192 infinity) of the two operands is chosen as the result.
4193
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004194 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004195 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004196 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004197 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004198 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004199 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004200 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4201 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004202 """
4203 return a.min(b, context=self)
4204
Facundo Batista353750c2007-09-13 18:13:15 +00004205 def min_mag(self, a, b):
4206 """Compares the values numerically with their sign ignored."""
4207 return a.min_mag(b, context=self)
4208
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004209 def minus(self, a):
4210 """Minus corresponds to unary prefix minus in Python.
4211
4212 The operation is evaluated using the same rules as subtract; the
4213 operation minus(a) is calculated as subtract('0', a) where the '0'
4214 has the same exponent as the operand.
4215
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004216 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004217 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004218 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004219 Decimal("1.3")
4220 """
4221 return a.__neg__(context=self)
4222
4223 def multiply(self, a, b):
4224 """multiply multiplies two operands.
4225
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004226 If either operand is a special value then the general rules apply.
4227 Otherwise, the operands are multiplied together ('long multiplication'),
4228 resulting in a number which may be as long as the sum of the lengths
4229 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004230
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004231 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004232 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004233 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004234 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004235 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004236 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004237 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004238 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004239 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004240 Decimal("4.28135971E+11")
4241 """
4242 return a.__mul__(b, context=self)
4243
Facundo Batista353750c2007-09-13 18:13:15 +00004244 def next_minus(self, a):
4245 """Returns the largest representable number smaller than a.
4246
4247 >>> c = ExtendedContext.copy()
4248 >>> c.Emin = -999
4249 >>> c.Emax = 999
4250 >>> ExtendedContext.next_minus(Decimal('1'))
4251 Decimal("0.999999999")
4252 >>> c.next_minus(Decimal('1E-1007'))
4253 Decimal("0E-1007")
4254 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4255 Decimal("-1.00000004")
4256 >>> c.next_minus(Decimal('Infinity'))
4257 Decimal("9.99999999E+999")
4258 """
4259 return a.next_minus(context=self)
4260
4261 def next_plus(self, a):
4262 """Returns the smallest representable number larger than a.
4263
4264 >>> c = ExtendedContext.copy()
4265 >>> c.Emin = -999
4266 >>> c.Emax = 999
4267 >>> ExtendedContext.next_plus(Decimal('1'))
4268 Decimal("1.00000001")
4269 >>> c.next_plus(Decimal('-1E-1007'))
4270 Decimal("-0E-1007")
4271 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4272 Decimal("-1.00000002")
4273 >>> c.next_plus(Decimal('-Infinity'))
4274 Decimal("-9.99999999E+999")
4275 """
4276 return a.next_plus(context=self)
4277
4278 def next_toward(self, a, b):
4279 """Returns the number closest to a, in direction towards b.
4280
4281 The result is the closest representable number from the first
4282 operand (but not the first operand) that is in the direction
4283 towards the second operand, unless the operands have the same
4284 value.
4285
4286 >>> c = ExtendedContext.copy()
4287 >>> c.Emin = -999
4288 >>> c.Emax = 999
4289 >>> c.next_toward(Decimal('1'), Decimal('2'))
4290 Decimal("1.00000001")
4291 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4292 Decimal("-0E-1007")
4293 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4294 Decimal("-1.00000002")
4295 >>> c.next_toward(Decimal('1'), Decimal('0'))
4296 Decimal("0.999999999")
4297 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4298 Decimal("0E-1007")
4299 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4300 Decimal("-1.00000004")
4301 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4302 Decimal("-0.00")
4303 """
4304 return a.next_toward(b, context=self)
4305
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004306 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004307 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004308
4309 Essentially a plus operation with all trailing zeros removed from the
4310 result.
4311
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004312 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004313 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004314 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004315 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004316 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004317 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004318 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004319 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004320 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004321 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004322 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004323 Decimal("0")
4324 """
4325 return a.normalize(context=self)
4326
Facundo Batista353750c2007-09-13 18:13:15 +00004327 def number_class(self, a):
4328 """Returns an indication of the class of the operand.
4329
4330 The class is one of the following strings:
4331 -sNaN
4332 -NaN
4333 -Infinity
4334 -Normal
4335 -Subnormal
4336 -Zero
4337 +Zero
4338 +Subnormal
4339 +Normal
4340 +Infinity
4341
4342 >>> c = Context(ExtendedContext)
4343 >>> c.Emin = -999
4344 >>> c.Emax = 999
4345 >>> c.number_class(Decimal('Infinity'))
4346 '+Infinity'
4347 >>> c.number_class(Decimal('1E-10'))
4348 '+Normal'
4349 >>> c.number_class(Decimal('2.50'))
4350 '+Normal'
4351 >>> c.number_class(Decimal('0.1E-999'))
4352 '+Subnormal'
4353 >>> c.number_class(Decimal('0'))
4354 '+Zero'
4355 >>> c.number_class(Decimal('-0'))
4356 '-Zero'
4357 >>> c.number_class(Decimal('-0.1E-999'))
4358 '-Subnormal'
4359 >>> c.number_class(Decimal('-1E-10'))
4360 '-Normal'
4361 >>> c.number_class(Decimal('-2.50'))
4362 '-Normal'
4363 >>> c.number_class(Decimal('-Infinity'))
4364 '-Infinity'
4365 >>> c.number_class(Decimal('NaN'))
4366 'NaN'
4367 >>> c.number_class(Decimal('-NaN'))
4368 'NaN'
4369 >>> c.number_class(Decimal('sNaN'))
4370 'sNaN'
4371 """
4372 return a.number_class(context=self)
4373
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004374 def plus(self, a):
4375 """Plus corresponds to unary prefix plus in Python.
4376
4377 The operation is evaluated using the same rules as add; the
4378 operation plus(a) is calculated as add('0', a) where the '0'
4379 has the same exponent as the operand.
4380
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004381 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004382 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004383 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004384 Decimal("-1.3")
4385 """
4386 return a.__pos__(context=self)
4387
4388 def power(self, a, b, modulo=None):
4389 """Raises a to the power of b, to modulo if given.
4390
Facundo Batista353750c2007-09-13 18:13:15 +00004391 With two arguments, compute a**b. If a is negative then b
4392 must be integral. The result will be inexact unless b is
4393 integral and the result is finite and can be expressed exactly
4394 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004395
Facundo Batista353750c2007-09-13 18:13:15 +00004396 With three arguments, compute (a**b) % modulo. For the
4397 three argument form, the following restrictions on the
4398 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004399
Facundo Batista353750c2007-09-13 18:13:15 +00004400 - all three arguments must be integral
4401 - b must be nonnegative
4402 - at least one of a or b must be nonzero
4403 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004404
Facundo Batista353750c2007-09-13 18:13:15 +00004405 The result of pow(a, b, modulo) is identical to the result
4406 that would be obtained by computing (a**b) % modulo with
4407 unbounded precision, but is computed more efficiently. It is
4408 always exact.
4409
4410 >>> c = ExtendedContext.copy()
4411 >>> c.Emin = -999
4412 >>> c.Emax = 999
4413 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004414 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004415 >>> c.power(Decimal('-2'), Decimal('3'))
4416 Decimal("-8")
4417 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004418 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004419 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004420 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004421 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4422 Decimal("2.00000000")
4423 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004424 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004425 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004426 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004427 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004428 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004429 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004430 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004431 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004432 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004433 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004434 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004435 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004436 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004437 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004438 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004439
4440 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4441 Decimal("11")
4442 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4443 Decimal("-11")
4444 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4445 Decimal("1")
4446 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4447 Decimal("11")
4448 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4449 Decimal("11729830")
4450 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4451 Decimal("-0")
4452 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4453 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004454 """
4455 return a.__pow__(b, modulo, context=self)
4456
4457 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004458 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004459
4460 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004461 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004462 exponent is being increased), multiplied by a positive power of ten (if
4463 the exponent is being decreased), or is unchanged (if the exponent is
4464 already equal to that of the right-hand operand).
4465
4466 Unlike other operations, if the length of the coefficient after the
4467 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004468 operation condition is raised. This guarantees that, unless there is
4469 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004470 equal to that of the right-hand operand.
4471
4472 Also unlike other operations, quantize will never raise Underflow, even
4473 if the result is subnormal and inexact.
4474
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004475 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004476 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004477 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004478 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004479 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004480 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004481 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004482 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004483 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004484 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004485 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004486 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004487 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004488 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004489 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004490 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004491 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004492 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004493 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004494 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004495 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004496 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004497 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004498 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004499 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004500 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004501 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004502 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004503 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004504 Decimal("2E+2")
4505 """
4506 return a.quantize(b, context=self)
4507
Facundo Batista353750c2007-09-13 18:13:15 +00004508 def radix(self):
4509 """Just returns 10, as this is Decimal, :)
4510
4511 >>> ExtendedContext.radix()
4512 Decimal("10")
4513 """
4514 return Decimal(10)
4515
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004516 def remainder(self, a, b):
4517 """Returns the remainder from integer division.
4518
4519 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004520 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004521 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004522 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004523
4524 This operation will fail under the same conditions as integer division
4525 (that is, if integer division on the same two operands would fail, the
4526 remainder cannot be calculated).
4527
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004528 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004529 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004530 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004531 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004532 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004533 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004534 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004535 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004536 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004537 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004538 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004539 Decimal("1.0")
4540 """
4541 return a.__mod__(b, context=self)
4542
4543 def remainder_near(self, a, b):
4544 """Returns to be "a - b * n", where n is the integer nearest the exact
4545 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004546 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004547 sign of a.
4548
4549 This operation will fail under the same conditions as integer division
4550 (that is, if integer division on the same two operands would fail, the
4551 remainder cannot be calculated).
4552
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004553 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004554 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004555 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004556 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004557 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004558 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004559 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004560 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004561 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004562 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004563 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004564 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004565 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004566 Decimal("-0.3")
4567 """
4568 return a.remainder_near(b, context=self)
4569
Facundo Batista353750c2007-09-13 18:13:15 +00004570 def rotate(self, a, b):
4571 """Returns a rotated copy of a, b times.
4572
4573 The coefficient of the result is a rotated copy of the digits in
4574 the coefficient of the first operand. The number of places of
4575 rotation is taken from the absolute value of the second operand,
4576 with the rotation being to the left if the second operand is
4577 positive or to the right otherwise.
4578
4579 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4580 Decimal("400000003")
4581 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4582 Decimal("12")
4583 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4584 Decimal("891234567")
4585 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4586 Decimal("123456789")
4587 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4588 Decimal("345678912")
4589 """
4590 return a.rotate(b, context=self)
4591
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004592 def same_quantum(self, a, b):
4593 """Returns True if the two operands have the same exponent.
4594
4595 The result is never affected by either the sign or the coefficient of
4596 either operand.
4597
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004598 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004599 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004600 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004601 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004602 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004603 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004604 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004605 True
4606 """
4607 return a.same_quantum(b)
4608
Facundo Batista353750c2007-09-13 18:13:15 +00004609 def scaleb (self, a, b):
4610 """Returns the first operand after adding the second value its exp.
4611
4612 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4613 Decimal("0.0750")
4614 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4615 Decimal("7.50")
4616 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4617 Decimal("7.50E+3")
4618 """
4619 return a.scaleb (b, context=self)
4620
4621 def shift(self, a, b):
4622 """Returns a shifted copy of a, b times.
4623
4624 The coefficient of the result is a shifted copy of the digits
4625 in the coefficient of the first operand. The number of places
4626 to shift is taken from the absolute value of the second operand,
4627 with the shift being to the left if the second operand is
4628 positive or to the right otherwise. Digits shifted into the
4629 coefficient are zeros.
4630
4631 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4632 Decimal("400000000")
4633 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4634 Decimal("0")
4635 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4636 Decimal("1234567")
4637 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4638 Decimal("123456789")
4639 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4640 Decimal("345678900")
4641 """
4642 return a.shift(b, context=self)
4643
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004644 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004645 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004646
4647 If the result must be inexact, it is rounded using the round-half-even
4648 algorithm.
4649
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004650 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004651 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004652 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004653 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004654 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004655 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004656 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004657 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004658 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004659 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004660 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004661 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004662 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004663 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004664 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004665 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004666 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004667 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004668 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004669 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004670 """
4671 return a.sqrt(context=self)
4672
4673 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004674 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004675
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004676 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004677 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004678 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004679 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004680 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004681 Decimal("-0.77")
4682 """
4683 return a.__sub__(b, context=self)
4684
4685 def to_eng_string(self, a):
4686 """Converts a number to a string, using scientific notation.
4687
4688 The operation is not affected by the context.
4689 """
4690 return a.to_eng_string(context=self)
4691
4692 def to_sci_string(self, a):
4693 """Converts a number to a string, using scientific notation.
4694
4695 The operation is not affected by the context.
4696 """
4697 return a.__str__(context=self)
4698
Facundo Batista353750c2007-09-13 18:13:15 +00004699 def to_integral_exact(self, a):
4700 """Rounds to an integer.
4701
4702 When the operand has a negative exponent, the result is the same
4703 as using the quantize() operation using the given operand as the
4704 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4705 of the operand as the precision setting; Inexact and Rounded flags
4706 are allowed in this operation. The rounding mode is taken from the
4707 context.
4708
4709 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4710 Decimal("2")
4711 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4712 Decimal("100")
4713 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4714 Decimal("100")
4715 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4716 Decimal("102")
4717 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4718 Decimal("-102")
4719 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4720 Decimal("1.0E+6")
4721 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4722 Decimal("7.89E+77")
4723 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4724 Decimal("-Infinity")
4725 """
4726 return a.to_integral_exact(context=self)
4727
4728 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004729 """Rounds to an integer.
4730
4731 When the operand has a negative exponent, the result is the same
4732 as using the quantize() operation using the given operand as the
4733 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4734 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004735 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004736
Facundo Batista353750c2007-09-13 18:13:15 +00004737 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004738 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004739 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004740 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004741 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004742 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004743 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004744 Decimal("102")
Facundo Batista353750c2007-09-13 18:13:15 +00004745 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004746 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004747 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004748 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004749 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004750 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004751 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004752 Decimal("-Infinity")
4753 """
Facundo Batista353750c2007-09-13 18:13:15 +00004754 return a.to_integral_value(context=self)
4755
4756 # the method name changed, but we provide also the old one, for compatibility
4757 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004758
4759class _WorkRep(object):
4760 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004761 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004762 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004763 # exp: None, int, or string
4764
4765 def __init__(self, value=None):
4766 if value is None:
4767 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004768 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004769 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004770 elif isinstance(value, Decimal):
4771 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004772 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004773 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004774 else:
4775 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004776 self.sign = value[0]
4777 self.int = value[1]
4778 self.exp = value[2]
4779
4780 def __repr__(self):
4781 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4782
4783 __str__ = __repr__
4784
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004785
4786
Facundo Batistae64acfa2007-12-17 14:18:42 +00004787def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004788 """Normalizes op1, op2 to have the same exp and length of coefficient.
4789
4790 Done during addition.
4791 """
Facundo Batista353750c2007-09-13 18:13:15 +00004792 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004793 tmp = op2
4794 other = op1
4795 else:
4796 tmp = op1
4797 other = op2
4798
Facundo Batista353750c2007-09-13 18:13:15 +00004799 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4800 # Then adding 10**exp to tmp has the same effect (after rounding)
4801 # as adding any positive quantity smaller than 10**exp; similarly
4802 # for subtraction. So if other is smaller than 10**exp we replace
4803 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00004804 tmp_len = len(str(tmp.int))
4805 other_len = len(str(other.int))
4806 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4807 if other_len + other.exp - 1 < exp:
4808 other.int = 1
4809 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004810
Facundo Batista353750c2007-09-13 18:13:15 +00004811 tmp.int *= 10 ** (tmp.exp - other.exp)
4812 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004813 return op1, op2
4814
Facundo Batista353750c2007-09-13 18:13:15 +00004815##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4816
4817# This function from Tim Peters was taken from here:
4818# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4819# The correction being in the function definition is for speed, and
4820# the whole function is not resolved with math.log because of avoiding
4821# the use of floats.
4822def _nbits(n, correction = {
4823 '0': 4, '1': 3, '2': 2, '3': 2,
4824 '4': 1, '5': 1, '6': 1, '7': 1,
4825 '8': 0, '9': 0, 'a': 0, 'b': 0,
4826 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4827 """Number of bits in binary representation of the positive integer n,
4828 or 0 if n == 0.
4829 """
4830 if n < 0:
4831 raise ValueError("The argument to _nbits should be nonnegative.")
4832 hex_n = "%x" % n
4833 return 4*len(hex_n) - correction[hex_n[0]]
4834
4835def _sqrt_nearest(n, a):
4836 """Closest integer to the square root of the positive integer n. a is
4837 an initial approximation to the square root. Any positive integer
4838 will do for a, but the closer a is to the square root of n the
4839 faster convergence will be.
4840
4841 """
4842 if n <= 0 or a <= 0:
4843 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4844
4845 b=0
4846 while a != b:
4847 b, a = a, a--n//a>>1
4848 return a
4849
4850def _rshift_nearest(x, shift):
4851 """Given an integer x and a nonnegative integer shift, return closest
4852 integer to x / 2**shift; use round-to-even in case of a tie.
4853
4854 """
4855 b, q = 1L << shift, x >> shift
4856 return q + (2*(x & (b-1)) + (q&1) > b)
4857
4858def _div_nearest(a, b):
4859 """Closest integer to a/b, a and b positive integers; rounds to even
4860 in the case of a tie.
4861
4862 """
4863 q, r = divmod(a, b)
4864 return q + (2*r + (q&1) > b)
4865
4866def _ilog(x, M, L = 8):
4867 """Integer approximation to M*log(x/M), with absolute error boundable
4868 in terms only of x/M.
4869
4870 Given positive integers x and M, return an integer approximation to
4871 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4872 between the approximation and the exact result is at most 22. For
4873 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4874 both cases these are upper bounds on the error; it will usually be
4875 much smaller."""
4876
4877 # The basic algorithm is the following: let log1p be the function
4878 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4879 # the reduction
4880 #
4881 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4882 #
4883 # repeatedly until the argument to log1p is small (< 2**-L in
4884 # absolute value). For small y we can use the Taylor series
4885 # expansion
4886 #
4887 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4888 #
4889 # truncating at T such that y**T is small enough. The whole
4890 # computation is carried out in a form of fixed-point arithmetic,
4891 # with a real number z being represented by an integer
4892 # approximation to z*M. To avoid loss of precision, the y below
4893 # is actually an integer approximation to 2**R*y*M, where R is the
4894 # number of reductions performed so far.
4895
4896 y = x-M
4897 # argument reduction; R = number of reductions performed
4898 R = 0
4899 while (R <= L and long(abs(y)) << L-R >= M or
4900 R > L and abs(y) >> R-L >= M):
4901 y = _div_nearest(long(M*y) << 1,
4902 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4903 R += 1
4904
4905 # Taylor series with T terms
4906 T = -int(-10*len(str(M))//(3*L))
4907 yshift = _rshift_nearest(y, R)
4908 w = _div_nearest(M, T)
4909 for k in xrange(T-1, 0, -1):
4910 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4911
4912 return _div_nearest(w*y, M)
4913
4914def _dlog10(c, e, p):
4915 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4916 approximation to 10**p * log10(c*10**e), with an absolute error of
4917 at most 1. Assumes that c*10**e is not exactly 1."""
4918
4919 # increase precision by 2; compensate for this by dividing
4920 # final result by 100
4921 p += 2
4922
4923 # write c*10**e as d*10**f with either:
4924 # f >= 0 and 1 <= d <= 10, or
4925 # f <= 0 and 0.1 <= d <= 1.
4926 # Thus for c*10**e close to 1, f = 0
4927 l = len(str(c))
4928 f = e+l - (e+l >= 1)
4929
4930 if p > 0:
4931 M = 10**p
4932 k = e+p-f
4933 if k >= 0:
4934 c *= 10**k
4935 else:
4936 c = _div_nearest(c, 10**-k)
4937
4938 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004939 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004940 log_d = _div_nearest(log_d*M, log_10)
4941 log_tenpower = f*M # exact
4942 else:
4943 log_d = 0 # error < 2.31
4944 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4945
4946 return _div_nearest(log_tenpower+log_d, 100)
4947
4948def _dlog(c, e, p):
4949 """Given integers c, e and p with c > 0, compute an integer
4950 approximation to 10**p * log(c*10**e), with an absolute error of
4951 at most 1. Assumes that c*10**e is not exactly 1."""
4952
4953 # Increase precision by 2. The precision increase is compensated
4954 # for at the end with a division by 100.
4955 p += 2
4956
4957 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4958 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4959 # as 10**p * log(d) + 10**p*f * log(10).
4960 l = len(str(c))
4961 f = e+l - (e+l >= 1)
4962
4963 # compute approximation to 10**p*log(d), with error < 27
4964 if p > 0:
4965 k = e+p-f
4966 if k >= 0:
4967 c *= 10**k
4968 else:
4969 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4970
4971 # _ilog magnifies existing error in c by a factor of at most 10
4972 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4973 else:
4974 # p <= 0: just approximate the whole thing by 0; error < 2.31
4975 log_d = 0
4976
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004977 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00004978 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004979 extra = len(str(abs(f)))-1
4980 if p + extra >= 0:
4981 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4982 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4983 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00004984 else:
4985 f_log_ten = 0
4986 else:
4987 f_log_ten = 0
4988
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004989 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004990 return _div_nearest(f_log_ten + log_d, 100)
4991
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004992class _Log10Memoize(object):
4993 """Class to compute, store, and allow retrieval of, digits of the
4994 constant log(10) = 2.302585.... This constant is needed by
4995 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4996 def __init__(self):
4997 self.digits = "23025850929940456840179914546843642076011014886"
4998
4999 def getdigits(self, p):
5000 """Given an integer p >= 0, return floor(10**p)*log(10).
5001
5002 For example, self.getdigits(3) returns 2302.
5003 """
5004 # digits are stored as a string, for quick conversion to
5005 # integer in the case that we've already computed enough
5006 # digits; the stored digits should always be correct
5007 # (truncated, not rounded to nearest).
5008 if p < 0:
5009 raise ValueError("p should be nonnegative")
5010
5011 if p >= len(self.digits):
5012 # compute p+3, p+6, p+9, ... digits; continue until at
5013 # least one of the extra digits is nonzero
5014 extra = 3
5015 while True:
5016 # compute p+extra digits, correct to within 1ulp
5017 M = 10**(p+extra+2)
5018 digits = str(_div_nearest(_ilog(10*M, M), 100))
5019 if digits[-extra:] != '0'*extra:
5020 break
5021 extra += 3
5022 # keep all reliable digits so far; remove trailing zeros
5023 # and next nonzero digit
5024 self.digits = digits.rstrip('0')[:-1]
5025 return int(self.digits[:p+1])
5026
5027_log10_digits = _Log10Memoize().getdigits
5028
Facundo Batista353750c2007-09-13 18:13:15 +00005029def _iexp(x, M, L=8):
5030 """Given integers x and M, M > 0, such that x/M is small in absolute
5031 value, compute an integer approximation to M*exp(x/M). For 0 <=
5032 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5033 is usually much smaller)."""
5034
5035 # Algorithm: to compute exp(z) for a real number z, first divide z
5036 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5037 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5038 # series
5039 #
5040 # expm1(x) = x + x**2/2! + x**3/3! + ...
5041 #
5042 # Now use the identity
5043 #
5044 # expm1(2x) = expm1(x)*(expm1(x)+2)
5045 #
5046 # R times to compute the sequence expm1(z/2**R),
5047 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5048
5049 # Find R such that x/2**R/M <= 2**-L
5050 R = _nbits((long(x)<<L)//M)
5051
5052 # Taylor series. (2**L)**T > M
5053 T = -int(-10*len(str(M))//(3*L))
5054 y = _div_nearest(x, T)
5055 Mshift = long(M)<<R
5056 for i in xrange(T-1, 0, -1):
5057 y = _div_nearest(x*(Mshift + y), Mshift * i)
5058
5059 # Expansion
5060 for k in xrange(R-1, -1, -1):
5061 Mshift = long(M)<<(k+2)
5062 y = _div_nearest(y*(y+Mshift), Mshift)
5063
5064 return M+y
5065
5066def _dexp(c, e, p):
5067 """Compute an approximation to exp(c*10**e), with p decimal places of
5068 precision.
5069
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005070 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005071
5072 10**(p-1) <= d <= 10**p, and
5073 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5074
5075 In other words, d*10**f is an approximation to exp(c*10**e) with p
5076 digits of precision, and with an error in d of at most 1. This is
5077 almost, but not quite, the same as the error being < 1ulp: when d
5078 = 10**(p-1) the error could be up to 10 ulp."""
5079
5080 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5081 p += 2
5082
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005083 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005084 extra = max(0, e + len(str(c)) - 1)
5085 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005086
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005087 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005088 # rounding down
5089 shift = e+q
5090 if shift >= 0:
5091 cshift = c*10**shift
5092 else:
5093 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005094 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005095
5096 # reduce remainder back to original precision
5097 rem = _div_nearest(rem, 10**extra)
5098
5099 # error in result of _iexp < 120; error after division < 0.62
5100 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5101
5102def _dpower(xc, xe, yc, ye, p):
5103 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5104 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5105
5106 10**(p-1) <= c <= 10**p, and
5107 (c-1)*10**e < x**y < (c+1)*10**e
5108
5109 in other words, c*10**e is an approximation to x**y with p digits
5110 of precision, and with an error in c of at most 1. (This is
5111 almost, but not quite, the same as the error being < 1ulp: when c
5112 == 10**(p-1) we can only guarantee error < 10ulp.)
5113
5114 We assume that: x is positive and not equal to 1, and y is nonzero.
5115 """
5116
5117 # Find b such that 10**(b-1) <= |y| <= 10**b
5118 b = len(str(abs(yc))) + ye
5119
5120 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5121 lxc = _dlog(xc, xe, p+b+1)
5122
5123 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5124 shift = ye-b
5125 if shift >= 0:
5126 pc = lxc*yc*10**shift
5127 else:
5128 pc = _div_nearest(lxc*yc, 10**-shift)
5129
5130 if pc == 0:
5131 # we prefer a result that isn't exactly 1; this makes it
5132 # easier to compute a correctly rounded result in __pow__
5133 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5134 coeff, exp = 10**(p-1)+1, 1-p
5135 else:
5136 coeff, exp = 10**p-1, -p
5137 else:
5138 coeff, exp = _dexp(pc, -(p+1), p+1)
5139 coeff = _div_nearest(coeff, 10)
5140 exp += 1
5141
5142 return coeff, exp
5143
5144def _log10_lb(c, correction = {
5145 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5146 '6': 23, '7': 16, '8': 10, '9': 5}):
5147 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5148 if c <= 0:
5149 raise ValueError("The argument to _log10_lb should be nonnegative.")
5150 str_c = str(c)
5151 return 100*len(str_c) - correction[str_c[0]]
5152
Facundo Batista59c58842007-04-10 12:58:45 +00005153##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005154
Facundo Batista353750c2007-09-13 18:13:15 +00005155def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005156 """Convert other to Decimal.
5157
5158 Verifies that it's ok to use in an implicit construction.
5159 """
5160 if isinstance(other, Decimal):
5161 return other
5162 if isinstance(other, (int, long)):
5163 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005164 if raiseit:
5165 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005166 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005167
Facundo Batista59c58842007-04-10 12:58:45 +00005168##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005169
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005170# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005171# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005172
5173DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005174 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005175 traps=[DivisionByZero, Overflow, InvalidOperation],
5176 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005177 Emax=999999999,
5178 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005179 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005180)
5181
5182# Pre-made alternate contexts offered by the specification
5183# Don't change these; the user should be able to select these
5184# contexts and be able to reproduce results from other implementations
5185# of the spec.
5186
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005187BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005188 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005189 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5190 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005191)
5192
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005193ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005194 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005195 traps=[],
5196 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005197)
5198
5199
Facundo Batista72bc54f2007-11-23 17:59:00 +00005200##### crud for parsing strings #############################################
5201import re
5202
5203# Regular expression used for parsing numeric strings. Additional
5204# comments:
5205#
5206# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5207# whitespace. But note that the specification disallows whitespace in
5208# a numeric string.
5209#
5210# 2. For finite numbers (not infinities and NaNs) the body of the
5211# number between the optional sign and the optional exponent must have
5212# at least one decimal digit, possibly after the decimal point. The
5213# lookahead expression '(?=\d|\.\d)' checks this.
5214#
5215# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5216# other meaning for \d than the numbers [0-9].
5217
5218import re
5219_parser = re.compile(r""" # A numeric string consists of:
5220# \s*
5221 (?P<sign>[-+])? # an optional sign, followed by either...
5222 (
5223 (?=\d|\.\d) # ...a number (with at least one digit)
5224 (?P<int>\d*) # consisting of a (possibly empty) integer part
5225 (\.(?P<frac>\d*))? # followed by an optional fractional part
5226 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5227 |
5228 Inf(inity)? # ...an infinity, or...
5229 |
5230 (?P<signal>s)? # ...an (optionally signaling)
5231 NaN # NaN
5232 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5233 )
5234# \s*
Mark Dickinson59bc20b2008-01-12 01:56:00 +00005235 \Z
Facundo Batista72bc54f2007-11-23 17:59:00 +00005236""", re.VERBOSE | re.IGNORECASE).match
5237
Facundo Batista2ec74152007-12-03 17:55:00 +00005238_all_zeros = re.compile('0*$').match
5239_exact_half = re.compile('50*$').match
Facundo Batista72bc54f2007-11-23 17:59:00 +00005240del re
5241
5242
Facundo Batista59c58842007-04-10 12:58:45 +00005243##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005244
Facundo Batista59c58842007-04-10 12:58:45 +00005245# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005246Inf = Decimal('Inf')
5247negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005248NaN = Decimal('NaN')
5249Dec_0 = Decimal(0)
5250Dec_p1 = Decimal(1)
5251Dec_n1 = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005252
Facundo Batista59c58842007-04-10 12:58:45 +00005253# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005254Infsign = (Inf, negInf)
5255
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005256
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005257
5258if __name__ == '__main__':
5259 import doctest, sys
5260 doctest.testmod(sys.modules[__name__])