blob: e624a6dbbec16f4be98da63d00ae1240c2adf2c8 [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
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000720 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000721 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000722
Facundo Batista1a191df2007-10-02 17:01:24 +0000723 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000724 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000725 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000726
Facundo Batista353750c2007-09-13 18:13:15 +0000727 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000728 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000729 if other is NotImplemented:
Facundo Batista353750c2007-09-13 18:13:15 +0000730 # Never return NotImplemented
731 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000732
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000733 if self._is_special or other._is_special:
Facundo Batista353750c2007-09-13 18:13:15 +0000734 # check for nans, without raising on a signaling nan
735 if self._isnan() or other._isnan():
Facundo Batista59c58842007-04-10 12:58:45 +0000736 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000737
738 # INF = INF
739 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000740
Facundo Batista353750c2007-09-13 18:13:15 +0000741 # check for zeros; note that cmp(0, -0) should return 0
742 if not self:
743 if not other:
744 return 0
745 else:
746 return -((-1)**other._sign)
747 if not other:
748 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000749
Facundo Batista59c58842007-04-10 12:58:45 +0000750 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000751 if other._sign < self._sign:
752 return -1
753 if self._sign < other._sign:
754 return 1
755
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000756 self_adjusted = self.adjusted()
757 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000758 if self_adjusted == other_adjusted:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000759 self_padded = self._int + '0'*(self._exp - other._exp)
760 other_padded = other._int + '0'*(other._exp - self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +0000761 return cmp(self_padded, other_padded) * (-1)**self._sign
762 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000763 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000764 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000765 return -((-1)**self._sign)
766
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000767 def __eq__(self, other):
768 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000769 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000770 return self.__cmp__(other) == 0
771
772 def __ne__(self, other):
773 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000774 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000775 return self.__cmp__(other) != 0
776
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000777 def compare(self, other, context=None):
778 """Compares one to another.
779
780 -1 => a < b
781 0 => a = b
782 1 => a > b
783 NaN => one is NaN
784 Like __cmp__, but returns Decimal instances.
785 """
Facundo Batista353750c2007-09-13 18:13:15 +0000786 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000787
Facundo Batista59c58842007-04-10 12:58:45 +0000788 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000789 if (self._is_special or other and other._is_special):
790 ans = self._check_nans(other, context)
791 if ans:
792 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000793
Facundo Batista353750c2007-09-13 18:13:15 +0000794 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000795
796 def __hash__(self):
797 """x.__hash__() <==> hash(x)"""
798 # Decimal integers must hash the same as the ints
Facundo Batista52b25792008-01-08 12:25:20 +0000799 #
800 # The hash of a nonspecial noninteger Decimal must depend only
801 # on the value of that Decimal, and not on its representation.
802 # For example: hash(Decimal("100E-1")) == hash(Decimal("10")).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000803 if self._is_special:
804 if self._isnan():
805 raise TypeError('Cannot hash a NaN value.')
806 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000807 if not self:
808 return 0
809 if self._isinteger():
810 op = _WorkRep(self.to_integral_value())
811 # to make computation feasible for Decimals with large
812 # exponent, we use the fact that hash(n) == hash(m) for
813 # any two nonzero integers n and m such that (i) n and m
814 # have the same sign, and (ii) n is congruent to m modulo
815 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
816 # hash((-1)**s*c*pow(10, e, 2**64-1).
817 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Facundo Batista52b25792008-01-08 12:25:20 +0000818 # The value of a nonzero nonspecial Decimal instance is
819 # faithfully represented by the triple consisting of its sign,
820 # its adjusted exponent, and its coefficient with trailing
821 # zeros removed.
822 return hash((self._sign,
823 self._exp+len(self._int),
824 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000825
826 def as_tuple(self):
827 """Represents the number as a triple tuple.
828
829 To show the internals exactly as they are.
830 """
Raymond Hettinger097a1902008-01-11 02:24:13 +0000831 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000832
833 def __repr__(self):
834 """Represents the number as an instance of Decimal."""
835 # Invariant: eval(repr(d)) == d
836 return 'Decimal("%s")' % str(self)
837
Facundo Batista353750c2007-09-13 18:13:15 +0000838 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000839 """Return string representation of the number in scientific notation.
840
841 Captures all of the information in the underlying representation.
842 """
843
Facundo Batista62edb712007-12-03 16:29:52 +0000844 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000845 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +0000846 if self._exp == 'F':
847 return sign + 'Infinity'
848 elif self._exp == 'n':
849 return sign + 'NaN' + self._int
850 else: # self._exp == 'N'
851 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000852
Facundo Batista62edb712007-12-03 16:29:52 +0000853 # number of digits of self._int to left of decimal point
854 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000855
Facundo Batista62edb712007-12-03 16:29:52 +0000856 # dotplace is number of digits of self._int to the left of the
857 # decimal point in the mantissa of the output string (that is,
858 # after adjusting the exponent)
859 if self._exp <= 0 and leftdigits > -6:
860 # no exponent required
861 dotplace = leftdigits
862 elif not eng:
863 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000864 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +0000865 elif self._int == '0':
866 # engineering notation, zero
867 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000868 else:
Facundo Batista62edb712007-12-03 16:29:52 +0000869 # engineering notation, nonzero
870 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000871
Facundo Batista62edb712007-12-03 16:29:52 +0000872 if dotplace <= 0:
873 intpart = '0'
874 fracpart = '.' + '0'*(-dotplace) + self._int
875 elif dotplace >= len(self._int):
876 intpart = self._int+'0'*(dotplace-len(self._int))
877 fracpart = ''
878 else:
879 intpart = self._int[:dotplace]
880 fracpart = '.' + self._int[dotplace:]
881 if leftdigits == dotplace:
882 exp = ''
883 else:
884 if context is None:
885 context = getcontext()
886 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
887
888 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000889
890 def to_eng_string(self, context=None):
891 """Convert to engineering-type string.
892
893 Engineering notation has an exponent which is a multiple of 3, so there
894 are up to 3 digits left of the decimal place.
895
896 Same rules for when in exponential and when as a value as in __str__.
897 """
Facundo Batista353750c2007-09-13 18:13:15 +0000898 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000899
900 def __neg__(self, context=None):
901 """Returns a copy with the sign switched.
902
903 Rounds, if it has reason.
904 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000905 if self._is_special:
906 ans = self._check_nans(context=context)
907 if ans:
908 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000909
910 if not self:
911 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000912 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000913 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000914 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000915
916 if context is None:
917 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +0000918 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000919
920 def __pos__(self, context=None):
921 """Returns a copy, unless it is a sNaN.
922
923 Rounds the number (if more then precision digits)
924 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000925 if self._is_special:
926 ans = self._check_nans(context=context)
927 if ans:
928 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000929
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000930 if not self:
931 # + (-0) = 0
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000932 ans = self.copy_abs()
Facundo Batista353750c2007-09-13 18:13:15 +0000933 else:
934 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000935
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000936 if context is None:
937 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +0000938 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000939
Facundo Batistae64acfa2007-12-17 14:18:42 +0000940 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000941 """Returns the absolute value of self.
942
Facundo Batistae64acfa2007-12-17 14:18:42 +0000943 If the keyword argument 'round' is false, do not round. The
944 expression self.__abs__(round=False) is equivalent to
945 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000946 """
Facundo Batistae64acfa2007-12-17 14:18:42 +0000947 if not round:
948 return self.copy_abs()
949
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000950 if self._is_special:
951 ans = self._check_nans(context=context)
952 if ans:
953 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000954
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000955 if self._sign:
956 ans = self.__neg__(context=context)
957 else:
958 ans = self.__pos__(context=context)
959
960 return ans
961
962 def __add__(self, other, context=None):
963 """Returns self + other.
964
965 -INF + INF (or the reverse) cause InvalidOperation errors.
966 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000967 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000968 if other is NotImplemented:
969 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000970
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971 if context is None:
972 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000973
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000974 if self._is_special or other._is_special:
975 ans = self._check_nans(other, context)
976 if ans:
977 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000978
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000979 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000980 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000981 if self._sign != other._sign and other._isinfinity():
982 return context._raise_error(InvalidOperation, '-INF + INF')
983 return Decimal(self)
984 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000985 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000986
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000987 exp = min(self._exp, other._exp)
988 negativezero = 0
989 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +0000990 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000991 negativezero = 1
992
993 if not self and not other:
994 sign = min(self._sign, other._sign)
995 if negativezero:
996 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +0000997 ans = _dec_from_triple(sign, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +0000998 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +0000999 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001001 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001002 ans = other._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001003 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001004 return ans
1005 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001006 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001007 ans = self._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001008 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009 return ans
1010
1011 op1 = _WorkRep(self)
1012 op2 = _WorkRep(other)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001013 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001014
1015 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001016 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001017 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001018 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001019 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001020 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001021 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001022 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001023 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001024 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001025 if op1.sign == 1:
1026 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001027 op1.sign, op2.sign = op2.sign, op1.sign
1028 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001029 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001030 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001031 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001032 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001033 op1.sign, op2.sign = (0, 0)
1034 else:
1035 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001036 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001037
Raymond Hettinger17931de2004-10-27 06:21:46 +00001038 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001039 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001040 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001041 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001042
1043 result.exp = op1.exp
1044 ans = Decimal(result)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001045 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001046 return ans
1047
1048 __radd__ = __add__
1049
1050 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001051 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001052 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001053 if other is NotImplemented:
1054 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001056 if self._is_special or other._is_special:
1057 ans = self._check_nans(other, context=context)
1058 if ans:
1059 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001060
Facundo Batista353750c2007-09-13 18:13:15 +00001061 # self - other is computed as self + other.copy_negate()
1062 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001063
1064 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001065 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001066 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001067 if other is NotImplemented:
1068 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001069
Facundo Batista353750c2007-09-13 18:13:15 +00001070 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001071
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001072 def __mul__(self, other, context=None):
1073 """Return self * other.
1074
1075 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1076 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001077 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001078 if other is NotImplemented:
1079 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001080
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081 if context is None:
1082 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001083
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001084 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001085
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001086 if self._is_special or other._is_special:
1087 ans = self._check_nans(other, context)
1088 if ans:
1089 return ans
1090
1091 if self._isinfinity():
1092 if not other:
1093 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1094 return Infsign[resultsign]
1095
1096 if other._isinfinity():
1097 if not self:
1098 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1099 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001100
1101 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001102
1103 # Special case for multiplying by zero
1104 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001105 ans = _dec_from_triple(resultsign, '0', resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001106 # Fixing in case the exponent is out of bounds
1107 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001108 return ans
1109
1110 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001111 if self._int == '1':
1112 ans = _dec_from_triple(resultsign, other._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001113 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001114 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001115 if other._int == '1':
1116 ans = _dec_from_triple(resultsign, self._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001117 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001118 return ans
1119
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001120 op1 = _WorkRep(self)
1121 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001122
Facundo Batista72bc54f2007-11-23 17:59:00 +00001123 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001124 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001125
1126 return ans
1127 __rmul__ = __mul__
1128
1129 def __div__(self, other, context=None):
1130 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001131 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001132 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001133 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001134
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001135 if context is None:
1136 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001137
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001138 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001139
1140 if self._is_special or other._is_special:
1141 ans = self._check_nans(other, context)
1142 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001143 return ans
1144
1145 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001146 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001147
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001148 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001149 return Infsign[sign]
1150
1151 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001152 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001153 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001154
1155 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001156 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001157 if not self:
1158 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001159 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001160
Facundo Batistacce8df22007-09-18 16:53:18 +00001161 if not self:
1162 exp = self._exp - other._exp
1163 coeff = 0
1164 else:
1165 # OK, so neither = 0, INF or NaN
1166 shift = len(other._int) - len(self._int) + context.prec + 1
1167 exp = self._exp - other._exp - shift
1168 op1 = _WorkRep(self)
1169 op2 = _WorkRep(other)
1170 if shift >= 0:
1171 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1172 else:
1173 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1174 if remainder:
1175 # result is not exact; adjust to ensure correct rounding
1176 if coeff % 5 == 0:
1177 coeff += 1
1178 else:
1179 # result is exact; get as close to ideal exponent as possible
1180 ideal_exp = self._exp - other._exp
1181 while exp < ideal_exp and coeff % 10 == 0:
1182 coeff //= 10
1183 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001184
Facundo Batista72bc54f2007-11-23 17:59:00 +00001185 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001186 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001187
Facundo Batistacce8df22007-09-18 16:53:18 +00001188 __truediv__ = __div__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001189
Facundo Batistacce8df22007-09-18 16:53:18 +00001190 def _divide(self, other, context):
1191 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001192
Facundo Batistacce8df22007-09-18 16:53:18 +00001193 Assumes that neither self nor other is a NaN, that self is not
1194 infinite and that other is nonzero.
1195 """
1196 sign = self._sign ^ other._sign
1197 if other._isinfinity():
1198 ideal_exp = self._exp
1199 else:
1200 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001201
Facundo Batistacce8df22007-09-18 16:53:18 +00001202 expdiff = self.adjusted() - other.adjusted()
1203 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001204 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001205 self._rescale(ideal_exp, context.rounding))
1206 if expdiff <= context.prec:
1207 op1 = _WorkRep(self)
1208 op2 = _WorkRep(other)
1209 if op1.exp >= op2.exp:
1210 op1.int *= 10**(op1.exp - op2.exp)
1211 else:
1212 op2.int *= 10**(op2.exp - op1.exp)
1213 q, r = divmod(op1.int, op2.int)
1214 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001215 return (_dec_from_triple(sign, str(q), 0),
1216 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001217
Facundo Batistacce8df22007-09-18 16:53:18 +00001218 # Here the quotient is too large to be representable
1219 ans = context._raise_error(DivisionImpossible,
1220 'quotient too large in //, % or divmod')
1221 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001222
1223 def __rdiv__(self, other, context=None):
1224 """Swaps self/other and returns __div__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001225 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001226 if other is NotImplemented:
1227 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001228 return other.__div__(self, context=context)
1229 __rtruediv__ = __rdiv__
1230
1231 def __divmod__(self, other, context=None):
1232 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001233 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001234 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001235 other = _convert_other(other)
1236 if other is NotImplemented:
1237 return other
1238
1239 if context is None:
1240 context = getcontext()
1241
1242 ans = self._check_nans(other, context)
1243 if ans:
1244 return (ans, ans)
1245
1246 sign = self._sign ^ other._sign
1247 if self._isinfinity():
1248 if other._isinfinity():
1249 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1250 return ans, ans
1251 else:
1252 return (Infsign[sign],
1253 context._raise_error(InvalidOperation, 'INF % x'))
1254
1255 if not other:
1256 if not self:
1257 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1258 return ans, ans
1259 else:
1260 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1261 context._raise_error(InvalidOperation, 'x % 0'))
1262
1263 quotient, remainder = self._divide(other, context)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001264 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001265 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001266
1267 def __rdivmod__(self, other, context=None):
1268 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001269 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001270 if other is NotImplemented:
1271 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001272 return other.__divmod__(self, context=context)
1273
1274 def __mod__(self, other, context=None):
1275 """
1276 self % other
1277 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001278 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001279 if other is NotImplemented:
1280 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001281
Facundo Batistacce8df22007-09-18 16:53:18 +00001282 if context is None:
1283 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001284
Facundo Batistacce8df22007-09-18 16:53:18 +00001285 ans = self._check_nans(other, context)
1286 if ans:
1287 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001288
Facundo Batistacce8df22007-09-18 16:53:18 +00001289 if self._isinfinity():
1290 return context._raise_error(InvalidOperation, 'INF % x')
1291 elif not other:
1292 if self:
1293 return context._raise_error(InvalidOperation, 'x % 0')
1294 else:
1295 return context._raise_error(DivisionUndefined, '0 % 0')
1296
1297 remainder = self._divide(other, context)[1]
Facundo Batistae64acfa2007-12-17 14:18:42 +00001298 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001299 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001300
1301 def __rmod__(self, other, context=None):
1302 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001303 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001304 if other is NotImplemented:
1305 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001306 return other.__mod__(self, context=context)
1307
1308 def remainder_near(self, other, context=None):
1309 """
1310 Remainder nearest to 0- abs(remainder-near) <= other/2
1311 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001312 if context is None:
1313 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001314
Facundo Batista353750c2007-09-13 18:13:15 +00001315 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001316
Facundo Batista353750c2007-09-13 18:13:15 +00001317 ans = self._check_nans(other, context)
1318 if ans:
1319 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001320
Facundo Batista353750c2007-09-13 18:13:15 +00001321 # self == +/-infinity -> InvalidOperation
1322 if self._isinfinity():
1323 return context._raise_error(InvalidOperation,
1324 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001325
Facundo Batista353750c2007-09-13 18:13:15 +00001326 # other == 0 -> either InvalidOperation or DivisionUndefined
1327 if not other:
1328 if self:
1329 return context._raise_error(InvalidOperation,
1330 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001331 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001332 return context._raise_error(DivisionUndefined,
1333 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001334
Facundo Batista353750c2007-09-13 18:13:15 +00001335 # other = +/-infinity -> remainder = self
1336 if other._isinfinity():
1337 ans = Decimal(self)
1338 return ans._fix(context)
1339
1340 # self = 0 -> remainder = self, with ideal exponent
1341 ideal_exponent = min(self._exp, other._exp)
1342 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001343 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001344 return ans._fix(context)
1345
1346 # catch most cases of large or small quotient
1347 expdiff = self.adjusted() - other.adjusted()
1348 if expdiff >= context.prec + 1:
1349 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001350 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001351 if expdiff <= -2:
1352 # expdiff <= -2 => abs(self/other) < 0.1
1353 ans = self._rescale(ideal_exponent, context.rounding)
1354 return ans._fix(context)
1355
1356 # adjust both arguments to have the same exponent, then divide
1357 op1 = _WorkRep(self)
1358 op2 = _WorkRep(other)
1359 if op1.exp >= op2.exp:
1360 op1.int *= 10**(op1.exp - op2.exp)
1361 else:
1362 op2.int *= 10**(op2.exp - op1.exp)
1363 q, r = divmod(op1.int, op2.int)
1364 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1365 # 10**ideal_exponent. Apply correction to ensure that
1366 # abs(remainder) <= abs(other)/2
1367 if 2*r + (q&1) > op2.int:
1368 r -= op2.int
1369 q += 1
1370
1371 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001372 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001373
1374 # result has same sign as self unless r is negative
1375 sign = self._sign
1376 if r < 0:
1377 sign = 1-sign
1378 r = -r
1379
Facundo Batista72bc54f2007-11-23 17:59:00 +00001380 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001381 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001382
1383 def __floordiv__(self, other, context=None):
1384 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001385 other = _convert_other(other)
1386 if other is NotImplemented:
1387 return other
1388
1389 if context is None:
1390 context = getcontext()
1391
1392 ans = self._check_nans(other, context)
1393 if ans:
1394 return ans
1395
1396 if self._isinfinity():
1397 if other._isinfinity():
1398 return context._raise_error(InvalidOperation, 'INF // INF')
1399 else:
1400 return Infsign[self._sign ^ other._sign]
1401
1402 if not other:
1403 if self:
1404 return context._raise_error(DivisionByZero, 'x // 0',
1405 self._sign ^ other._sign)
1406 else:
1407 return context._raise_error(DivisionUndefined, '0 // 0')
1408
1409 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001410
1411 def __rfloordiv__(self, other, context=None):
1412 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001413 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001414 if other is NotImplemented:
1415 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001416 return other.__floordiv__(self, context=context)
1417
1418 def __float__(self):
1419 """Float representation."""
1420 return float(str(self))
1421
1422 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001423 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001424 if self._is_special:
1425 if self._isnan():
1426 context = getcontext()
1427 return context._raise_error(InvalidContext)
1428 elif self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001429 raise OverflowError("Cannot convert infinity to long")
Facundo Batista353750c2007-09-13 18:13:15 +00001430 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001431 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001432 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001433 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001434 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001435
1436 def __long__(self):
1437 """Converts to a long.
1438
1439 Equivalent to long(int(self))
1440 """
1441 return long(self.__int__())
1442
Facundo Batista353750c2007-09-13 18:13:15 +00001443 def _fix_nan(self, context):
1444 """Decapitate the payload of a NaN to fit the context"""
1445 payload = self._int
1446
1447 # maximum length of payload is precision if _clamp=0,
1448 # precision-1 if _clamp=1.
1449 max_payload_len = context.prec - context._clamp
1450 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001451 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1452 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001453 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001454
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001455 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001456 """Round if it is necessary to keep self within prec precision.
1457
1458 Rounds and fixes the exponent. Does not raise on a sNaN.
1459
1460 Arguments:
1461 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001462 context - context used.
1463 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001464
Facundo Batista353750c2007-09-13 18:13:15 +00001465 if self._is_special:
1466 if self._isnan():
1467 # decapitate payload if necessary
1468 return self._fix_nan(context)
1469 else:
1470 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001471 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001472
Facundo Batista353750c2007-09-13 18:13:15 +00001473 # if self is zero then exponent should be between Etiny and
1474 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1475 Etiny = context.Etiny()
1476 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001477 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001478 exp_max = [context.Emax, Etop][context._clamp]
1479 new_exp = min(max(self._exp, Etiny), exp_max)
1480 if new_exp != self._exp:
1481 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001482 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001483 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001484 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001485
1486 # exp_min is the smallest allowable exponent of the result,
1487 # equal to max(self.adjusted()-context.prec+1, Etiny)
1488 exp_min = len(self._int) + self._exp - context.prec
1489 if exp_min > Etop:
1490 # overflow: exp_min > Etop iff self.adjusted() > Emax
1491 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001492 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001493 return context._raise_error(Overflow, 'above Emax', self._sign)
1494 self_is_subnormal = exp_min < Etiny
1495 if self_is_subnormal:
1496 context._raise_error(Subnormal)
1497 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001498
Facundo Batista353750c2007-09-13 18:13:15 +00001499 # round if self has too many digits
1500 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001501 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001502 digits = len(self._int) + self._exp - exp_min
1503 if digits < 0:
1504 self = _dec_from_triple(self._sign, '1', exp_min-1)
1505 digits = 0
1506 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1507 changed = this_function(digits)
1508 coeff = self._int[:digits] or '0'
1509 if changed == 1:
1510 coeff = str(int(coeff)+1)
1511 ans = _dec_from_triple(self._sign, coeff, exp_min)
1512
1513 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001514 context._raise_error(Inexact)
1515 if self_is_subnormal:
1516 context._raise_error(Underflow)
1517 if not ans:
1518 # raise Clamped on underflow to 0
1519 context._raise_error(Clamped)
1520 elif len(ans._int) == context.prec+1:
1521 # we get here only if rescaling rounds the
1522 # cofficient up to exactly 10**context.prec
1523 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001524 ans = _dec_from_triple(ans._sign,
1525 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001526 else:
1527 # Inexact and Rounded have already been raised
1528 ans = context._raise_error(Overflow, 'above Emax',
1529 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001530 return ans
1531
Facundo Batista353750c2007-09-13 18:13:15 +00001532 # fold down if _clamp == 1 and self has too few digits
1533 if context._clamp == 1 and self._exp > Etop:
1534 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001535 self_padded = self._int + '0'*(self._exp - Etop)
1536 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001537
Facundo Batista353750c2007-09-13 18:13:15 +00001538 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001539 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001540
1541 _pick_rounding_function = {}
1542
Facundo Batista353750c2007-09-13 18:13:15 +00001543 # for each of the rounding functions below:
1544 # self is a finite, nonzero Decimal
1545 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001546 #
1547 # each function returns either -1, 0, or 1, as follows:
1548 # 1 indicates that self should be rounded up (away from zero)
1549 # 0 indicates that self should be truncated, and that all the
1550 # digits to be truncated are zeros (so the value is unchanged)
1551 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001552
1553 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001554 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001555 if _all_zeros(self._int, prec):
1556 return 0
1557 else:
1558 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001559
Facundo Batista353750c2007-09-13 18:13:15 +00001560 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001561 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001562 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001563
Facundo Batista353750c2007-09-13 18:13:15 +00001564 def _round_half_up(self, prec):
1565 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001566 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001567 return 1
1568 elif _all_zeros(self._int, prec):
1569 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001570 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001571 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001572
1573 def _round_half_down(self, prec):
1574 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001575 if _exact_half(self._int, prec):
1576 return -1
1577 else:
1578 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001579
1580 def _round_half_even(self, prec):
1581 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001582 if _exact_half(self._int, prec) and \
1583 (prec == 0 or self._int[prec-1] in '02468'):
1584 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001585 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001586 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001587
1588 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001589 """Rounds up (not away from 0 if negative.)"""
1590 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001591 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001592 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001593 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001594
Facundo Batista353750c2007-09-13 18:13:15 +00001595 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001596 """Rounds down (not towards 0 if negative)"""
1597 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001598 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001599 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001600 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001601
Facundo Batista353750c2007-09-13 18:13:15 +00001602 def _round_05up(self, prec):
1603 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001604 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001605 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001606 else:
1607 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001608
Facundo Batista353750c2007-09-13 18:13:15 +00001609 def fma(self, other, third, context=None):
1610 """Fused multiply-add.
1611
1612 Returns self*other+third with no rounding of the intermediate
1613 product self*other.
1614
1615 self and other are multiplied together, with no rounding of
1616 the result. The third operand is then added to the result,
1617 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001618 """
Facundo Batista353750c2007-09-13 18:13:15 +00001619
1620 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001621
1622 # compute product; raise InvalidOperation if either operand is
1623 # a signaling NaN or if the product is zero times infinity.
1624 if self._is_special or other._is_special:
1625 if context is None:
1626 context = getcontext()
1627 if self._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001628 return context._raise_error(InvalidOperation, 'sNaN', self)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001629 if other._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001630 return context._raise_error(InvalidOperation, 'sNaN', other)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001631 if self._exp == 'n':
1632 product = self
1633 elif other._exp == 'n':
1634 product = other
1635 elif self._exp == 'F':
1636 if not other:
1637 return context._raise_error(InvalidOperation,
1638 'INF * 0 in fma')
1639 product = Infsign[self._sign ^ other._sign]
1640 elif other._exp == 'F':
1641 if not self:
1642 return context._raise_error(InvalidOperation,
1643 '0 * INF in fma')
1644 product = Infsign[self._sign ^ other._sign]
1645 else:
1646 product = _dec_from_triple(self._sign ^ other._sign,
1647 str(int(self._int) * int(other._int)),
1648 self._exp + other._exp)
1649
Facundo Batista353750c2007-09-13 18:13:15 +00001650 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001651 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001652
Facundo Batista353750c2007-09-13 18:13:15 +00001653 def _power_modulo(self, other, modulo, context=None):
1654 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001655
Facundo Batista353750c2007-09-13 18:13:15 +00001656 # if can't convert other and modulo to Decimal, raise
1657 # TypeError; there's no point returning NotImplemented (no
1658 # equivalent of __rpow__ for three argument pow)
1659 other = _convert_other(other, raiseit=True)
1660 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001661
Facundo Batista353750c2007-09-13 18:13:15 +00001662 if context is None:
1663 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001664
Facundo Batista353750c2007-09-13 18:13:15 +00001665 # deal with NaNs: if there are any sNaNs then first one wins,
1666 # (i.e. behaviour for NaNs is identical to that of fma)
1667 self_is_nan = self._isnan()
1668 other_is_nan = other._isnan()
1669 modulo_is_nan = modulo._isnan()
1670 if self_is_nan or other_is_nan or modulo_is_nan:
1671 if self_is_nan == 2:
1672 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001673 self)
Facundo Batista353750c2007-09-13 18:13:15 +00001674 if other_is_nan == 2:
1675 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001676 other)
Facundo Batista353750c2007-09-13 18:13:15 +00001677 if modulo_is_nan == 2:
1678 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001679 modulo)
Facundo Batista353750c2007-09-13 18:13:15 +00001680 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001681 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001682 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001683 return other._fix_nan(context)
1684 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001685
Facundo Batista353750c2007-09-13 18:13:15 +00001686 # check inputs: we apply same restrictions as Python's pow()
1687 if not (self._isinteger() and
1688 other._isinteger() and
1689 modulo._isinteger()):
1690 return context._raise_error(InvalidOperation,
1691 'pow() 3rd argument not allowed '
1692 'unless all arguments are integers')
1693 if other < 0:
1694 return context._raise_error(InvalidOperation,
1695 'pow() 2nd argument cannot be '
1696 'negative when 3rd argument specified')
1697 if not modulo:
1698 return context._raise_error(InvalidOperation,
1699 'pow() 3rd argument cannot be 0')
1700
1701 # additional restriction for decimal: the modulus must be less
1702 # than 10**prec in absolute value
1703 if modulo.adjusted() >= context.prec:
1704 return context._raise_error(InvalidOperation,
1705 'insufficient precision: pow() 3rd '
1706 'argument must not have more than '
1707 'precision digits')
1708
1709 # define 0**0 == NaN, for consistency with two-argument pow
1710 # (even though it hurts!)
1711 if not other and not self:
1712 return context._raise_error(InvalidOperation,
1713 'at least one of pow() 1st argument '
1714 'and 2nd argument must be nonzero ;'
1715 '0**0 is not defined')
1716
1717 # compute sign of result
1718 if other._iseven():
1719 sign = 0
1720 else:
1721 sign = self._sign
1722
1723 # convert modulo to a Python integer, and self and other to
1724 # Decimal integers (i.e. force their exponents to be >= 0)
1725 modulo = abs(int(modulo))
1726 base = _WorkRep(self.to_integral_value())
1727 exponent = _WorkRep(other.to_integral_value())
1728
1729 # compute result using integer pow()
1730 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1731 for i in xrange(exponent.exp):
1732 base = pow(base, 10, modulo)
1733 base = pow(base, exponent.int, modulo)
1734
Facundo Batista72bc54f2007-11-23 17:59:00 +00001735 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001736
1737 def _power_exact(self, other, p):
1738 """Attempt to compute self**other exactly.
1739
1740 Given Decimals self and other and an integer p, attempt to
1741 compute an exact result for the power self**other, with p
1742 digits of precision. Return None if self**other is not
1743 exactly representable in p digits.
1744
1745 Assumes that elimination of special cases has already been
1746 performed: self and other must both be nonspecial; self must
1747 be positive and not numerically equal to 1; other must be
1748 nonzero. For efficiency, other._exp should not be too large,
1749 so that 10**abs(other._exp) is a feasible calculation."""
1750
1751 # In the comments below, we write x for the value of self and
1752 # y for the value of other. Write x = xc*10**xe and y =
1753 # yc*10**ye.
1754
1755 # The main purpose of this method is to identify the *failure*
1756 # of x**y to be exactly representable with as little effort as
1757 # possible. So we look for cheap and easy tests that
1758 # eliminate the possibility of x**y being exact. Only if all
1759 # these tests are passed do we go on to actually compute x**y.
1760
1761 # Here's the main idea. First normalize both x and y. We
1762 # express y as a rational m/n, with m and n relatively prime
1763 # and n>0. Then for x**y to be exactly representable (at
1764 # *any* precision), xc must be the nth power of a positive
1765 # integer and xe must be divisible by n. If m is negative
1766 # then additionally xc must be a power of either 2 or 5, hence
1767 # a power of 2**n or 5**n.
1768 #
1769 # There's a limit to how small |y| can be: if y=m/n as above
1770 # then:
1771 #
1772 # (1) if xc != 1 then for the result to be representable we
1773 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1774 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1775 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1776 # representable.
1777 #
1778 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1779 # |y| < 1/|xe| then the result is not representable.
1780 #
1781 # Note that since x is not equal to 1, at least one of (1) and
1782 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1783 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1784 #
1785 # There's also a limit to how large y can be, at least if it's
1786 # positive: the normalized result will have coefficient xc**y,
1787 # so if it's representable then xc**y < 10**p, and y <
1788 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1789 # not exactly representable.
1790
1791 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1792 # so |y| < 1/xe and the result is not representable.
1793 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1794 # < 1/nbits(xc).
1795
1796 x = _WorkRep(self)
1797 xc, xe = x.int, x.exp
1798 while xc % 10 == 0:
1799 xc //= 10
1800 xe += 1
1801
1802 y = _WorkRep(other)
1803 yc, ye = y.int, y.exp
1804 while yc % 10 == 0:
1805 yc //= 10
1806 ye += 1
1807
1808 # case where xc == 1: result is 10**(xe*y), with xe*y
1809 # required to be an integer
1810 if xc == 1:
1811 if ye >= 0:
1812 exponent = xe*yc*10**ye
1813 else:
1814 exponent, remainder = divmod(xe*yc, 10**-ye)
1815 if remainder:
1816 return None
1817 if y.sign == 1:
1818 exponent = -exponent
1819 # if other is a nonnegative integer, use ideal exponent
1820 if other._isinteger() and other._sign == 0:
1821 ideal_exponent = self._exp*int(other)
1822 zeros = min(exponent-ideal_exponent, p-1)
1823 else:
1824 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001825 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001826
1827 # case where y is negative: xc must be either a power
1828 # of 2 or a power of 5.
1829 if y.sign == 1:
1830 last_digit = xc % 10
1831 if last_digit in (2,4,6,8):
1832 # quick test for power of 2
1833 if xc & -xc != xc:
1834 return None
1835 # now xc is a power of 2; e is its exponent
1836 e = _nbits(xc)-1
1837 # find e*y and xe*y; both must be integers
1838 if ye >= 0:
1839 y_as_int = yc*10**ye
1840 e = e*y_as_int
1841 xe = xe*y_as_int
1842 else:
1843 ten_pow = 10**-ye
1844 e, remainder = divmod(e*yc, ten_pow)
1845 if remainder:
1846 return None
1847 xe, remainder = divmod(xe*yc, ten_pow)
1848 if remainder:
1849 return None
1850
1851 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1852 return None
1853 xc = 5**e
1854
1855 elif last_digit == 5:
1856 # e >= log_5(xc) if xc is a power of 5; we have
1857 # equality all the way up to xc=5**2658
1858 e = _nbits(xc)*28//65
1859 xc, remainder = divmod(5**e, xc)
1860 if remainder:
1861 return None
1862 while xc % 5 == 0:
1863 xc //= 5
1864 e -= 1
1865 if ye >= 0:
1866 y_as_integer = yc*10**ye
1867 e = e*y_as_integer
1868 xe = xe*y_as_integer
1869 else:
1870 ten_pow = 10**-ye
1871 e, remainder = divmod(e*yc, ten_pow)
1872 if remainder:
1873 return None
1874 xe, remainder = divmod(xe*yc, ten_pow)
1875 if remainder:
1876 return None
1877 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1878 return None
1879 xc = 2**e
1880 else:
1881 return None
1882
1883 if xc >= 10**p:
1884 return None
1885 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00001886 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00001887
1888 # now y is positive; find m and n such that y = m/n
1889 if ye >= 0:
1890 m, n = yc*10**ye, 1
1891 else:
1892 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1893 return None
1894 xc_bits = _nbits(xc)
1895 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1896 return None
1897 m, n = yc, 10**(-ye)
1898 while m % 2 == n % 2 == 0:
1899 m //= 2
1900 n //= 2
1901 while m % 5 == n % 5 == 0:
1902 m //= 5
1903 n //= 5
1904
1905 # compute nth root of xc*10**xe
1906 if n > 1:
1907 # if 1 < xc < 2**n then xc isn't an nth power
1908 if xc != 1 and xc_bits <= n:
1909 return None
1910
1911 xe, rem = divmod(xe, n)
1912 if rem != 0:
1913 return None
1914
1915 # compute nth root of xc using Newton's method
1916 a = 1L << -(-_nbits(xc)//n) # initial estimate
1917 while True:
1918 q, r = divmod(xc, a**(n-1))
1919 if a <= q:
1920 break
1921 else:
1922 a = (a*(n-1) + q)//n
1923 if not (a == q and r == 0):
1924 return None
1925 xc = a
1926
1927 # now xc*10**xe is the nth root of the original xc*10**xe
1928 # compute mth power of xc*10**xe
1929
1930 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1931 # 10**p and the result is not representable.
1932 if xc > 1 and m > p*100//_log10_lb(xc):
1933 return None
1934 xc = xc**m
1935 xe *= m
1936 if xc > 10**p:
1937 return None
1938
1939 # by this point the result *is* exactly representable
1940 # adjust the exponent to get as close as possible to the ideal
1941 # exponent, if necessary
1942 str_xc = str(xc)
1943 if other._isinteger() and other._sign == 0:
1944 ideal_exponent = self._exp*int(other)
1945 zeros = min(xe-ideal_exponent, p-len(str_xc))
1946 else:
1947 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001948 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001949
1950 def __pow__(self, other, modulo=None, context=None):
1951 """Return self ** other [ % modulo].
1952
1953 With two arguments, compute self**other.
1954
1955 With three arguments, compute (self**other) % modulo. For the
1956 three argument form, the following restrictions on the
1957 arguments hold:
1958
1959 - all three arguments must be integral
1960 - other must be nonnegative
1961 - either self or other (or both) must be nonzero
1962 - modulo must be nonzero and must have at most p digits,
1963 where p is the context precision.
1964
1965 If any of these restrictions is violated the InvalidOperation
1966 flag is raised.
1967
1968 The result of pow(self, other, modulo) is identical to the
1969 result that would be obtained by computing (self**other) %
1970 modulo with unbounded precision, but is computed more
1971 efficiently. It is always exact.
1972 """
1973
1974 if modulo is not None:
1975 return self._power_modulo(other, modulo, context)
1976
1977 other = _convert_other(other)
1978 if other is NotImplemented:
1979 return other
1980
1981 if context is None:
1982 context = getcontext()
1983
1984 # either argument is a NaN => result is NaN
1985 ans = self._check_nans(other, context)
1986 if ans:
1987 return ans
1988
1989 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1990 if not other:
1991 if not self:
1992 return context._raise_error(InvalidOperation, '0 ** 0')
1993 else:
1994 return Dec_p1
1995
1996 # result has sign 1 iff self._sign is 1 and other is an odd integer
1997 result_sign = 0
1998 if self._sign == 1:
1999 if other._isinteger():
2000 if not other._iseven():
2001 result_sign = 1
2002 else:
2003 # -ve**noninteger = NaN
2004 # (-0)**noninteger = 0**noninteger
2005 if self:
2006 return context._raise_error(InvalidOperation,
2007 'x ** y with x negative and y not an integer')
2008 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002009 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002010
2011 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2012 if not self:
2013 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002014 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002015 else:
2016 return Infsign[result_sign]
2017
2018 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002019 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002020 if other._sign == 0:
2021 return Infsign[result_sign]
2022 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002023 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002024
Facundo Batista353750c2007-09-13 18:13:15 +00002025 # 1**other = 1, but the choice of exponent and the flags
2026 # depend on the exponent of self, and on whether other is a
2027 # positive integer, a negative integer, or neither
2028 if self == Dec_p1:
2029 if other._isinteger():
2030 # exp = max(self._exp*max(int(other), 0),
2031 # 1-context.prec) but evaluating int(other) directly
2032 # is dangerous until we know other is small (other
2033 # could be 1e999999999)
2034 if other._sign == 1:
2035 multiplier = 0
2036 elif other > context.prec:
2037 multiplier = context.prec
2038 else:
2039 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002040
Facundo Batista353750c2007-09-13 18:13:15 +00002041 exp = self._exp * multiplier
2042 if exp < 1-context.prec:
2043 exp = 1-context.prec
2044 context._raise_error(Rounded)
2045 else:
2046 context._raise_error(Inexact)
2047 context._raise_error(Rounded)
2048 exp = 1-context.prec
2049
Facundo Batista72bc54f2007-11-23 17:59:00 +00002050 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002051
2052 # compute adjusted exponent of self
2053 self_adj = self.adjusted()
2054
2055 # self ** infinity is infinity if self > 1, 0 if self < 1
2056 # self ** -infinity is infinity if self < 1, 0 if self > 1
2057 if other._isinfinity():
2058 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002059 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002060 else:
2061 return Infsign[result_sign]
2062
2063 # from here on, the result always goes through the call
2064 # to _fix at the end of this function.
2065 ans = None
2066
2067 # crude test to catch cases of extreme overflow/underflow. If
2068 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2069 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2070 # self**other >= 10**(Emax+1), so overflow occurs. The test
2071 # for underflow is similar.
2072 bound = self._log10_exp_bound() + other.adjusted()
2073 if (self_adj >= 0) == (other._sign == 0):
2074 # self > 1 and other +ve, or self < 1 and other -ve
2075 # possibility of overflow
2076 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002077 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002078 else:
2079 # self > 1 and other -ve, or self < 1 and other +ve
2080 # possibility of underflow to 0
2081 Etiny = context.Etiny()
2082 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002083 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002084
2085 # try for an exact result with precision +1
2086 if ans is None:
2087 ans = self._power_exact(other, context.prec + 1)
2088 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002089 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002090
2091 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2092 if ans is None:
2093 p = context.prec
2094 x = _WorkRep(self)
2095 xc, xe = x.int, x.exp
2096 y = _WorkRep(other)
2097 yc, ye = y.int, y.exp
2098 if y.sign == 1:
2099 yc = -yc
2100
2101 # compute correctly rounded result: start with precision +3,
2102 # then increase precision until result is unambiguously roundable
2103 extra = 3
2104 while True:
2105 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2106 if coeff % (5*10**(len(str(coeff))-p-1)):
2107 break
2108 extra += 3
2109
Facundo Batista72bc54f2007-11-23 17:59:00 +00002110 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002111
2112 # the specification says that for non-integer other we need to
2113 # raise Inexact, even when the result is actually exact. In
2114 # the same way, we need to raise Underflow here if the result
2115 # is subnormal. (The call to _fix will take care of raising
2116 # Rounded and Subnormal, as usual.)
2117 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002118 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002119 # pad with zeros up to length context.prec+1 if necessary
2120 if len(ans._int) <= context.prec:
2121 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002122 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2123 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002124 if ans.adjusted() < context.Emin:
2125 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002126
Facundo Batista353750c2007-09-13 18:13:15 +00002127 # unlike exp, ln and log10, the power function respects the
2128 # rounding mode; no need to use ROUND_HALF_EVEN here
2129 ans = ans._fix(context)
2130 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002131
2132 def __rpow__(self, other, context=None):
2133 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002134 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002135 if other is NotImplemented:
2136 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002137 return other.__pow__(self, context=context)
2138
2139 def normalize(self, context=None):
2140 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002141
Facundo Batista353750c2007-09-13 18:13:15 +00002142 if context is None:
2143 context = getcontext()
2144
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002145 if self._is_special:
2146 ans = self._check_nans(context=context)
2147 if ans:
2148 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002149
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002150 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002151 if dup._isinfinity():
2152 return dup
2153
2154 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002155 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002156 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002157 end = len(dup._int)
2158 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002159 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002160 exp += 1
2161 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002162 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002163
Facundo Batistabd2fe832007-09-13 18:42:09 +00002164 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002165 """Quantize self so its exponent is the same as that of exp.
2166
2167 Similar to self._rescale(exp._exp) but with error checking.
2168 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002169 exp = _convert_other(exp, raiseit=True)
2170
Facundo Batista353750c2007-09-13 18:13:15 +00002171 if context is None:
2172 context = getcontext()
2173 if rounding is None:
2174 rounding = context.rounding
2175
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002176 if self._is_special or exp._is_special:
2177 ans = self._check_nans(exp, context)
2178 if ans:
2179 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002180
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002181 if exp._isinfinity() or self._isinfinity():
2182 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002183 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002184 return context._raise_error(InvalidOperation,
2185 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002186
Facundo Batistabd2fe832007-09-13 18:42:09 +00002187 # if we're not watching exponents, do a simple rescale
2188 if not watchexp:
2189 ans = self._rescale(exp._exp, rounding)
2190 # raise Inexact and Rounded where appropriate
2191 if ans._exp > self._exp:
2192 context._raise_error(Rounded)
2193 if ans != self:
2194 context._raise_error(Inexact)
2195 return ans
2196
Facundo Batista353750c2007-09-13 18:13:15 +00002197 # exp._exp should be between Etiny and Emax
2198 if not (context.Etiny() <= exp._exp <= context.Emax):
2199 return context._raise_error(InvalidOperation,
2200 'target exponent out of bounds in quantize')
2201
2202 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002203 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002204 return ans._fix(context)
2205
2206 self_adjusted = self.adjusted()
2207 if self_adjusted > context.Emax:
2208 return context._raise_error(InvalidOperation,
2209 'exponent of quantize result too large for current context')
2210 if self_adjusted - exp._exp + 1 > context.prec:
2211 return context._raise_error(InvalidOperation,
2212 'quantize result has too many digits for current context')
2213
2214 ans = self._rescale(exp._exp, rounding)
2215 if ans.adjusted() > context.Emax:
2216 return context._raise_error(InvalidOperation,
2217 'exponent of quantize result too large for current context')
2218 if len(ans._int) > context.prec:
2219 return context._raise_error(InvalidOperation,
2220 'quantize result has too many digits for current context')
2221
2222 # raise appropriate flags
2223 if ans._exp > self._exp:
2224 context._raise_error(Rounded)
2225 if ans != self:
2226 context._raise_error(Inexact)
2227 if ans and ans.adjusted() < context.Emin:
2228 context._raise_error(Subnormal)
2229
2230 # call to fix takes care of any necessary folddown
2231 ans = ans._fix(context)
2232 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002233
2234 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002235 """Return True if self and other have the same exponent; otherwise
2236 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002237
Facundo Batista1a191df2007-10-02 17:01:24 +00002238 If either operand is a special value, the following rules are used:
2239 * return True if both operands are infinities
2240 * return True if both operands are NaNs
2241 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002242 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002243 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002244 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002245 return (self.is_nan() and other.is_nan() or
2246 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002247 return self._exp == other._exp
2248
Facundo Batista353750c2007-09-13 18:13:15 +00002249 def _rescale(self, exp, rounding):
2250 """Rescale self so that the exponent is exp, either by padding with zeros
2251 or by truncating digits, using the given rounding mode.
2252
2253 Specials are returned without change. This operation is
2254 quiet: it raises no flags, and uses no information from the
2255 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002256
2257 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002258 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002259 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002260 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002261 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002262 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002263 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002264
Facundo Batista353750c2007-09-13 18:13:15 +00002265 if self._exp >= exp:
2266 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002267 return _dec_from_triple(self._sign,
2268 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002269
Facundo Batista353750c2007-09-13 18:13:15 +00002270 # too many digits; round and lose data. If self.adjusted() <
2271 # exp-1, replace self by 10**(exp-1) before rounding
2272 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002273 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002274 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002275 digits = 0
2276 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002277 changed = this_function(digits)
2278 coeff = self._int[:digits] or '0'
2279 if changed == 1:
2280 coeff = str(int(coeff)+1)
2281 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002282
Facundo Batista353750c2007-09-13 18:13:15 +00002283 def to_integral_exact(self, rounding=None, context=None):
2284 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002285
Facundo Batista353750c2007-09-13 18:13:15 +00002286 If no rounding mode is specified, take the rounding mode from
2287 the context. This method raises the Rounded and Inexact flags
2288 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002289
Facundo Batista353750c2007-09-13 18:13:15 +00002290 See also: to_integral_value, which does exactly the same as
2291 this method except that it doesn't raise Inexact or Rounded.
2292 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002293 if self._is_special:
2294 ans = self._check_nans(context=context)
2295 if ans:
2296 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002297 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002298 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002299 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002300 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002301 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002302 if context is None:
2303 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002304 if rounding is None:
2305 rounding = context.rounding
2306 context._raise_error(Rounded)
2307 ans = self._rescale(0, rounding)
2308 if ans != self:
2309 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002310 return ans
2311
Facundo Batista353750c2007-09-13 18:13:15 +00002312 def to_integral_value(self, rounding=None, context=None):
2313 """Rounds to the nearest integer, without raising inexact, rounded."""
2314 if context is None:
2315 context = getcontext()
2316 if rounding is None:
2317 rounding = context.rounding
2318 if self._is_special:
2319 ans = self._check_nans(context=context)
2320 if ans:
2321 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002322 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002323 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002324 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002325 else:
2326 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002327
Facundo Batista353750c2007-09-13 18:13:15 +00002328 # the method name changed, but we provide also the old one, for compatibility
2329 to_integral = to_integral_value
2330
2331 def sqrt(self, context=None):
2332 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002333 if self._is_special:
2334 ans = self._check_nans(context=context)
2335 if ans:
2336 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002337
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002338 if self._isinfinity() and self._sign == 0:
2339 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002340
2341 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002342 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002343 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002344 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002345
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002346 if context is None:
2347 context = getcontext()
2348
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002349 if self._sign == 1:
2350 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2351
Facundo Batista353750c2007-09-13 18:13:15 +00002352 # At this point self represents a positive number. Let p be
2353 # the desired precision and express self in the form c*100**e
2354 # with c a positive real number and e an integer, c and e
2355 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2356 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2357 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2358 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2359 # the closest integer to sqrt(c) with the even integer chosen
2360 # in the case of a tie.
2361 #
2362 # To ensure correct rounding in all cases, we use the
2363 # following trick: we compute the square root to an extra
2364 # place (precision p+1 instead of precision p), rounding down.
2365 # Then, if the result is inexact and its last digit is 0 or 5,
2366 # we increase the last digit to 1 or 6 respectively; if it's
2367 # exact we leave the last digit alone. Now the final round to
2368 # p places (or fewer in the case of underflow) will round
2369 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002370
Facundo Batista353750c2007-09-13 18:13:15 +00002371 # use an extra digit of precision
2372 prec = context.prec+1
2373
2374 # write argument in the form c*100**e where e = self._exp//2
2375 # is the 'ideal' exponent, to be used if the square root is
2376 # exactly representable. l is the number of 'digits' of c in
2377 # base 100, so that 100**(l-1) <= c < 100**l.
2378 op = _WorkRep(self)
2379 e = op.exp >> 1
2380 if op.exp & 1:
2381 c = op.int * 10
2382 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002383 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002384 c = op.int
2385 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002386
Facundo Batista353750c2007-09-13 18:13:15 +00002387 # rescale so that c has exactly prec base 100 'digits'
2388 shift = prec-l
2389 if shift >= 0:
2390 c *= 100**shift
2391 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002392 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002393 c, remainder = divmod(c, 100**-shift)
2394 exact = not remainder
2395 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002396
Facundo Batista353750c2007-09-13 18:13:15 +00002397 # find n = floor(sqrt(c)) using Newton's method
2398 n = 10**prec
2399 while True:
2400 q = c//n
2401 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002402 break
Facundo Batista353750c2007-09-13 18:13:15 +00002403 else:
2404 n = n + q >> 1
2405 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002406
Facundo Batista353750c2007-09-13 18:13:15 +00002407 if exact:
2408 # result is exact; rescale to use ideal exponent e
2409 if shift >= 0:
2410 # assert n % 10**shift == 0
2411 n //= 10**shift
2412 else:
2413 n *= 10**-shift
2414 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002415 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002416 # result is not exact; fix last digit as described above
2417 if n % 5 == 0:
2418 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002419
Facundo Batista72bc54f2007-11-23 17:59:00 +00002420 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002421
Facundo Batista353750c2007-09-13 18:13:15 +00002422 # round, and fit to current context
2423 context = context._shallow_copy()
2424 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002425 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002426 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002427
Facundo Batista353750c2007-09-13 18:13:15 +00002428 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002429
2430 def max(self, other, context=None):
2431 """Returns the larger value.
2432
Facundo Batista353750c2007-09-13 18:13:15 +00002433 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002434 NaN (and signals if one is sNaN). Also rounds.
2435 """
Facundo Batista353750c2007-09-13 18:13:15 +00002436 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002437
Facundo Batista6c398da2007-09-17 17:30:13 +00002438 if context is None:
2439 context = getcontext()
2440
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002441 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002442 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002443 # number is always returned
2444 sn = self._isnan()
2445 on = other._isnan()
2446 if sn or on:
2447 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002448 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002449 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002450 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002451 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002452
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002453 c = self.__cmp__(other)
2454 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002455 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002456 # then an ordering is applied:
2457 #
Facundo Batista59c58842007-04-10 12:58:45 +00002458 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002459 # positive sign and min returns the operand with the negative sign
2460 #
Facundo Batista59c58842007-04-10 12:58:45 +00002461 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002462 # the result. This is exactly the ordering used in compare_total.
2463 c = self.compare_total(other)
2464
2465 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002466 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002467 else:
2468 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002469
Facundo Batistae64acfa2007-12-17 14:18:42 +00002470 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002471
2472 def min(self, other, context=None):
2473 """Returns the smaller value.
2474
Facundo Batista59c58842007-04-10 12:58:45 +00002475 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002476 NaN (and signals if one is sNaN). Also rounds.
2477 """
Facundo Batista353750c2007-09-13 18:13:15 +00002478 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002479
Facundo Batista6c398da2007-09-17 17:30:13 +00002480 if context is None:
2481 context = getcontext()
2482
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002483 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002484 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002485 # number is always returned
2486 sn = self._isnan()
2487 on = other._isnan()
2488 if sn or on:
2489 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002490 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002491 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002492 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002493 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002494
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002495 c = self.__cmp__(other)
2496 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002497 c = self.compare_total(other)
2498
2499 if c == -1:
2500 ans = self
2501 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002502 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002503
Facundo Batistae64acfa2007-12-17 14:18:42 +00002504 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002505
2506 def _isinteger(self):
2507 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002508 if self._is_special:
2509 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002510 if self._exp >= 0:
2511 return True
2512 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002513 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002514
2515 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002516 """Returns True if self is even. Assumes self is an integer."""
2517 if not self or self._exp > 0:
2518 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002519 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002520
2521 def adjusted(self):
2522 """Return the adjusted exponent of self"""
2523 try:
2524 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002525 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002526 except TypeError:
2527 return 0
2528
Facundo Batista353750c2007-09-13 18:13:15 +00002529 def canonical(self, context=None):
2530 """Returns the same Decimal object.
2531
2532 As we do not have different encodings for the same number, the
2533 received object already is in its canonical form.
2534 """
2535 return self
2536
2537 def compare_signal(self, other, context=None):
2538 """Compares self to the other operand numerically.
2539
2540 It's pretty much like compare(), but all NaNs signal, with signaling
2541 NaNs taking precedence over quiet NaNs.
2542 """
2543 if context is None:
2544 context = getcontext()
2545
2546 self_is_nan = self._isnan()
2547 other_is_nan = other._isnan()
2548 if self_is_nan == 2:
2549 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002550 self)
Facundo Batista353750c2007-09-13 18:13:15 +00002551 if other_is_nan == 2:
2552 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002553 other)
Facundo Batista353750c2007-09-13 18:13:15 +00002554 if self_is_nan:
2555 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002556 self)
Facundo Batista353750c2007-09-13 18:13:15 +00002557 if other_is_nan:
2558 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002559 other)
Facundo Batista353750c2007-09-13 18:13:15 +00002560 return self.compare(other, context=context)
2561
2562 def compare_total(self, other):
2563 """Compares self to other using the abstract representations.
2564
2565 This is not like the standard compare, which use their numerical
2566 value. Note that a total ordering is defined for all possible abstract
2567 representations.
2568 """
2569 # if one is negative and the other is positive, it's easy
2570 if self._sign and not other._sign:
2571 return Dec_n1
2572 if not self._sign and other._sign:
2573 return Dec_p1
2574 sign = self._sign
2575
2576 # let's handle both NaN types
2577 self_nan = self._isnan()
2578 other_nan = other._isnan()
2579 if self_nan or other_nan:
2580 if self_nan == other_nan:
2581 if self._int < other._int:
2582 if sign:
2583 return Dec_p1
2584 else:
2585 return Dec_n1
2586 if self._int > other._int:
2587 if sign:
2588 return Dec_n1
2589 else:
2590 return Dec_p1
2591 return Dec_0
2592
2593 if sign:
2594 if self_nan == 1:
2595 return Dec_n1
2596 if other_nan == 1:
2597 return Dec_p1
2598 if self_nan == 2:
2599 return Dec_n1
2600 if other_nan == 2:
2601 return Dec_p1
2602 else:
2603 if self_nan == 1:
2604 return Dec_p1
2605 if other_nan == 1:
2606 return Dec_n1
2607 if self_nan == 2:
2608 return Dec_p1
2609 if other_nan == 2:
2610 return Dec_n1
2611
2612 if self < other:
2613 return Dec_n1
2614 if self > other:
2615 return Dec_p1
2616
2617 if self._exp < other._exp:
2618 if sign:
2619 return Dec_p1
2620 else:
2621 return Dec_n1
2622 if self._exp > other._exp:
2623 if sign:
2624 return Dec_n1
2625 else:
2626 return Dec_p1
2627 return Dec_0
2628
2629
2630 def compare_total_mag(self, other):
2631 """Compares self to other using abstract repr., ignoring sign.
2632
2633 Like compare_total, but with operand's sign ignored and assumed to be 0.
2634 """
2635 s = self.copy_abs()
2636 o = other.copy_abs()
2637 return s.compare_total(o)
2638
2639 def copy_abs(self):
2640 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002641 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002642
2643 def copy_negate(self):
2644 """Returns a copy with the sign inverted."""
2645 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002646 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002647 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002648 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002649
2650 def copy_sign(self, other):
2651 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002652 return _dec_from_triple(other._sign, self._int,
2653 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002654
2655 def exp(self, context=None):
2656 """Returns e ** self."""
2657
2658 if context is None:
2659 context = getcontext()
2660
2661 # exp(NaN) = NaN
2662 ans = self._check_nans(context=context)
2663 if ans:
2664 return ans
2665
2666 # exp(-Infinity) = 0
2667 if self._isinfinity() == -1:
2668 return Dec_0
2669
2670 # exp(0) = 1
2671 if not self:
2672 return Dec_p1
2673
2674 # exp(Infinity) = Infinity
2675 if self._isinfinity() == 1:
2676 return Decimal(self)
2677
2678 # the result is now guaranteed to be inexact (the true
2679 # mathematical result is transcendental). There's no need to
2680 # raise Rounded and Inexact here---they'll always be raised as
2681 # a result of the call to _fix.
2682 p = context.prec
2683 adj = self.adjusted()
2684
2685 # we only need to do any computation for quite a small range
2686 # of adjusted exponents---for example, -29 <= adj <= 10 for
2687 # the default context. For smaller exponent the result is
2688 # indistinguishable from 1 at the given precision, while for
2689 # larger exponent the result either overflows or underflows.
2690 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2691 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002692 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002693 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2694 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002695 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002696 elif self._sign == 0 and adj < -p:
2697 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002698 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002699 elif self._sign == 1 and adj < -p-1:
2700 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002701 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002702 # general case
2703 else:
2704 op = _WorkRep(self)
2705 c, e = op.int, op.exp
2706 if op.sign == 1:
2707 c = -c
2708
2709 # compute correctly rounded result: increase precision by
2710 # 3 digits at a time until we get an unambiguously
2711 # roundable result
2712 extra = 3
2713 while True:
2714 coeff, exp = _dexp(c, e, p+extra)
2715 if coeff % (5*10**(len(str(coeff))-p-1)):
2716 break
2717 extra += 3
2718
Facundo Batista72bc54f2007-11-23 17:59:00 +00002719 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002720
2721 # at this stage, ans should round correctly with *any*
2722 # rounding mode, not just with ROUND_HALF_EVEN
2723 context = context._shallow_copy()
2724 rounding = context._set_rounding(ROUND_HALF_EVEN)
2725 ans = ans._fix(context)
2726 context.rounding = rounding
2727
2728 return ans
2729
2730 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002731 """Return True if self is canonical; otherwise return False.
2732
2733 Currently, the encoding of a Decimal instance is always
2734 canonical, so this method returns True for any Decimal.
2735 """
2736 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002737
2738 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002739 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002740
Facundo Batista1a191df2007-10-02 17:01:24 +00002741 A Decimal instance is considered finite if it is neither
2742 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002743 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002744 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002745
2746 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002747 """Return True if self is infinite; otherwise return False."""
2748 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002749
2750 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002751 """Return True if self is a qNaN or sNaN; otherwise return False."""
2752 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002753
2754 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002755 """Return True if self is a normal number; otherwise return False."""
2756 if self._is_special or not self:
2757 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002758 if context is None:
2759 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002760 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002761
2762 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002763 """Return True if self is a quiet NaN; otherwise return False."""
2764 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002765
2766 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002767 """Return True if self is negative; otherwise return False."""
2768 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002769
2770 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002771 """Return True if self is a signaling NaN; otherwise return False."""
2772 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002773
2774 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002775 """Return True if self is subnormal; otherwise return False."""
2776 if self._is_special or not self:
2777 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002778 if context is None:
2779 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002780 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002781
2782 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002783 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002784 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002785
2786 def _ln_exp_bound(self):
2787 """Compute a lower bound for the adjusted exponent of self.ln().
2788 In other words, compute r such that self.ln() >= 10**r. Assumes
2789 that self is finite and positive and that self != 1.
2790 """
2791
2792 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2793 adj = self._exp + len(self._int) - 1
2794 if adj >= 1:
2795 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2796 return len(str(adj*23//10)) - 1
2797 if adj <= -2:
2798 # argument <= 0.1
2799 return len(str((-1-adj)*23//10)) - 1
2800 op = _WorkRep(self)
2801 c, e = op.int, op.exp
2802 if adj == 0:
2803 # 1 < self < 10
2804 num = str(c-10**-e)
2805 den = str(c)
2806 return len(num) - len(den) - (num < den)
2807 # adj == -1, 0.1 <= self < 1
2808 return e + len(str(10**-e - c)) - 1
2809
2810
2811 def ln(self, context=None):
2812 """Returns the natural (base e) logarithm of self."""
2813
2814 if context is None:
2815 context = getcontext()
2816
2817 # ln(NaN) = NaN
2818 ans = self._check_nans(context=context)
2819 if ans:
2820 return ans
2821
2822 # ln(0.0) == -Infinity
2823 if not self:
2824 return negInf
2825
2826 # ln(Infinity) = Infinity
2827 if self._isinfinity() == 1:
2828 return Inf
2829
2830 # ln(1.0) == 0.0
2831 if self == Dec_p1:
2832 return Dec_0
2833
2834 # ln(negative) raises InvalidOperation
2835 if self._sign == 1:
2836 return context._raise_error(InvalidOperation,
2837 'ln of a negative value')
2838
2839 # result is irrational, so necessarily inexact
2840 op = _WorkRep(self)
2841 c, e = op.int, op.exp
2842 p = context.prec
2843
2844 # correctly rounded result: repeatedly increase precision by 3
2845 # until we get an unambiguously roundable result
2846 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2847 while True:
2848 coeff = _dlog(c, e, places)
2849 # assert len(str(abs(coeff)))-p >= 1
2850 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2851 break
2852 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002853 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002854
2855 context = context._shallow_copy()
2856 rounding = context._set_rounding(ROUND_HALF_EVEN)
2857 ans = ans._fix(context)
2858 context.rounding = rounding
2859 return ans
2860
2861 def _log10_exp_bound(self):
2862 """Compute a lower bound for the adjusted exponent of self.log10().
2863 In other words, find r such that self.log10() >= 10**r.
2864 Assumes that self is finite and positive and that self != 1.
2865 """
2866
2867 # For x >= 10 or x < 0.1 we only need a bound on the integer
2868 # part of log10(self), and this comes directly from the
2869 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2870 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2871 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2872
2873 adj = self._exp + len(self._int) - 1
2874 if adj >= 1:
2875 # self >= 10
2876 return len(str(adj))-1
2877 if adj <= -2:
2878 # self < 0.1
2879 return len(str(-1-adj))-1
2880 op = _WorkRep(self)
2881 c, e = op.int, op.exp
2882 if adj == 0:
2883 # 1 < self < 10
2884 num = str(c-10**-e)
2885 den = str(231*c)
2886 return len(num) - len(den) - (num < den) + 2
2887 # adj == -1, 0.1 <= self < 1
2888 num = str(10**-e-c)
2889 return len(num) + e - (num < "231") - 1
2890
2891 def log10(self, context=None):
2892 """Returns the base 10 logarithm of self."""
2893
2894 if context is None:
2895 context = getcontext()
2896
2897 # log10(NaN) = NaN
2898 ans = self._check_nans(context=context)
2899 if ans:
2900 return ans
2901
2902 # log10(0.0) == -Infinity
2903 if not self:
2904 return negInf
2905
2906 # log10(Infinity) = Infinity
2907 if self._isinfinity() == 1:
2908 return Inf
2909
2910 # log10(negative or -Infinity) raises InvalidOperation
2911 if self._sign == 1:
2912 return context._raise_error(InvalidOperation,
2913 'log10 of a negative value')
2914
2915 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00002916 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00002917 # answer may need rounding
2918 ans = Decimal(self._exp + len(self._int) - 1)
2919 else:
2920 # result is irrational, so necessarily inexact
2921 op = _WorkRep(self)
2922 c, e = op.int, op.exp
2923 p = context.prec
2924
2925 # correctly rounded result: repeatedly increase precision
2926 # until result is unambiguously roundable
2927 places = p-self._log10_exp_bound()+2
2928 while True:
2929 coeff = _dlog10(c, e, places)
2930 # assert len(str(abs(coeff)))-p >= 1
2931 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2932 break
2933 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002934 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002935
2936 context = context._shallow_copy()
2937 rounding = context._set_rounding(ROUND_HALF_EVEN)
2938 ans = ans._fix(context)
2939 context.rounding = rounding
2940 return ans
2941
2942 def logb(self, context=None):
2943 """ Returns the exponent of the magnitude of self's MSD.
2944
2945 The result is the integer which is the exponent of the magnitude
2946 of the most significant digit of self (as though it were truncated
2947 to a single digit while maintaining the value of that digit and
2948 without limiting the resulting exponent).
2949 """
2950 # logb(NaN) = NaN
2951 ans = self._check_nans(context=context)
2952 if ans:
2953 return ans
2954
2955 if context is None:
2956 context = getcontext()
2957
2958 # logb(+/-Inf) = +Inf
2959 if self._isinfinity():
2960 return Inf
2961
2962 # logb(0) = -Inf, DivisionByZero
2963 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00002964 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00002965
2966 # otherwise, simply return the adjusted exponent of self, as a
2967 # Decimal. Note that no attempt is made to fit the result
2968 # into the current context.
2969 return Decimal(self.adjusted())
2970
2971 def _islogical(self):
2972 """Return True if self is a logical operand.
2973
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00002974 For being logical, it must be a finite number with a sign of 0,
Facundo Batista353750c2007-09-13 18:13:15 +00002975 an exponent of 0, and a coefficient whose digits must all be
2976 either 0 or 1.
2977 """
2978 if self._sign != 0 or self._exp != 0:
2979 return False
2980 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002981 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00002982 return False
2983 return True
2984
2985 def _fill_logical(self, context, opa, opb):
2986 dif = context.prec - len(opa)
2987 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002988 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00002989 elif dif < 0:
2990 opa = opa[-context.prec:]
2991 dif = context.prec - len(opb)
2992 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002993 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00002994 elif dif < 0:
2995 opb = opb[-context.prec:]
2996 return opa, opb
2997
2998 def logical_and(self, other, context=None):
2999 """Applies an 'and' operation between self and other's digits."""
3000 if context is None:
3001 context = getcontext()
3002 if not self._islogical() or not other._islogical():
3003 return context._raise_error(InvalidOperation)
3004
3005 # fill to context.prec
3006 (opa, opb) = self._fill_logical(context, self._int, other._int)
3007
3008 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003009 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3010 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003011
3012 def logical_invert(self, context=None):
3013 """Invert all its digits."""
3014 if context is None:
3015 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003016 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3017 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003018
3019 def logical_or(self, other, context=None):
3020 """Applies an 'or' operation between self and other's digits."""
3021 if context is None:
3022 context = getcontext()
3023 if not self._islogical() or not other._islogical():
3024 return context._raise_error(InvalidOperation)
3025
3026 # fill to context.prec
3027 (opa, opb) = self._fill_logical(context, self._int, other._int)
3028
3029 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003030 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3031 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003032
3033 def logical_xor(self, other, context=None):
3034 """Applies an 'xor' operation between self and other's digits."""
3035 if context is None:
3036 context = getcontext()
3037 if not self._islogical() or not other._islogical():
3038 return context._raise_error(InvalidOperation)
3039
3040 # fill to context.prec
3041 (opa, opb) = self._fill_logical(context, self._int, other._int)
3042
3043 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003044 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3045 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003046
3047 def max_mag(self, other, context=None):
3048 """Compares the values numerically with their sign ignored."""
3049 other = _convert_other(other, raiseit=True)
3050
Facundo Batista6c398da2007-09-17 17:30:13 +00003051 if context is None:
3052 context = getcontext()
3053
Facundo Batista353750c2007-09-13 18:13:15 +00003054 if self._is_special or other._is_special:
3055 # If one operand is a quiet NaN and the other is number, then the
3056 # number is always returned
3057 sn = self._isnan()
3058 on = other._isnan()
3059 if sn or on:
3060 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003061 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003062 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003063 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003064 return self._check_nans(other, context)
3065
3066 c = self.copy_abs().__cmp__(other.copy_abs())
3067 if c == 0:
3068 c = self.compare_total(other)
3069
3070 if c == -1:
3071 ans = other
3072 else:
3073 ans = self
3074
Facundo Batistae64acfa2007-12-17 14:18:42 +00003075 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003076
3077 def min_mag(self, other, context=None):
3078 """Compares the values numerically with their sign ignored."""
3079 other = _convert_other(other, raiseit=True)
3080
Facundo Batista6c398da2007-09-17 17:30:13 +00003081 if context is None:
3082 context = getcontext()
3083
Facundo Batista353750c2007-09-13 18:13:15 +00003084 if self._is_special or other._is_special:
3085 # If one operand is a quiet NaN and the other is number, then the
3086 # number is always returned
3087 sn = self._isnan()
3088 on = other._isnan()
3089 if sn or on:
3090 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003091 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003092 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003093 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003094 return self._check_nans(other, context)
3095
3096 c = self.copy_abs().__cmp__(other.copy_abs())
3097 if c == 0:
3098 c = self.compare_total(other)
3099
3100 if c == -1:
3101 ans = self
3102 else:
3103 ans = other
3104
Facundo Batistae64acfa2007-12-17 14:18:42 +00003105 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003106
3107 def next_minus(self, context=None):
3108 """Returns the largest representable number smaller than itself."""
3109 if context is None:
3110 context = getcontext()
3111
3112 ans = self._check_nans(context=context)
3113 if ans:
3114 return ans
3115
3116 if self._isinfinity() == -1:
3117 return negInf
3118 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003119 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003120
3121 context = context.copy()
3122 context._set_rounding(ROUND_FLOOR)
3123 context._ignore_all_flags()
3124 new_self = self._fix(context)
3125 if new_self != self:
3126 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003127 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3128 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003129
3130 def next_plus(self, context=None):
3131 """Returns the smallest representable number larger than itself."""
3132 if context is None:
3133 context = getcontext()
3134
3135 ans = self._check_nans(context=context)
3136 if ans:
3137 return ans
3138
3139 if self._isinfinity() == 1:
3140 return Inf
3141 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003142 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003143
3144 context = context.copy()
3145 context._set_rounding(ROUND_CEILING)
3146 context._ignore_all_flags()
3147 new_self = self._fix(context)
3148 if new_self != self:
3149 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003150 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3151 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003152
3153 def next_toward(self, other, context=None):
3154 """Returns the number closest to self, in the direction towards other.
3155
3156 The result is the closest representable number to self
3157 (excluding self) that is in the direction towards other,
3158 unless both have the same value. If the two operands are
3159 numerically equal, then the result is a copy of self with the
3160 sign set to be the same as the sign of other.
3161 """
3162 other = _convert_other(other, raiseit=True)
3163
3164 if context is None:
3165 context = getcontext()
3166
3167 ans = self._check_nans(other, context)
3168 if ans:
3169 return ans
3170
3171 comparison = self.__cmp__(other)
3172 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003173 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003174
3175 if comparison == -1:
3176 ans = self.next_plus(context)
3177 else: # comparison == 1
3178 ans = self.next_minus(context)
3179
3180 # decide which flags to raise using value of ans
3181 if ans._isinfinity():
3182 context._raise_error(Overflow,
3183 'Infinite result from next_toward',
3184 ans._sign)
3185 context._raise_error(Rounded)
3186 context._raise_error(Inexact)
3187 elif ans.adjusted() < context.Emin:
3188 context._raise_error(Underflow)
3189 context._raise_error(Subnormal)
3190 context._raise_error(Rounded)
3191 context._raise_error(Inexact)
3192 # if precision == 1 then we don't raise Clamped for a
3193 # result 0E-Etiny.
3194 if not ans:
3195 context._raise_error(Clamped)
3196
3197 return ans
3198
3199 def number_class(self, context=None):
3200 """Returns an indication of the class of self.
3201
3202 The class is one of the following strings:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00003203 sNaN
3204 NaN
Facundo Batista353750c2007-09-13 18:13:15 +00003205 -Infinity
3206 -Normal
3207 -Subnormal
3208 -Zero
3209 +Zero
3210 +Subnormal
3211 +Normal
3212 +Infinity
3213 """
3214 if self.is_snan():
3215 return "sNaN"
3216 if self.is_qnan():
3217 return "NaN"
3218 inf = self._isinfinity()
3219 if inf == 1:
3220 return "+Infinity"
3221 if inf == -1:
3222 return "-Infinity"
3223 if self.is_zero():
3224 if self._sign:
3225 return "-Zero"
3226 else:
3227 return "+Zero"
3228 if context is None:
3229 context = getcontext()
3230 if self.is_subnormal(context=context):
3231 if self._sign:
3232 return "-Subnormal"
3233 else:
3234 return "+Subnormal"
3235 # just a normal, regular, boring number, :)
3236 if self._sign:
3237 return "-Normal"
3238 else:
3239 return "+Normal"
3240
3241 def radix(self):
3242 """Just returns 10, as this is Decimal, :)"""
3243 return Decimal(10)
3244
3245 def rotate(self, other, context=None):
3246 """Returns a rotated copy of self, value-of-other times."""
3247 if context is None:
3248 context = getcontext()
3249
3250 ans = self._check_nans(other, context)
3251 if ans:
3252 return ans
3253
3254 if other._exp != 0:
3255 return context._raise_error(InvalidOperation)
3256 if not (-context.prec <= int(other) <= context.prec):
3257 return context._raise_error(InvalidOperation)
3258
3259 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003260 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003261
3262 # get values, pad if necessary
3263 torot = int(other)
3264 rotdig = self._int
3265 topad = context.prec - len(rotdig)
3266 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003267 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003268
3269 # let's rotate!
3270 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003271 return _dec_from_triple(self._sign,
3272 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003273
3274 def scaleb (self, other, context=None):
3275 """Returns self operand after adding the second value to its exp."""
3276 if context is None:
3277 context = getcontext()
3278
3279 ans = self._check_nans(other, context)
3280 if ans:
3281 return ans
3282
3283 if other._exp != 0:
3284 return context._raise_error(InvalidOperation)
3285 liminf = -2 * (context.Emax + context.prec)
3286 limsup = 2 * (context.Emax + context.prec)
3287 if not (liminf <= int(other) <= limsup):
3288 return context._raise_error(InvalidOperation)
3289
3290 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003291 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003292
Facundo Batista72bc54f2007-11-23 17:59:00 +00003293 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003294 d = d._fix(context)
3295 return d
3296
3297 def shift(self, other, context=None):
3298 """Returns a shifted copy of self, value-of-other times."""
3299 if context is None:
3300 context = getcontext()
3301
3302 ans = self._check_nans(other, context)
3303 if ans:
3304 return ans
3305
3306 if other._exp != 0:
3307 return context._raise_error(InvalidOperation)
3308 if not (-context.prec <= int(other) <= context.prec):
3309 return context._raise_error(InvalidOperation)
3310
3311 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003312 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003313
3314 # get values, pad if necessary
3315 torot = int(other)
3316 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003317 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003318 rotdig = self._int
3319 topad = context.prec - len(rotdig)
3320 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003321 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003322
3323 # let's shift!
3324 if torot < 0:
3325 rotated = rotdig[:torot]
3326 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003327 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003328 rotated = rotated[-context.prec:]
3329
Facundo Batista72bc54f2007-11-23 17:59:00 +00003330 return _dec_from_triple(self._sign,
3331 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003332
Facundo Batista59c58842007-04-10 12:58:45 +00003333 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003334 def __reduce__(self):
3335 return (self.__class__, (str(self),))
3336
3337 def __copy__(self):
3338 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003339 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003340 return self.__class__(str(self))
3341
3342 def __deepcopy__(self, memo):
3343 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003344 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003345 return self.__class__(str(self))
3346
Facundo Batista72bc54f2007-11-23 17:59:00 +00003347def _dec_from_triple(sign, coefficient, exponent, special=False):
3348 """Create a decimal instance directly, without any validation,
3349 normalization (e.g. removal of leading zeros) or argument
3350 conversion.
3351
3352 This function is for *internal use only*.
3353 """
3354
3355 self = object.__new__(Decimal)
3356 self._sign = sign
3357 self._int = coefficient
3358 self._exp = exponent
3359 self._is_special = special
3360
3361 return self
3362
Facundo Batista59c58842007-04-10 12:58:45 +00003363##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003364
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003365
3366# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003367rounding_functions = [name for name in Decimal.__dict__.keys()
3368 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003369for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003370 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003371 globalname = name[1:].upper()
3372 val = globals()[globalname]
3373 Decimal._pick_rounding_function[val] = name
3374
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003375del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003376
Nick Coghlanced12182006-09-02 03:54:17 +00003377class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003378 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003379
Nick Coghlanced12182006-09-02 03:54:17 +00003380 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003381 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003382 """
3383 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003384 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003385 def __enter__(self):
3386 self.saved_context = getcontext()
3387 setcontext(self.new_context)
3388 return self.new_context
3389 def __exit__(self, t, v, tb):
3390 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003391
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003392class Context(object):
3393 """Contains the context for a Decimal instance.
3394
3395 Contains:
3396 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003397 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003398 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003399 raised when it is caused. Otherwise, a value is
3400 substituted in.
3401 flags - When an exception is caused, flags[exception] is incremented.
3402 (Whether or not the trap_enabler is set)
3403 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003404 Emin - Minimum exponent
3405 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003406 capitals - If 1, 1*10^1 is printed as 1E+1.
3407 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003408 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003409 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003410
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003411 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003412 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003413 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003414 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003415 _ignored_flags=None):
3416 if flags is None:
3417 flags = []
3418 if _ignored_flags is None:
3419 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003420 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003421 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003422 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003423 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003424 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003425 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003426 for name, val in locals().items():
3427 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003428 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003429 else:
3430 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003431 del self.self
3432
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003433 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003434 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003435 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003436 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3437 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3438 % vars(self))
3439 names = [f.__name__ for f, v in self.flags.items() if v]
3440 s.append('flags=[' + ', '.join(names) + ']')
3441 names = [t.__name__ for t, v in self.traps.items() if v]
3442 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003443 return ', '.join(s) + ')'
3444
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003445 def clear_flags(self):
3446 """Reset all flags to zero"""
3447 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003448 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003449
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003450 def _shallow_copy(self):
3451 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003452 nc = Context(self.prec, self.rounding, self.traps,
3453 self.flags, self.Emin, self.Emax,
3454 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003455 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003456
3457 def copy(self):
3458 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003459 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003460 self.flags.copy(), self.Emin, self.Emax,
3461 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003462 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003463 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003464
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003465 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003466 """Handles an error
3467
3468 If the flag is in _ignored_flags, returns the default response.
3469 Otherwise, it increments the flag, then, if the corresponding
3470 trap_enabler is set, it reaises the exception. Otherwise, it returns
3471 the default value after incrementing the flag.
3472 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003473 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003474 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003475 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003476 return error().handle(self, *args)
3477
3478 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003479 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003480 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003481 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003482
3483 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003484 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003485 raise error, explanation
3486
3487 def _ignore_all_flags(self):
3488 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003489 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003490
3491 def _ignore_flags(self, *flags):
3492 """Ignore the flags, if they are raised"""
3493 # Do not mutate-- This way, copies of a context leave the original
3494 # alone.
3495 self._ignored_flags = (self._ignored_flags + list(flags))
3496 return list(flags)
3497
3498 def _regard_flags(self, *flags):
3499 """Stop ignoring the flags, if they are raised"""
3500 if flags and isinstance(flags[0], (tuple,list)):
3501 flags = flags[0]
3502 for flag in flags:
3503 self._ignored_flags.remove(flag)
3504
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003505 def __hash__(self):
3506 """A Context cannot be hashed."""
3507 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003508 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003509
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003510 def Etiny(self):
3511 """Returns Etiny (= Emin - prec + 1)"""
3512 return int(self.Emin - self.prec + 1)
3513
3514 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003515 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003516 return int(self.Emax - self.prec + 1)
3517
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003518 def _set_rounding(self, type):
3519 """Sets the rounding type.
3520
3521 Sets the rounding type, and returns the current (previous)
3522 rounding type. Often used like:
3523
3524 context = context.copy()
3525 # so you don't change the calling context
3526 # if an error occurs in the middle.
3527 rounding = context._set_rounding(ROUND_UP)
3528 val = self.__sub__(other, context=context)
3529 context._set_rounding(rounding)
3530
3531 This will make it round up for that operation.
3532 """
3533 rounding = self.rounding
3534 self.rounding= type
3535 return rounding
3536
Raymond Hettingerfed52962004-07-14 15:41:57 +00003537 def create_decimal(self, num='0'):
Mark Dickinson59bc20b2008-01-12 01:56:00 +00003538 """Creates a new Decimal instance but using self as context.
3539
3540 This method implements the to-number operation of the
3541 IBM Decimal specification."""
3542
3543 if isinstance(num, basestring) and num != num.strip():
3544 return self._raise_error(ConversionSyntax,
3545 "no trailing or leading whitespace is "
3546 "permitted.")
3547
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003548 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003549 if d._isnan() and len(d._int) > self.prec - self._clamp:
3550 return self._raise_error(ConversionSyntax,
3551 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003552 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003553
Facundo Batista59c58842007-04-10 12:58:45 +00003554 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003555 def abs(self, a):
3556 """Returns the absolute value of the operand.
3557
3558 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003559 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003560 the plus operation on the operand.
3561
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003562 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003563 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003564 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003565 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003566 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003567 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003568 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003569 Decimal("101.5")
3570 """
3571 return a.__abs__(context=self)
3572
3573 def add(self, a, b):
3574 """Return the sum of the two operands.
3575
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003576 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003577 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003578 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003579 Decimal("1.02E+4")
3580 """
3581 return a.__add__(b, context=self)
3582
3583 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003584 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003585
Facundo Batista353750c2007-09-13 18:13:15 +00003586 def canonical(self, a):
3587 """Returns the same Decimal object.
3588
3589 As we do not have different encodings for the same number, the
3590 received object already is in its canonical form.
3591
3592 >>> ExtendedContext.canonical(Decimal('2.50'))
3593 Decimal("2.50")
3594 """
3595 return a.canonical(context=self)
3596
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003597 def compare(self, a, b):
3598 """Compares values numerically.
3599
3600 If the signs of the operands differ, a value representing each operand
3601 ('-1' if the operand is less than zero, '0' if the operand is zero or
3602 negative zero, or '1' if the operand is greater than zero) is used in
3603 place of that operand for the comparison instead of the actual
3604 operand.
3605
3606 The comparison is then effected by subtracting the second operand from
3607 the first and then returning a value according to the result of the
3608 subtraction: '-1' if the result is less than zero, '0' if the result is
3609 zero or negative zero, or '1' if the result is greater than zero.
3610
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003611 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003612 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003613 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003614 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003615 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003616 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003617 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003618 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003619 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003620 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003621 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003622 Decimal("-1")
3623 """
3624 return a.compare(b, context=self)
3625
Facundo Batista353750c2007-09-13 18:13:15 +00003626 def compare_signal(self, a, b):
3627 """Compares the values of the two operands numerically.
3628
3629 It's pretty much like compare(), but all NaNs signal, with signaling
3630 NaNs taking precedence over quiet NaNs.
3631
3632 >>> c = ExtendedContext
3633 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3634 Decimal("-1")
3635 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3636 Decimal("0")
3637 >>> c.flags[InvalidOperation] = 0
3638 >>> print c.flags[InvalidOperation]
3639 0
3640 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3641 Decimal("NaN")
3642 >>> print c.flags[InvalidOperation]
3643 1
3644 >>> c.flags[InvalidOperation] = 0
3645 >>> print c.flags[InvalidOperation]
3646 0
3647 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3648 Decimal("NaN")
3649 >>> print c.flags[InvalidOperation]
3650 1
3651 """
3652 return a.compare_signal(b, context=self)
3653
3654 def compare_total(self, a, b):
3655 """Compares two operands using their abstract representation.
3656
3657 This is not like the standard compare, which use their numerical
3658 value. Note that a total ordering is defined for all possible abstract
3659 representations.
3660
3661 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3662 Decimal("-1")
3663 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3664 Decimal("-1")
3665 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3666 Decimal("-1")
3667 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3668 Decimal("0")
3669 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3670 Decimal("1")
3671 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3672 Decimal("-1")
3673 """
3674 return a.compare_total(b)
3675
3676 def compare_total_mag(self, a, b):
3677 """Compares two operands using their abstract representation ignoring sign.
3678
3679 Like compare_total, but with operand's sign ignored and assumed to be 0.
3680 """
3681 return a.compare_total_mag(b)
3682
3683 def copy_abs(self, a):
3684 """Returns a copy of the operand with the sign set to 0.
3685
3686 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3687 Decimal("2.1")
3688 >>> ExtendedContext.copy_abs(Decimal('-100'))
3689 Decimal("100")
3690 """
3691 return a.copy_abs()
3692
3693 def copy_decimal(self, a):
3694 """Returns a copy of the decimal objet.
3695
3696 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3697 Decimal("2.1")
3698 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3699 Decimal("-1.00")
3700 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003701 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003702
3703 def copy_negate(self, a):
3704 """Returns a copy of the operand with the sign inverted.
3705
3706 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3707 Decimal("-101.5")
3708 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3709 Decimal("101.5")
3710 """
3711 return a.copy_negate()
3712
3713 def copy_sign(self, a, b):
3714 """Copies the second operand's sign to the first one.
3715
3716 In detail, it returns a copy of the first operand with the sign
3717 equal to the sign of the second operand.
3718
3719 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3720 Decimal("1.50")
3721 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3722 Decimal("1.50")
3723 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3724 Decimal("-1.50")
3725 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3726 Decimal("-1.50")
3727 """
3728 return a.copy_sign(b)
3729
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003730 def divide(self, a, b):
3731 """Decimal division in a specified context.
3732
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003733 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003734 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003735 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003736 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003737 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003738 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003739 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003740 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003741 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003742 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003743 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003744 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003745 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003746 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003747 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003748 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003749 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003750 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003751 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003752 Decimal("1.20E+6")
3753 """
3754 return a.__div__(b, context=self)
3755
3756 def divide_int(self, a, b):
3757 """Divides two numbers and returns the integer part of the result.
3758
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003759 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003760 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003761 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003762 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003763 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003764 Decimal("3")
3765 """
3766 return a.__floordiv__(b, context=self)
3767
3768 def divmod(self, a, b):
3769 return a.__divmod__(b, context=self)
3770
Facundo Batista353750c2007-09-13 18:13:15 +00003771 def exp(self, a):
3772 """Returns e ** a.
3773
3774 >>> c = ExtendedContext.copy()
3775 >>> c.Emin = -999
3776 >>> c.Emax = 999
3777 >>> c.exp(Decimal('-Infinity'))
3778 Decimal("0")
3779 >>> c.exp(Decimal('-1'))
3780 Decimal("0.367879441")
3781 >>> c.exp(Decimal('0'))
3782 Decimal("1")
3783 >>> c.exp(Decimal('1'))
3784 Decimal("2.71828183")
3785 >>> c.exp(Decimal('0.693147181'))
3786 Decimal("2.00000000")
3787 >>> c.exp(Decimal('+Infinity'))
3788 Decimal("Infinity")
3789 """
3790 return a.exp(context=self)
3791
3792 def fma(self, a, b, c):
3793 """Returns a multiplied by b, plus c.
3794
3795 The first two operands are multiplied together, using multiply,
3796 the third operand is then added to the result of that
3797 multiplication, using add, all with only one final rounding.
3798
3799 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3800 Decimal("22")
3801 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3802 Decimal("-8")
3803 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3804 Decimal("1.38435736E+12")
3805 """
3806 return a.fma(b, c, context=self)
3807
3808 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003809 """Return True if the operand is canonical; otherwise return False.
3810
3811 Currently, the encoding of a Decimal instance is always
3812 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00003813
3814 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003815 True
Facundo Batista353750c2007-09-13 18:13:15 +00003816 """
Facundo Batista1a191df2007-10-02 17:01:24 +00003817 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00003818
3819 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003820 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003821
Facundo Batista1a191df2007-10-02 17:01:24 +00003822 A Decimal instance is considered finite if it is neither
3823 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00003824
3825 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003826 True
Facundo Batista353750c2007-09-13 18:13:15 +00003827 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003828 True
Facundo Batista353750c2007-09-13 18:13:15 +00003829 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003830 True
Facundo Batista353750c2007-09-13 18:13:15 +00003831 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003832 False
Facundo Batista353750c2007-09-13 18:13:15 +00003833 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003834 False
Facundo Batista353750c2007-09-13 18:13:15 +00003835 """
3836 return a.is_finite()
3837
3838 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003839 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003840
3841 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003842 False
Facundo Batista353750c2007-09-13 18:13:15 +00003843 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003844 True
Facundo Batista353750c2007-09-13 18:13:15 +00003845 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003846 False
Facundo Batista353750c2007-09-13 18:13:15 +00003847 """
3848 return a.is_infinite()
3849
3850 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003851 """Return True if the operand is a qNaN or sNaN;
3852 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003853
3854 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003855 False
Facundo Batista353750c2007-09-13 18:13:15 +00003856 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003857 True
Facundo Batista353750c2007-09-13 18:13:15 +00003858 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003859 True
Facundo Batista353750c2007-09-13 18:13:15 +00003860 """
3861 return a.is_nan()
3862
3863 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003864 """Return True if the operand is a normal number;
3865 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003866
3867 >>> c = ExtendedContext.copy()
3868 >>> c.Emin = -999
3869 >>> c.Emax = 999
3870 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003871 True
Facundo Batista353750c2007-09-13 18:13:15 +00003872 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003873 False
Facundo Batista353750c2007-09-13 18:13:15 +00003874 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003875 False
Facundo Batista353750c2007-09-13 18:13:15 +00003876 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003877 False
Facundo Batista353750c2007-09-13 18:13:15 +00003878 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003879 False
Facundo Batista353750c2007-09-13 18:13:15 +00003880 """
3881 return a.is_normal(context=self)
3882
3883 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003884 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003885
3886 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003887 False
Facundo Batista353750c2007-09-13 18:13:15 +00003888 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003889 True
Facundo Batista353750c2007-09-13 18:13:15 +00003890 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003891 False
Facundo Batista353750c2007-09-13 18:13:15 +00003892 """
3893 return a.is_qnan()
3894
3895 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003896 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003897
3898 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003899 False
Facundo Batista353750c2007-09-13 18:13:15 +00003900 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003901 True
Facundo Batista353750c2007-09-13 18:13:15 +00003902 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003903 True
Facundo Batista353750c2007-09-13 18:13:15 +00003904 """
3905 return a.is_signed()
3906
3907 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003908 """Return True if the operand is a signaling NaN;
3909 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003910
3911 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003912 False
Facundo Batista353750c2007-09-13 18:13:15 +00003913 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003914 False
Facundo Batista353750c2007-09-13 18:13:15 +00003915 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003916 True
Facundo Batista353750c2007-09-13 18:13:15 +00003917 """
3918 return a.is_snan()
3919
3920 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003921 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003922
3923 >>> c = ExtendedContext.copy()
3924 >>> c.Emin = -999
3925 >>> c.Emax = 999
3926 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003927 False
Facundo Batista353750c2007-09-13 18:13:15 +00003928 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003929 True
Facundo Batista353750c2007-09-13 18:13:15 +00003930 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003931 False
Facundo Batista353750c2007-09-13 18:13:15 +00003932 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003933 False
Facundo Batista353750c2007-09-13 18:13:15 +00003934 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003935 False
Facundo Batista353750c2007-09-13 18:13:15 +00003936 """
3937 return a.is_subnormal(context=self)
3938
3939 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003940 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003941
3942 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003943 True
Facundo Batista353750c2007-09-13 18:13:15 +00003944 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003945 False
Facundo Batista353750c2007-09-13 18:13:15 +00003946 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003947 True
Facundo Batista353750c2007-09-13 18:13:15 +00003948 """
3949 return a.is_zero()
3950
3951 def ln(self, a):
3952 """Returns the natural (base e) logarithm of the operand.
3953
3954 >>> c = ExtendedContext.copy()
3955 >>> c.Emin = -999
3956 >>> c.Emax = 999
3957 >>> c.ln(Decimal('0'))
3958 Decimal("-Infinity")
3959 >>> c.ln(Decimal('1.000'))
3960 Decimal("0")
3961 >>> c.ln(Decimal('2.71828183'))
3962 Decimal("1.00000000")
3963 >>> c.ln(Decimal('10'))
3964 Decimal("2.30258509")
3965 >>> c.ln(Decimal('+Infinity'))
3966 Decimal("Infinity")
3967 """
3968 return a.ln(context=self)
3969
3970 def log10(self, a):
3971 """Returns the base 10 logarithm of the operand.
3972
3973 >>> c = ExtendedContext.copy()
3974 >>> c.Emin = -999
3975 >>> c.Emax = 999
3976 >>> c.log10(Decimal('0'))
3977 Decimal("-Infinity")
3978 >>> c.log10(Decimal('0.001'))
3979 Decimal("-3")
3980 >>> c.log10(Decimal('1.000'))
3981 Decimal("0")
3982 >>> c.log10(Decimal('2'))
3983 Decimal("0.301029996")
3984 >>> c.log10(Decimal('10'))
3985 Decimal("1")
3986 >>> c.log10(Decimal('70'))
3987 Decimal("1.84509804")
3988 >>> c.log10(Decimal('+Infinity'))
3989 Decimal("Infinity")
3990 """
3991 return a.log10(context=self)
3992
3993 def logb(self, a):
3994 """ Returns the exponent of the magnitude of the operand's MSD.
3995
3996 The result is the integer which is the exponent of the magnitude
3997 of the most significant digit of the operand (as though the
3998 operand were truncated to a single digit while maintaining the
3999 value of that digit and without limiting the resulting exponent).
4000
4001 >>> ExtendedContext.logb(Decimal('250'))
4002 Decimal("2")
4003 >>> ExtendedContext.logb(Decimal('2.50'))
4004 Decimal("0")
4005 >>> ExtendedContext.logb(Decimal('0.03'))
4006 Decimal("-2")
4007 >>> ExtendedContext.logb(Decimal('0'))
4008 Decimal("-Infinity")
4009 """
4010 return a.logb(context=self)
4011
4012 def logical_and(self, a, b):
4013 """Applies the logical operation 'and' between each operand's digits.
4014
4015 The operands must be both logical numbers.
4016
4017 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4018 Decimal("0")
4019 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4020 Decimal("0")
4021 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4022 Decimal("0")
4023 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4024 Decimal("1")
4025 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4026 Decimal("1000")
4027 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4028 Decimal("10")
4029 """
4030 return a.logical_and(b, context=self)
4031
4032 def logical_invert(self, a):
4033 """Invert all the digits in the operand.
4034
4035 The operand must be a logical number.
4036
4037 >>> ExtendedContext.logical_invert(Decimal('0'))
4038 Decimal("111111111")
4039 >>> ExtendedContext.logical_invert(Decimal('1'))
4040 Decimal("111111110")
4041 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4042 Decimal("0")
4043 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4044 Decimal("10101010")
4045 """
4046 return a.logical_invert(context=self)
4047
4048 def logical_or(self, a, b):
4049 """Applies the logical operation 'or' between each operand's digits.
4050
4051 The operands must be both logical numbers.
4052
4053 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4054 Decimal("0")
4055 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4056 Decimal("1")
4057 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4058 Decimal("1")
4059 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4060 Decimal("1")
4061 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4062 Decimal("1110")
4063 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4064 Decimal("1110")
4065 """
4066 return a.logical_or(b, context=self)
4067
4068 def logical_xor(self, a, b):
4069 """Applies the logical operation 'xor' between each operand's digits.
4070
4071 The operands must be both logical numbers.
4072
4073 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4074 Decimal("0")
4075 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4076 Decimal("1")
4077 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4078 Decimal("1")
4079 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4080 Decimal("0")
4081 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4082 Decimal("110")
4083 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4084 Decimal("1101")
4085 """
4086 return a.logical_xor(b, context=self)
4087
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004088 def max(self, a,b):
4089 """max compares two values numerically and returns the maximum.
4090
4091 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004092 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004093 operation. If they are numerically equal then the left-hand operand
4094 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004095 infinity) of the two operands is chosen as the result.
4096
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004097 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004098 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004099 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004100 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004101 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004102 Decimal("1")
4103 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4104 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004105 """
4106 return a.max(b, context=self)
4107
Facundo Batista353750c2007-09-13 18:13:15 +00004108 def max_mag(self, a, b):
4109 """Compares the values numerically with their sign ignored."""
4110 return a.max_mag(b, context=self)
4111
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004112 def min(self, a,b):
4113 """min compares two values numerically and returns the minimum.
4114
4115 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004116 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004117 operation. If they are numerically equal then the left-hand operand
4118 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004119 infinity) of the two operands is chosen as the result.
4120
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004121 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004122 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004123 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004124 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004125 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004126 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004127 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4128 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004129 """
4130 return a.min(b, context=self)
4131
Facundo Batista353750c2007-09-13 18:13:15 +00004132 def min_mag(self, a, b):
4133 """Compares the values numerically with their sign ignored."""
4134 return a.min_mag(b, context=self)
4135
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004136 def minus(self, a):
4137 """Minus corresponds to unary prefix minus in Python.
4138
4139 The operation is evaluated using the same rules as subtract; the
4140 operation minus(a) is calculated as subtract('0', a) where the '0'
4141 has the same exponent as the operand.
4142
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004143 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004144 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004145 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004146 Decimal("1.3")
4147 """
4148 return a.__neg__(context=self)
4149
4150 def multiply(self, a, b):
4151 """multiply multiplies two operands.
4152
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004153 If either operand is a special value then the general rules apply.
4154 Otherwise, the operands are multiplied together ('long multiplication'),
4155 resulting in a number which may be as long as the sum of the lengths
4156 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004157
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004158 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004159 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004160 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004161 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004162 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004163 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004164 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004165 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004166 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004167 Decimal("4.28135971E+11")
4168 """
4169 return a.__mul__(b, context=self)
4170
Facundo Batista353750c2007-09-13 18:13:15 +00004171 def next_minus(self, a):
4172 """Returns the largest representable number smaller than a.
4173
4174 >>> c = ExtendedContext.copy()
4175 >>> c.Emin = -999
4176 >>> c.Emax = 999
4177 >>> ExtendedContext.next_minus(Decimal('1'))
4178 Decimal("0.999999999")
4179 >>> c.next_minus(Decimal('1E-1007'))
4180 Decimal("0E-1007")
4181 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4182 Decimal("-1.00000004")
4183 >>> c.next_minus(Decimal('Infinity'))
4184 Decimal("9.99999999E+999")
4185 """
4186 return a.next_minus(context=self)
4187
4188 def next_plus(self, a):
4189 """Returns the smallest representable number larger than a.
4190
4191 >>> c = ExtendedContext.copy()
4192 >>> c.Emin = -999
4193 >>> c.Emax = 999
4194 >>> ExtendedContext.next_plus(Decimal('1'))
4195 Decimal("1.00000001")
4196 >>> c.next_plus(Decimal('-1E-1007'))
4197 Decimal("-0E-1007")
4198 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4199 Decimal("-1.00000002")
4200 >>> c.next_plus(Decimal('-Infinity'))
4201 Decimal("-9.99999999E+999")
4202 """
4203 return a.next_plus(context=self)
4204
4205 def next_toward(self, a, b):
4206 """Returns the number closest to a, in direction towards b.
4207
4208 The result is the closest representable number from the first
4209 operand (but not the first operand) that is in the direction
4210 towards the second operand, unless the operands have the same
4211 value.
4212
4213 >>> c = ExtendedContext.copy()
4214 >>> c.Emin = -999
4215 >>> c.Emax = 999
4216 >>> c.next_toward(Decimal('1'), Decimal('2'))
4217 Decimal("1.00000001")
4218 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4219 Decimal("-0E-1007")
4220 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4221 Decimal("-1.00000002")
4222 >>> c.next_toward(Decimal('1'), Decimal('0'))
4223 Decimal("0.999999999")
4224 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4225 Decimal("0E-1007")
4226 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4227 Decimal("-1.00000004")
4228 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4229 Decimal("-0.00")
4230 """
4231 return a.next_toward(b, context=self)
4232
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004233 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004234 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004235
4236 Essentially a plus operation with all trailing zeros removed from the
4237 result.
4238
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004239 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004240 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004241 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004242 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004243 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004244 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004245 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004246 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004247 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004248 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004249 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004250 Decimal("0")
4251 """
4252 return a.normalize(context=self)
4253
Facundo Batista353750c2007-09-13 18:13:15 +00004254 def number_class(self, a):
4255 """Returns an indication of the class of the operand.
4256
4257 The class is one of the following strings:
4258 -sNaN
4259 -NaN
4260 -Infinity
4261 -Normal
4262 -Subnormal
4263 -Zero
4264 +Zero
4265 +Subnormal
4266 +Normal
4267 +Infinity
4268
4269 >>> c = Context(ExtendedContext)
4270 >>> c.Emin = -999
4271 >>> c.Emax = 999
4272 >>> c.number_class(Decimal('Infinity'))
4273 '+Infinity'
4274 >>> c.number_class(Decimal('1E-10'))
4275 '+Normal'
4276 >>> c.number_class(Decimal('2.50'))
4277 '+Normal'
4278 >>> c.number_class(Decimal('0.1E-999'))
4279 '+Subnormal'
4280 >>> c.number_class(Decimal('0'))
4281 '+Zero'
4282 >>> c.number_class(Decimal('-0'))
4283 '-Zero'
4284 >>> c.number_class(Decimal('-0.1E-999'))
4285 '-Subnormal'
4286 >>> c.number_class(Decimal('-1E-10'))
4287 '-Normal'
4288 >>> c.number_class(Decimal('-2.50'))
4289 '-Normal'
4290 >>> c.number_class(Decimal('-Infinity'))
4291 '-Infinity'
4292 >>> c.number_class(Decimal('NaN'))
4293 'NaN'
4294 >>> c.number_class(Decimal('-NaN'))
4295 'NaN'
4296 >>> c.number_class(Decimal('sNaN'))
4297 'sNaN'
4298 """
4299 return a.number_class(context=self)
4300
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004301 def plus(self, a):
4302 """Plus corresponds to unary prefix plus in Python.
4303
4304 The operation is evaluated using the same rules as add; the
4305 operation plus(a) is calculated as add('0', a) where the '0'
4306 has the same exponent as the operand.
4307
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004308 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004309 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004310 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004311 Decimal("-1.3")
4312 """
4313 return a.__pos__(context=self)
4314
4315 def power(self, a, b, modulo=None):
4316 """Raises a to the power of b, to modulo if given.
4317
Facundo Batista353750c2007-09-13 18:13:15 +00004318 With two arguments, compute a**b. If a is negative then b
4319 must be integral. The result will be inexact unless b is
4320 integral and the result is finite and can be expressed exactly
4321 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004322
Facundo Batista353750c2007-09-13 18:13:15 +00004323 With three arguments, compute (a**b) % modulo. For the
4324 three argument form, the following restrictions on the
4325 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004326
Facundo Batista353750c2007-09-13 18:13:15 +00004327 - all three arguments must be integral
4328 - b must be nonnegative
4329 - at least one of a or b must be nonzero
4330 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004331
Facundo Batista353750c2007-09-13 18:13:15 +00004332 The result of pow(a, b, modulo) is identical to the result
4333 that would be obtained by computing (a**b) % modulo with
4334 unbounded precision, but is computed more efficiently. It is
4335 always exact.
4336
4337 >>> c = ExtendedContext.copy()
4338 >>> c.Emin = -999
4339 >>> c.Emax = 999
4340 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004341 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004342 >>> c.power(Decimal('-2'), Decimal('3'))
4343 Decimal("-8")
4344 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004345 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004346 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004347 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004348 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4349 Decimal("2.00000000")
4350 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004351 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004352 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004353 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004354 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004355 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004356 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004357 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004358 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004359 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004360 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004361 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004362 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004363 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004364 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004365 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004366
4367 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4368 Decimal("11")
4369 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4370 Decimal("-11")
4371 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4372 Decimal("1")
4373 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4374 Decimal("11")
4375 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4376 Decimal("11729830")
4377 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4378 Decimal("-0")
4379 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4380 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004381 """
4382 return a.__pow__(b, modulo, context=self)
4383
4384 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004385 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004386
4387 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004388 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004389 exponent is being increased), multiplied by a positive power of ten (if
4390 the exponent is being decreased), or is unchanged (if the exponent is
4391 already equal to that of the right-hand operand).
4392
4393 Unlike other operations, if the length of the coefficient after the
4394 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004395 operation condition is raised. This guarantees that, unless there is
4396 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004397 equal to that of the right-hand operand.
4398
4399 Also unlike other operations, quantize will never raise Underflow, even
4400 if the result is subnormal and inexact.
4401
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004402 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004403 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004404 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004405 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004406 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004407 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004408 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004409 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004410 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004411 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004412 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004413 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004414 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004415 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004416 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004417 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004418 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004419 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004420 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004421 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004422 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004423 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004424 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004425 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004426 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004427 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004428 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004429 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004430 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004431 Decimal("2E+2")
4432 """
4433 return a.quantize(b, context=self)
4434
Facundo Batista353750c2007-09-13 18:13:15 +00004435 def radix(self):
4436 """Just returns 10, as this is Decimal, :)
4437
4438 >>> ExtendedContext.radix()
4439 Decimal("10")
4440 """
4441 return Decimal(10)
4442
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004443 def remainder(self, a, b):
4444 """Returns the remainder from integer division.
4445
4446 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004447 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004448 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004449 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004450
4451 This operation will fail under the same conditions as integer division
4452 (that is, if integer division on the same two operands would fail, the
4453 remainder cannot be calculated).
4454
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004455 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004456 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004457 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004458 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004459 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004460 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004461 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004462 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004463 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004464 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004465 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004466 Decimal("1.0")
4467 """
4468 return a.__mod__(b, context=self)
4469
4470 def remainder_near(self, a, b):
4471 """Returns to be "a - b * n", where n is the integer nearest the exact
4472 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004473 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004474 sign of a.
4475
4476 This operation will fail under the same conditions as integer division
4477 (that is, if integer division on the same two operands would fail, the
4478 remainder cannot be calculated).
4479
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004480 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004481 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004482 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004483 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004484 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004485 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004486 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004487 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004488 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004489 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004490 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004491 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004492 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004493 Decimal("-0.3")
4494 """
4495 return a.remainder_near(b, context=self)
4496
Facundo Batista353750c2007-09-13 18:13:15 +00004497 def rotate(self, a, b):
4498 """Returns a rotated copy of a, b times.
4499
4500 The coefficient of the result is a rotated copy of the digits in
4501 the coefficient of the first operand. The number of places of
4502 rotation is taken from the absolute value of the second operand,
4503 with the rotation being to the left if the second operand is
4504 positive or to the right otherwise.
4505
4506 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4507 Decimal("400000003")
4508 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4509 Decimal("12")
4510 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4511 Decimal("891234567")
4512 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4513 Decimal("123456789")
4514 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4515 Decimal("345678912")
4516 """
4517 return a.rotate(b, context=self)
4518
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004519 def same_quantum(self, a, b):
4520 """Returns True if the two operands have the same exponent.
4521
4522 The result is never affected by either the sign or the coefficient of
4523 either operand.
4524
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004525 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004526 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004527 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004528 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004529 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004530 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004531 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004532 True
4533 """
4534 return a.same_quantum(b)
4535
Facundo Batista353750c2007-09-13 18:13:15 +00004536 def scaleb (self, a, b):
4537 """Returns the first operand after adding the second value its exp.
4538
4539 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4540 Decimal("0.0750")
4541 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4542 Decimal("7.50")
4543 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4544 Decimal("7.50E+3")
4545 """
4546 return a.scaleb (b, context=self)
4547
4548 def shift(self, a, b):
4549 """Returns a shifted copy of a, b times.
4550
4551 The coefficient of the result is a shifted copy of the digits
4552 in the coefficient of the first operand. The number of places
4553 to shift is taken from the absolute value of the second operand,
4554 with the shift being to the left if the second operand is
4555 positive or to the right otherwise. Digits shifted into the
4556 coefficient are zeros.
4557
4558 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4559 Decimal("400000000")
4560 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4561 Decimal("0")
4562 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4563 Decimal("1234567")
4564 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4565 Decimal("123456789")
4566 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4567 Decimal("345678900")
4568 """
4569 return a.shift(b, context=self)
4570
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004571 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004572 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004573
4574 If the result must be inexact, it is rounded using the round-half-even
4575 algorithm.
4576
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004577 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004578 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004579 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004580 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004581 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004582 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004583 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004584 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004585 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004586 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004587 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004588 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004589 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004590 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004591 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004592 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004593 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004594 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004595 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004596 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004597 """
4598 return a.sqrt(context=self)
4599
4600 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004601 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004602
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004603 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004604 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004605 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004606 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004607 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004608 Decimal("-0.77")
4609 """
4610 return a.__sub__(b, context=self)
4611
4612 def to_eng_string(self, a):
4613 """Converts a number to a string, using scientific notation.
4614
4615 The operation is not affected by the context.
4616 """
4617 return a.to_eng_string(context=self)
4618
4619 def to_sci_string(self, a):
4620 """Converts a number to a string, using scientific notation.
4621
4622 The operation is not affected by the context.
4623 """
4624 return a.__str__(context=self)
4625
Facundo Batista353750c2007-09-13 18:13:15 +00004626 def to_integral_exact(self, a):
4627 """Rounds to an integer.
4628
4629 When the operand has a negative exponent, the result is the same
4630 as using the quantize() operation using the given operand as the
4631 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4632 of the operand as the precision setting; Inexact and Rounded flags
4633 are allowed in this operation. The rounding mode is taken from the
4634 context.
4635
4636 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4637 Decimal("2")
4638 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4639 Decimal("100")
4640 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4641 Decimal("100")
4642 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4643 Decimal("102")
4644 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4645 Decimal("-102")
4646 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4647 Decimal("1.0E+6")
4648 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4649 Decimal("7.89E+77")
4650 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4651 Decimal("-Infinity")
4652 """
4653 return a.to_integral_exact(context=self)
4654
4655 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004656 """Rounds to an integer.
4657
4658 When the operand has a negative exponent, the result is the same
4659 as using the quantize() operation using the given operand as the
4660 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4661 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004662 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004663
Facundo Batista353750c2007-09-13 18:13:15 +00004664 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004665 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004666 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004667 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004668 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004669 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004670 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004671 Decimal("102")
Facundo Batista353750c2007-09-13 18:13:15 +00004672 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004673 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004674 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004675 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004676 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004677 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004678 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004679 Decimal("-Infinity")
4680 """
Facundo Batista353750c2007-09-13 18:13:15 +00004681 return a.to_integral_value(context=self)
4682
4683 # the method name changed, but we provide also the old one, for compatibility
4684 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004685
4686class _WorkRep(object):
4687 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004688 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004689 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004690 # exp: None, int, or string
4691
4692 def __init__(self, value=None):
4693 if value is None:
4694 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004695 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004696 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004697 elif isinstance(value, Decimal):
4698 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004699 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004700 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004701 else:
4702 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004703 self.sign = value[0]
4704 self.int = value[1]
4705 self.exp = value[2]
4706
4707 def __repr__(self):
4708 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4709
4710 __str__ = __repr__
4711
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004712
4713
Facundo Batistae64acfa2007-12-17 14:18:42 +00004714def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004715 """Normalizes op1, op2 to have the same exp and length of coefficient.
4716
4717 Done during addition.
4718 """
Facundo Batista353750c2007-09-13 18:13:15 +00004719 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004720 tmp = op2
4721 other = op1
4722 else:
4723 tmp = op1
4724 other = op2
4725
Facundo Batista353750c2007-09-13 18:13:15 +00004726 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4727 # Then adding 10**exp to tmp has the same effect (after rounding)
4728 # as adding any positive quantity smaller than 10**exp; similarly
4729 # for subtraction. So if other is smaller than 10**exp we replace
4730 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00004731 tmp_len = len(str(tmp.int))
4732 other_len = len(str(other.int))
4733 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4734 if other_len + other.exp - 1 < exp:
4735 other.int = 1
4736 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004737
Facundo Batista353750c2007-09-13 18:13:15 +00004738 tmp.int *= 10 ** (tmp.exp - other.exp)
4739 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004740 return op1, op2
4741
Facundo Batista353750c2007-09-13 18:13:15 +00004742##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4743
4744# This function from Tim Peters was taken from here:
4745# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4746# The correction being in the function definition is for speed, and
4747# the whole function is not resolved with math.log because of avoiding
4748# the use of floats.
4749def _nbits(n, correction = {
4750 '0': 4, '1': 3, '2': 2, '3': 2,
4751 '4': 1, '5': 1, '6': 1, '7': 1,
4752 '8': 0, '9': 0, 'a': 0, 'b': 0,
4753 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4754 """Number of bits in binary representation of the positive integer n,
4755 or 0 if n == 0.
4756 """
4757 if n < 0:
4758 raise ValueError("The argument to _nbits should be nonnegative.")
4759 hex_n = "%x" % n
4760 return 4*len(hex_n) - correction[hex_n[0]]
4761
4762def _sqrt_nearest(n, a):
4763 """Closest integer to the square root of the positive integer n. a is
4764 an initial approximation to the square root. Any positive integer
4765 will do for a, but the closer a is to the square root of n the
4766 faster convergence will be.
4767
4768 """
4769 if n <= 0 or a <= 0:
4770 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4771
4772 b=0
4773 while a != b:
4774 b, a = a, a--n//a>>1
4775 return a
4776
4777def _rshift_nearest(x, shift):
4778 """Given an integer x and a nonnegative integer shift, return closest
4779 integer to x / 2**shift; use round-to-even in case of a tie.
4780
4781 """
4782 b, q = 1L << shift, x >> shift
4783 return q + (2*(x & (b-1)) + (q&1) > b)
4784
4785def _div_nearest(a, b):
4786 """Closest integer to a/b, a and b positive integers; rounds to even
4787 in the case of a tie.
4788
4789 """
4790 q, r = divmod(a, b)
4791 return q + (2*r + (q&1) > b)
4792
4793def _ilog(x, M, L = 8):
4794 """Integer approximation to M*log(x/M), with absolute error boundable
4795 in terms only of x/M.
4796
4797 Given positive integers x and M, return an integer approximation to
4798 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4799 between the approximation and the exact result is at most 22. For
4800 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4801 both cases these are upper bounds on the error; it will usually be
4802 much smaller."""
4803
4804 # The basic algorithm is the following: let log1p be the function
4805 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4806 # the reduction
4807 #
4808 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4809 #
4810 # repeatedly until the argument to log1p is small (< 2**-L in
4811 # absolute value). For small y we can use the Taylor series
4812 # expansion
4813 #
4814 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4815 #
4816 # truncating at T such that y**T is small enough. The whole
4817 # computation is carried out in a form of fixed-point arithmetic,
4818 # with a real number z being represented by an integer
4819 # approximation to z*M. To avoid loss of precision, the y below
4820 # is actually an integer approximation to 2**R*y*M, where R is the
4821 # number of reductions performed so far.
4822
4823 y = x-M
4824 # argument reduction; R = number of reductions performed
4825 R = 0
4826 while (R <= L and long(abs(y)) << L-R >= M or
4827 R > L and abs(y) >> R-L >= M):
4828 y = _div_nearest(long(M*y) << 1,
4829 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4830 R += 1
4831
4832 # Taylor series with T terms
4833 T = -int(-10*len(str(M))//(3*L))
4834 yshift = _rshift_nearest(y, R)
4835 w = _div_nearest(M, T)
4836 for k in xrange(T-1, 0, -1):
4837 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4838
4839 return _div_nearest(w*y, M)
4840
4841def _dlog10(c, e, p):
4842 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4843 approximation to 10**p * log10(c*10**e), with an absolute error of
4844 at most 1. Assumes that c*10**e is not exactly 1."""
4845
4846 # increase precision by 2; compensate for this by dividing
4847 # final result by 100
4848 p += 2
4849
4850 # write c*10**e as d*10**f with either:
4851 # f >= 0 and 1 <= d <= 10, or
4852 # f <= 0 and 0.1 <= d <= 1.
4853 # Thus for c*10**e close to 1, f = 0
4854 l = len(str(c))
4855 f = e+l - (e+l >= 1)
4856
4857 if p > 0:
4858 M = 10**p
4859 k = e+p-f
4860 if k >= 0:
4861 c *= 10**k
4862 else:
4863 c = _div_nearest(c, 10**-k)
4864
4865 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004866 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004867 log_d = _div_nearest(log_d*M, log_10)
4868 log_tenpower = f*M # exact
4869 else:
4870 log_d = 0 # error < 2.31
4871 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4872
4873 return _div_nearest(log_tenpower+log_d, 100)
4874
4875def _dlog(c, e, p):
4876 """Given integers c, e and p with c > 0, compute an integer
4877 approximation to 10**p * log(c*10**e), with an absolute error of
4878 at most 1. Assumes that c*10**e is not exactly 1."""
4879
4880 # Increase precision by 2. The precision increase is compensated
4881 # for at the end with a division by 100.
4882 p += 2
4883
4884 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4885 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4886 # as 10**p * log(d) + 10**p*f * log(10).
4887 l = len(str(c))
4888 f = e+l - (e+l >= 1)
4889
4890 # compute approximation to 10**p*log(d), with error < 27
4891 if p > 0:
4892 k = e+p-f
4893 if k >= 0:
4894 c *= 10**k
4895 else:
4896 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4897
4898 # _ilog magnifies existing error in c by a factor of at most 10
4899 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4900 else:
4901 # p <= 0: just approximate the whole thing by 0; error < 2.31
4902 log_d = 0
4903
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004904 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00004905 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004906 extra = len(str(abs(f)))-1
4907 if p + extra >= 0:
4908 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4909 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4910 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00004911 else:
4912 f_log_ten = 0
4913 else:
4914 f_log_ten = 0
4915
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004916 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004917 return _div_nearest(f_log_ten + log_d, 100)
4918
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004919class _Log10Memoize(object):
4920 """Class to compute, store, and allow retrieval of, digits of the
4921 constant log(10) = 2.302585.... This constant is needed by
4922 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4923 def __init__(self):
4924 self.digits = "23025850929940456840179914546843642076011014886"
4925
4926 def getdigits(self, p):
4927 """Given an integer p >= 0, return floor(10**p)*log(10).
4928
4929 For example, self.getdigits(3) returns 2302.
4930 """
4931 # digits are stored as a string, for quick conversion to
4932 # integer in the case that we've already computed enough
4933 # digits; the stored digits should always be correct
4934 # (truncated, not rounded to nearest).
4935 if p < 0:
4936 raise ValueError("p should be nonnegative")
4937
4938 if p >= len(self.digits):
4939 # compute p+3, p+6, p+9, ... digits; continue until at
4940 # least one of the extra digits is nonzero
4941 extra = 3
4942 while True:
4943 # compute p+extra digits, correct to within 1ulp
4944 M = 10**(p+extra+2)
4945 digits = str(_div_nearest(_ilog(10*M, M), 100))
4946 if digits[-extra:] != '0'*extra:
4947 break
4948 extra += 3
4949 # keep all reliable digits so far; remove trailing zeros
4950 # and next nonzero digit
4951 self.digits = digits.rstrip('0')[:-1]
4952 return int(self.digits[:p+1])
4953
4954_log10_digits = _Log10Memoize().getdigits
4955
Facundo Batista353750c2007-09-13 18:13:15 +00004956def _iexp(x, M, L=8):
4957 """Given integers x and M, M > 0, such that x/M is small in absolute
4958 value, compute an integer approximation to M*exp(x/M). For 0 <=
4959 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4960 is usually much smaller)."""
4961
4962 # Algorithm: to compute exp(z) for a real number z, first divide z
4963 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4964 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4965 # series
4966 #
4967 # expm1(x) = x + x**2/2! + x**3/3! + ...
4968 #
4969 # Now use the identity
4970 #
4971 # expm1(2x) = expm1(x)*(expm1(x)+2)
4972 #
4973 # R times to compute the sequence expm1(z/2**R),
4974 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
4975
4976 # Find R such that x/2**R/M <= 2**-L
4977 R = _nbits((long(x)<<L)//M)
4978
4979 # Taylor series. (2**L)**T > M
4980 T = -int(-10*len(str(M))//(3*L))
4981 y = _div_nearest(x, T)
4982 Mshift = long(M)<<R
4983 for i in xrange(T-1, 0, -1):
4984 y = _div_nearest(x*(Mshift + y), Mshift * i)
4985
4986 # Expansion
4987 for k in xrange(R-1, -1, -1):
4988 Mshift = long(M)<<(k+2)
4989 y = _div_nearest(y*(y+Mshift), Mshift)
4990
4991 return M+y
4992
4993def _dexp(c, e, p):
4994 """Compute an approximation to exp(c*10**e), with p decimal places of
4995 precision.
4996
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004997 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00004998
4999 10**(p-1) <= d <= 10**p, and
5000 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5001
5002 In other words, d*10**f is an approximation to exp(c*10**e) with p
5003 digits of precision, and with an error in d of at most 1. This is
5004 almost, but not quite, the same as the error being < 1ulp: when d
5005 = 10**(p-1) the error could be up to 10 ulp."""
5006
5007 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5008 p += 2
5009
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005010 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005011 extra = max(0, e + len(str(c)) - 1)
5012 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005013
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005014 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005015 # rounding down
5016 shift = e+q
5017 if shift >= 0:
5018 cshift = c*10**shift
5019 else:
5020 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005021 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005022
5023 # reduce remainder back to original precision
5024 rem = _div_nearest(rem, 10**extra)
5025
5026 # error in result of _iexp < 120; error after division < 0.62
5027 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5028
5029def _dpower(xc, xe, yc, ye, p):
5030 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5031 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5032
5033 10**(p-1) <= c <= 10**p, and
5034 (c-1)*10**e < x**y < (c+1)*10**e
5035
5036 in other words, c*10**e is an approximation to x**y with p digits
5037 of precision, and with an error in c of at most 1. (This is
5038 almost, but not quite, the same as the error being < 1ulp: when c
5039 == 10**(p-1) we can only guarantee error < 10ulp.)
5040
5041 We assume that: x is positive and not equal to 1, and y is nonzero.
5042 """
5043
5044 # Find b such that 10**(b-1) <= |y| <= 10**b
5045 b = len(str(abs(yc))) + ye
5046
5047 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5048 lxc = _dlog(xc, xe, p+b+1)
5049
5050 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5051 shift = ye-b
5052 if shift >= 0:
5053 pc = lxc*yc*10**shift
5054 else:
5055 pc = _div_nearest(lxc*yc, 10**-shift)
5056
5057 if pc == 0:
5058 # we prefer a result that isn't exactly 1; this makes it
5059 # easier to compute a correctly rounded result in __pow__
5060 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5061 coeff, exp = 10**(p-1)+1, 1-p
5062 else:
5063 coeff, exp = 10**p-1, -p
5064 else:
5065 coeff, exp = _dexp(pc, -(p+1), p+1)
5066 coeff = _div_nearest(coeff, 10)
5067 exp += 1
5068
5069 return coeff, exp
5070
5071def _log10_lb(c, correction = {
5072 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5073 '6': 23, '7': 16, '8': 10, '9': 5}):
5074 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5075 if c <= 0:
5076 raise ValueError("The argument to _log10_lb should be nonnegative.")
5077 str_c = str(c)
5078 return 100*len(str_c) - correction[str_c[0]]
5079
Facundo Batista59c58842007-04-10 12:58:45 +00005080##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005081
Facundo Batista353750c2007-09-13 18:13:15 +00005082def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005083 """Convert other to Decimal.
5084
5085 Verifies that it's ok to use in an implicit construction.
5086 """
5087 if isinstance(other, Decimal):
5088 return other
5089 if isinstance(other, (int, long)):
5090 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005091 if raiseit:
5092 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005093 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005094
Facundo Batista59c58842007-04-10 12:58:45 +00005095##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005096
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005097# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005098# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005099
5100DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005101 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005102 traps=[DivisionByZero, Overflow, InvalidOperation],
5103 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005104 Emax=999999999,
5105 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005106 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005107)
5108
5109# Pre-made alternate contexts offered by the specification
5110# Don't change these; the user should be able to select these
5111# contexts and be able to reproduce results from other implementations
5112# of the spec.
5113
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005114BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005115 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005116 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5117 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005118)
5119
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005120ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005121 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005122 traps=[],
5123 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005124)
5125
5126
Facundo Batista72bc54f2007-11-23 17:59:00 +00005127##### crud for parsing strings #############################################
5128import re
5129
5130# Regular expression used for parsing numeric strings. Additional
5131# comments:
5132#
5133# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5134# whitespace. But note that the specification disallows whitespace in
5135# a numeric string.
5136#
5137# 2. For finite numbers (not infinities and NaNs) the body of the
5138# number between the optional sign and the optional exponent must have
5139# at least one decimal digit, possibly after the decimal point. The
5140# lookahead expression '(?=\d|\.\d)' checks this.
5141#
5142# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5143# other meaning for \d than the numbers [0-9].
5144
5145import re
5146_parser = re.compile(r""" # A numeric string consists of:
5147# \s*
5148 (?P<sign>[-+])? # an optional sign, followed by either...
5149 (
5150 (?=\d|\.\d) # ...a number (with at least one digit)
5151 (?P<int>\d*) # consisting of a (possibly empty) integer part
5152 (\.(?P<frac>\d*))? # followed by an optional fractional part
5153 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5154 |
5155 Inf(inity)? # ...an infinity, or...
5156 |
5157 (?P<signal>s)? # ...an (optionally signaling)
5158 NaN # NaN
5159 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5160 )
5161# \s*
Mark Dickinson59bc20b2008-01-12 01:56:00 +00005162 \Z
Facundo Batista72bc54f2007-11-23 17:59:00 +00005163""", re.VERBOSE | re.IGNORECASE).match
5164
Facundo Batista2ec74152007-12-03 17:55:00 +00005165_all_zeros = re.compile('0*$').match
5166_exact_half = re.compile('50*$').match
Facundo Batista72bc54f2007-11-23 17:59:00 +00005167del re
5168
5169
Facundo Batista59c58842007-04-10 12:58:45 +00005170##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005171
Facundo Batista59c58842007-04-10 12:58:45 +00005172# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005173Inf = Decimal('Inf')
5174negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005175NaN = Decimal('NaN')
5176Dec_0 = Decimal(0)
5177Dec_p1 = Decimal(1)
5178Dec_n1 = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005179
Facundo Batista59c58842007-04-10 12:58:45 +00005180# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005181Infsign = (Inf, negInf)
5182
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005183
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005184
5185if __name__ == '__main__':
5186 import doctest, sys
5187 doctest.testmod(sys.modules[__name__])