blob: eea9448f4317eba0e3b0c14b5b880fe73d0c6773 [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
Raymond Hettinger5a053642008-01-24 19:05:29 +00001436 __trunc__ = __int__
1437
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001438 def __long__(self):
1439 """Converts to a long.
1440
1441 Equivalent to long(int(self))
1442 """
1443 return long(self.__int__())
1444
Facundo Batista353750c2007-09-13 18:13:15 +00001445 def _fix_nan(self, context):
1446 """Decapitate the payload of a NaN to fit the context"""
1447 payload = self._int
1448
1449 # maximum length of payload is precision if _clamp=0,
1450 # precision-1 if _clamp=1.
1451 max_payload_len = context.prec - context._clamp
1452 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001453 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1454 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001455 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001456
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001457 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001458 """Round if it is necessary to keep self within prec precision.
1459
1460 Rounds and fixes the exponent. Does not raise on a sNaN.
1461
1462 Arguments:
1463 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001464 context - context used.
1465 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001466
Facundo Batista353750c2007-09-13 18:13:15 +00001467 if self._is_special:
1468 if self._isnan():
1469 # decapitate payload if necessary
1470 return self._fix_nan(context)
1471 else:
1472 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001473 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001474
Facundo Batista353750c2007-09-13 18:13:15 +00001475 # if self is zero then exponent should be between Etiny and
1476 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1477 Etiny = context.Etiny()
1478 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001479 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001480 exp_max = [context.Emax, Etop][context._clamp]
1481 new_exp = min(max(self._exp, Etiny), exp_max)
1482 if new_exp != self._exp:
1483 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001484 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001485 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001486 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001487
1488 # exp_min is the smallest allowable exponent of the result,
1489 # equal to max(self.adjusted()-context.prec+1, Etiny)
1490 exp_min = len(self._int) + self._exp - context.prec
1491 if exp_min > Etop:
1492 # overflow: exp_min > Etop iff self.adjusted() > Emax
1493 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001494 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001495 return context._raise_error(Overflow, 'above Emax', self._sign)
1496 self_is_subnormal = exp_min < Etiny
1497 if self_is_subnormal:
1498 context._raise_error(Subnormal)
1499 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001500
Facundo Batista353750c2007-09-13 18:13:15 +00001501 # round if self has too many digits
1502 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001503 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001504 digits = len(self._int) + self._exp - exp_min
1505 if digits < 0:
1506 self = _dec_from_triple(self._sign, '1', exp_min-1)
1507 digits = 0
1508 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1509 changed = this_function(digits)
1510 coeff = self._int[:digits] or '0'
1511 if changed == 1:
1512 coeff = str(int(coeff)+1)
1513 ans = _dec_from_triple(self._sign, coeff, exp_min)
1514
1515 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001516 context._raise_error(Inexact)
1517 if self_is_subnormal:
1518 context._raise_error(Underflow)
1519 if not ans:
1520 # raise Clamped on underflow to 0
1521 context._raise_error(Clamped)
1522 elif len(ans._int) == context.prec+1:
1523 # we get here only if rescaling rounds the
1524 # cofficient up to exactly 10**context.prec
1525 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001526 ans = _dec_from_triple(ans._sign,
1527 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001528 else:
1529 # Inexact and Rounded have already been raised
1530 ans = context._raise_error(Overflow, 'above Emax',
1531 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001532 return ans
1533
Facundo Batista353750c2007-09-13 18:13:15 +00001534 # fold down if _clamp == 1 and self has too few digits
1535 if context._clamp == 1 and self._exp > Etop:
1536 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001537 self_padded = self._int + '0'*(self._exp - Etop)
1538 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001539
Facundo Batista353750c2007-09-13 18:13:15 +00001540 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001541 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001542
1543 _pick_rounding_function = {}
1544
Facundo Batista353750c2007-09-13 18:13:15 +00001545 # for each of the rounding functions below:
1546 # self is a finite, nonzero Decimal
1547 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001548 #
1549 # each function returns either -1, 0, or 1, as follows:
1550 # 1 indicates that self should be rounded up (away from zero)
1551 # 0 indicates that self should be truncated, and that all the
1552 # digits to be truncated are zeros (so the value is unchanged)
1553 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001554
1555 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001556 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001557 if _all_zeros(self._int, prec):
1558 return 0
1559 else:
1560 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001561
Facundo Batista353750c2007-09-13 18:13:15 +00001562 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001563 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001564 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001565
Facundo Batista353750c2007-09-13 18:13:15 +00001566 def _round_half_up(self, prec):
1567 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001568 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001569 return 1
1570 elif _all_zeros(self._int, prec):
1571 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001572 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001573 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001574
1575 def _round_half_down(self, prec):
1576 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001577 if _exact_half(self._int, prec):
1578 return -1
1579 else:
1580 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001581
1582 def _round_half_even(self, prec):
1583 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001584 if _exact_half(self._int, prec) and \
1585 (prec == 0 or self._int[prec-1] in '02468'):
1586 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001587 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001588 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001589
1590 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001591 """Rounds up (not away from 0 if negative.)"""
1592 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001593 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001594 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001595 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001596
Facundo Batista353750c2007-09-13 18:13:15 +00001597 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001598 """Rounds down (not towards 0 if negative)"""
1599 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001600 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001601 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001602 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001603
Facundo Batista353750c2007-09-13 18:13:15 +00001604 def _round_05up(self, prec):
1605 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001606 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001607 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001608 else:
1609 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001610
Facundo Batista353750c2007-09-13 18:13:15 +00001611 def fma(self, other, third, context=None):
1612 """Fused multiply-add.
1613
1614 Returns self*other+third with no rounding of the intermediate
1615 product self*other.
1616
1617 self and other are multiplied together, with no rounding of
1618 the result. The third operand is then added to the result,
1619 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001620 """
Facundo Batista353750c2007-09-13 18:13:15 +00001621
1622 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001623
1624 # compute product; raise InvalidOperation if either operand is
1625 # a signaling NaN or if the product is zero times infinity.
1626 if self._is_special or other._is_special:
1627 if context is None:
1628 context = getcontext()
1629 if self._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001630 return context._raise_error(InvalidOperation, 'sNaN', self)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001631 if other._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001632 return context._raise_error(InvalidOperation, 'sNaN', other)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001633 if self._exp == 'n':
1634 product = self
1635 elif other._exp == 'n':
1636 product = other
1637 elif self._exp == 'F':
1638 if not other:
1639 return context._raise_error(InvalidOperation,
1640 'INF * 0 in fma')
1641 product = Infsign[self._sign ^ other._sign]
1642 elif other._exp == 'F':
1643 if not self:
1644 return context._raise_error(InvalidOperation,
1645 '0 * INF in fma')
1646 product = Infsign[self._sign ^ other._sign]
1647 else:
1648 product = _dec_from_triple(self._sign ^ other._sign,
1649 str(int(self._int) * int(other._int)),
1650 self._exp + other._exp)
1651
Facundo Batista353750c2007-09-13 18:13:15 +00001652 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001653 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001654
Facundo Batista353750c2007-09-13 18:13:15 +00001655 def _power_modulo(self, other, modulo, context=None):
1656 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001657
Facundo Batista353750c2007-09-13 18:13:15 +00001658 # if can't convert other and modulo to Decimal, raise
1659 # TypeError; there's no point returning NotImplemented (no
1660 # equivalent of __rpow__ for three argument pow)
1661 other = _convert_other(other, raiseit=True)
1662 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001663
Facundo Batista353750c2007-09-13 18:13:15 +00001664 if context is None:
1665 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001666
Facundo Batista353750c2007-09-13 18:13:15 +00001667 # deal with NaNs: if there are any sNaNs then first one wins,
1668 # (i.e. behaviour for NaNs is identical to that of fma)
1669 self_is_nan = self._isnan()
1670 other_is_nan = other._isnan()
1671 modulo_is_nan = modulo._isnan()
1672 if self_is_nan or other_is_nan or modulo_is_nan:
1673 if self_is_nan == 2:
1674 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001675 self)
Facundo Batista353750c2007-09-13 18:13:15 +00001676 if other_is_nan == 2:
1677 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001678 other)
Facundo Batista353750c2007-09-13 18:13:15 +00001679 if modulo_is_nan == 2:
1680 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001681 modulo)
Facundo Batista353750c2007-09-13 18:13:15 +00001682 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001683 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001684 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001685 return other._fix_nan(context)
1686 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001687
Facundo Batista353750c2007-09-13 18:13:15 +00001688 # check inputs: we apply same restrictions as Python's pow()
1689 if not (self._isinteger() and
1690 other._isinteger() and
1691 modulo._isinteger()):
1692 return context._raise_error(InvalidOperation,
1693 'pow() 3rd argument not allowed '
1694 'unless all arguments are integers')
1695 if other < 0:
1696 return context._raise_error(InvalidOperation,
1697 'pow() 2nd argument cannot be '
1698 'negative when 3rd argument specified')
1699 if not modulo:
1700 return context._raise_error(InvalidOperation,
1701 'pow() 3rd argument cannot be 0')
1702
1703 # additional restriction for decimal: the modulus must be less
1704 # than 10**prec in absolute value
1705 if modulo.adjusted() >= context.prec:
1706 return context._raise_error(InvalidOperation,
1707 'insufficient precision: pow() 3rd '
1708 'argument must not have more than '
1709 'precision digits')
1710
1711 # define 0**0 == NaN, for consistency with two-argument pow
1712 # (even though it hurts!)
1713 if not other and not self:
1714 return context._raise_error(InvalidOperation,
1715 'at least one of pow() 1st argument '
1716 'and 2nd argument must be nonzero ;'
1717 '0**0 is not defined')
1718
1719 # compute sign of result
1720 if other._iseven():
1721 sign = 0
1722 else:
1723 sign = self._sign
1724
1725 # convert modulo to a Python integer, and self and other to
1726 # Decimal integers (i.e. force their exponents to be >= 0)
1727 modulo = abs(int(modulo))
1728 base = _WorkRep(self.to_integral_value())
1729 exponent = _WorkRep(other.to_integral_value())
1730
1731 # compute result using integer pow()
1732 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1733 for i in xrange(exponent.exp):
1734 base = pow(base, 10, modulo)
1735 base = pow(base, exponent.int, modulo)
1736
Facundo Batista72bc54f2007-11-23 17:59:00 +00001737 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001738
1739 def _power_exact(self, other, p):
1740 """Attempt to compute self**other exactly.
1741
1742 Given Decimals self and other and an integer p, attempt to
1743 compute an exact result for the power self**other, with p
1744 digits of precision. Return None if self**other is not
1745 exactly representable in p digits.
1746
1747 Assumes that elimination of special cases has already been
1748 performed: self and other must both be nonspecial; self must
1749 be positive and not numerically equal to 1; other must be
1750 nonzero. For efficiency, other._exp should not be too large,
1751 so that 10**abs(other._exp) is a feasible calculation."""
1752
1753 # In the comments below, we write x for the value of self and
1754 # y for the value of other. Write x = xc*10**xe and y =
1755 # yc*10**ye.
1756
1757 # The main purpose of this method is to identify the *failure*
1758 # of x**y to be exactly representable with as little effort as
1759 # possible. So we look for cheap and easy tests that
1760 # eliminate the possibility of x**y being exact. Only if all
1761 # these tests are passed do we go on to actually compute x**y.
1762
1763 # Here's the main idea. First normalize both x and y. We
1764 # express y as a rational m/n, with m and n relatively prime
1765 # and n>0. Then for x**y to be exactly representable (at
1766 # *any* precision), xc must be the nth power of a positive
1767 # integer and xe must be divisible by n. If m is negative
1768 # then additionally xc must be a power of either 2 or 5, hence
1769 # a power of 2**n or 5**n.
1770 #
1771 # There's a limit to how small |y| can be: if y=m/n as above
1772 # then:
1773 #
1774 # (1) if xc != 1 then for the result to be representable we
1775 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1776 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1777 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1778 # representable.
1779 #
1780 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1781 # |y| < 1/|xe| then the result is not representable.
1782 #
1783 # Note that since x is not equal to 1, at least one of (1) and
1784 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1785 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1786 #
1787 # There's also a limit to how large y can be, at least if it's
1788 # positive: the normalized result will have coefficient xc**y,
1789 # so if it's representable then xc**y < 10**p, and y <
1790 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1791 # not exactly representable.
1792
1793 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1794 # so |y| < 1/xe and the result is not representable.
1795 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1796 # < 1/nbits(xc).
1797
1798 x = _WorkRep(self)
1799 xc, xe = x.int, x.exp
1800 while xc % 10 == 0:
1801 xc //= 10
1802 xe += 1
1803
1804 y = _WorkRep(other)
1805 yc, ye = y.int, y.exp
1806 while yc % 10 == 0:
1807 yc //= 10
1808 ye += 1
1809
1810 # case where xc == 1: result is 10**(xe*y), with xe*y
1811 # required to be an integer
1812 if xc == 1:
1813 if ye >= 0:
1814 exponent = xe*yc*10**ye
1815 else:
1816 exponent, remainder = divmod(xe*yc, 10**-ye)
1817 if remainder:
1818 return None
1819 if y.sign == 1:
1820 exponent = -exponent
1821 # if other is a nonnegative integer, use ideal exponent
1822 if other._isinteger() and other._sign == 0:
1823 ideal_exponent = self._exp*int(other)
1824 zeros = min(exponent-ideal_exponent, p-1)
1825 else:
1826 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001827 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001828
1829 # case where y is negative: xc must be either a power
1830 # of 2 or a power of 5.
1831 if y.sign == 1:
1832 last_digit = xc % 10
1833 if last_digit in (2,4,6,8):
1834 # quick test for power of 2
1835 if xc & -xc != xc:
1836 return None
1837 # now xc is a power of 2; e is its exponent
1838 e = _nbits(xc)-1
1839 # find e*y and xe*y; both must be integers
1840 if ye >= 0:
1841 y_as_int = yc*10**ye
1842 e = e*y_as_int
1843 xe = xe*y_as_int
1844 else:
1845 ten_pow = 10**-ye
1846 e, remainder = divmod(e*yc, ten_pow)
1847 if remainder:
1848 return None
1849 xe, remainder = divmod(xe*yc, ten_pow)
1850 if remainder:
1851 return None
1852
1853 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1854 return None
1855 xc = 5**e
1856
1857 elif last_digit == 5:
1858 # e >= log_5(xc) if xc is a power of 5; we have
1859 # equality all the way up to xc=5**2658
1860 e = _nbits(xc)*28//65
1861 xc, remainder = divmod(5**e, xc)
1862 if remainder:
1863 return None
1864 while xc % 5 == 0:
1865 xc //= 5
1866 e -= 1
1867 if ye >= 0:
1868 y_as_integer = yc*10**ye
1869 e = e*y_as_integer
1870 xe = xe*y_as_integer
1871 else:
1872 ten_pow = 10**-ye
1873 e, remainder = divmod(e*yc, ten_pow)
1874 if remainder:
1875 return None
1876 xe, remainder = divmod(xe*yc, ten_pow)
1877 if remainder:
1878 return None
1879 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1880 return None
1881 xc = 2**e
1882 else:
1883 return None
1884
1885 if xc >= 10**p:
1886 return None
1887 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00001888 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00001889
1890 # now y is positive; find m and n such that y = m/n
1891 if ye >= 0:
1892 m, n = yc*10**ye, 1
1893 else:
1894 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1895 return None
1896 xc_bits = _nbits(xc)
1897 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1898 return None
1899 m, n = yc, 10**(-ye)
1900 while m % 2 == n % 2 == 0:
1901 m //= 2
1902 n //= 2
1903 while m % 5 == n % 5 == 0:
1904 m //= 5
1905 n //= 5
1906
1907 # compute nth root of xc*10**xe
1908 if n > 1:
1909 # if 1 < xc < 2**n then xc isn't an nth power
1910 if xc != 1 and xc_bits <= n:
1911 return None
1912
1913 xe, rem = divmod(xe, n)
1914 if rem != 0:
1915 return None
1916
1917 # compute nth root of xc using Newton's method
1918 a = 1L << -(-_nbits(xc)//n) # initial estimate
1919 while True:
1920 q, r = divmod(xc, a**(n-1))
1921 if a <= q:
1922 break
1923 else:
1924 a = (a*(n-1) + q)//n
1925 if not (a == q and r == 0):
1926 return None
1927 xc = a
1928
1929 # now xc*10**xe is the nth root of the original xc*10**xe
1930 # compute mth power of xc*10**xe
1931
1932 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1933 # 10**p and the result is not representable.
1934 if xc > 1 and m > p*100//_log10_lb(xc):
1935 return None
1936 xc = xc**m
1937 xe *= m
1938 if xc > 10**p:
1939 return None
1940
1941 # by this point the result *is* exactly representable
1942 # adjust the exponent to get as close as possible to the ideal
1943 # exponent, if necessary
1944 str_xc = str(xc)
1945 if other._isinteger() and other._sign == 0:
1946 ideal_exponent = self._exp*int(other)
1947 zeros = min(xe-ideal_exponent, p-len(str_xc))
1948 else:
1949 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001950 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001951
1952 def __pow__(self, other, modulo=None, context=None):
1953 """Return self ** other [ % modulo].
1954
1955 With two arguments, compute self**other.
1956
1957 With three arguments, compute (self**other) % modulo. For the
1958 three argument form, the following restrictions on the
1959 arguments hold:
1960
1961 - all three arguments must be integral
1962 - other must be nonnegative
1963 - either self or other (or both) must be nonzero
1964 - modulo must be nonzero and must have at most p digits,
1965 where p is the context precision.
1966
1967 If any of these restrictions is violated the InvalidOperation
1968 flag is raised.
1969
1970 The result of pow(self, other, modulo) is identical to the
1971 result that would be obtained by computing (self**other) %
1972 modulo with unbounded precision, but is computed more
1973 efficiently. It is always exact.
1974 """
1975
1976 if modulo is not None:
1977 return self._power_modulo(other, modulo, context)
1978
1979 other = _convert_other(other)
1980 if other is NotImplemented:
1981 return other
1982
1983 if context is None:
1984 context = getcontext()
1985
1986 # either argument is a NaN => result is NaN
1987 ans = self._check_nans(other, context)
1988 if ans:
1989 return ans
1990
1991 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1992 if not other:
1993 if not self:
1994 return context._raise_error(InvalidOperation, '0 ** 0')
1995 else:
1996 return Dec_p1
1997
1998 # result has sign 1 iff self._sign is 1 and other is an odd integer
1999 result_sign = 0
2000 if self._sign == 1:
2001 if other._isinteger():
2002 if not other._iseven():
2003 result_sign = 1
2004 else:
2005 # -ve**noninteger = NaN
2006 # (-0)**noninteger = 0**noninteger
2007 if self:
2008 return context._raise_error(InvalidOperation,
2009 'x ** y with x negative and y not an integer')
2010 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002011 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002012
2013 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2014 if not self:
2015 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002016 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002017 else:
2018 return Infsign[result_sign]
2019
2020 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002021 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002022 if other._sign == 0:
2023 return Infsign[result_sign]
2024 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002025 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002026
Facundo Batista353750c2007-09-13 18:13:15 +00002027 # 1**other = 1, but the choice of exponent and the flags
2028 # depend on the exponent of self, and on whether other is a
2029 # positive integer, a negative integer, or neither
2030 if self == Dec_p1:
2031 if other._isinteger():
2032 # exp = max(self._exp*max(int(other), 0),
2033 # 1-context.prec) but evaluating int(other) directly
2034 # is dangerous until we know other is small (other
2035 # could be 1e999999999)
2036 if other._sign == 1:
2037 multiplier = 0
2038 elif other > context.prec:
2039 multiplier = context.prec
2040 else:
2041 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002042
Facundo Batista353750c2007-09-13 18:13:15 +00002043 exp = self._exp * multiplier
2044 if exp < 1-context.prec:
2045 exp = 1-context.prec
2046 context._raise_error(Rounded)
2047 else:
2048 context._raise_error(Inexact)
2049 context._raise_error(Rounded)
2050 exp = 1-context.prec
2051
Facundo Batista72bc54f2007-11-23 17:59:00 +00002052 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002053
2054 # compute adjusted exponent of self
2055 self_adj = self.adjusted()
2056
2057 # self ** infinity is infinity if self > 1, 0 if self < 1
2058 # self ** -infinity is infinity if self < 1, 0 if self > 1
2059 if other._isinfinity():
2060 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002061 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002062 else:
2063 return Infsign[result_sign]
2064
2065 # from here on, the result always goes through the call
2066 # to _fix at the end of this function.
2067 ans = None
2068
2069 # crude test to catch cases of extreme overflow/underflow. If
2070 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2071 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2072 # self**other >= 10**(Emax+1), so overflow occurs. The test
2073 # for underflow is similar.
2074 bound = self._log10_exp_bound() + other.adjusted()
2075 if (self_adj >= 0) == (other._sign == 0):
2076 # self > 1 and other +ve, or self < 1 and other -ve
2077 # possibility of overflow
2078 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002079 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002080 else:
2081 # self > 1 and other -ve, or self < 1 and other +ve
2082 # possibility of underflow to 0
2083 Etiny = context.Etiny()
2084 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002085 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002086
2087 # try for an exact result with precision +1
2088 if ans is None:
2089 ans = self._power_exact(other, context.prec + 1)
2090 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002091 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002092
2093 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2094 if ans is None:
2095 p = context.prec
2096 x = _WorkRep(self)
2097 xc, xe = x.int, x.exp
2098 y = _WorkRep(other)
2099 yc, ye = y.int, y.exp
2100 if y.sign == 1:
2101 yc = -yc
2102
2103 # compute correctly rounded result: start with precision +3,
2104 # then increase precision until result is unambiguously roundable
2105 extra = 3
2106 while True:
2107 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2108 if coeff % (5*10**(len(str(coeff))-p-1)):
2109 break
2110 extra += 3
2111
Facundo Batista72bc54f2007-11-23 17:59:00 +00002112 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002113
2114 # the specification says that for non-integer other we need to
2115 # raise Inexact, even when the result is actually exact. In
2116 # the same way, we need to raise Underflow here if the result
2117 # is subnormal. (The call to _fix will take care of raising
2118 # Rounded and Subnormal, as usual.)
2119 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002120 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002121 # pad with zeros up to length context.prec+1 if necessary
2122 if len(ans._int) <= context.prec:
2123 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002124 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2125 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002126 if ans.adjusted() < context.Emin:
2127 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002128
Facundo Batista353750c2007-09-13 18:13:15 +00002129 # unlike exp, ln and log10, the power function respects the
2130 # rounding mode; no need to use ROUND_HALF_EVEN here
2131 ans = ans._fix(context)
2132 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002133
2134 def __rpow__(self, other, context=None):
2135 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002136 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002137 if other is NotImplemented:
2138 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002139 return other.__pow__(self, context=context)
2140
2141 def normalize(self, context=None):
2142 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002143
Facundo Batista353750c2007-09-13 18:13:15 +00002144 if context is None:
2145 context = getcontext()
2146
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002147 if self._is_special:
2148 ans = self._check_nans(context=context)
2149 if ans:
2150 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002151
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002152 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002153 if dup._isinfinity():
2154 return dup
2155
2156 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002157 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002158 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002159 end = len(dup._int)
2160 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002161 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002162 exp += 1
2163 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002164 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002165
Facundo Batistabd2fe832007-09-13 18:42:09 +00002166 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002167 """Quantize self so its exponent is the same as that of exp.
2168
2169 Similar to self._rescale(exp._exp) but with error checking.
2170 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002171 exp = _convert_other(exp, raiseit=True)
2172
Facundo Batista353750c2007-09-13 18:13:15 +00002173 if context is None:
2174 context = getcontext()
2175 if rounding is None:
2176 rounding = context.rounding
2177
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002178 if self._is_special or exp._is_special:
2179 ans = self._check_nans(exp, context)
2180 if ans:
2181 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002182
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002183 if exp._isinfinity() or self._isinfinity():
2184 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002185 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002186 return context._raise_error(InvalidOperation,
2187 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002188
Facundo Batistabd2fe832007-09-13 18:42:09 +00002189 # if we're not watching exponents, do a simple rescale
2190 if not watchexp:
2191 ans = self._rescale(exp._exp, rounding)
2192 # raise Inexact and Rounded where appropriate
2193 if ans._exp > self._exp:
2194 context._raise_error(Rounded)
2195 if ans != self:
2196 context._raise_error(Inexact)
2197 return ans
2198
Facundo Batista353750c2007-09-13 18:13:15 +00002199 # exp._exp should be between Etiny and Emax
2200 if not (context.Etiny() <= exp._exp <= context.Emax):
2201 return context._raise_error(InvalidOperation,
2202 'target exponent out of bounds in quantize')
2203
2204 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002205 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002206 return ans._fix(context)
2207
2208 self_adjusted = self.adjusted()
2209 if self_adjusted > context.Emax:
2210 return context._raise_error(InvalidOperation,
2211 'exponent of quantize result too large for current context')
2212 if self_adjusted - exp._exp + 1 > context.prec:
2213 return context._raise_error(InvalidOperation,
2214 'quantize result has too many digits for current context')
2215
2216 ans = self._rescale(exp._exp, rounding)
2217 if ans.adjusted() > context.Emax:
2218 return context._raise_error(InvalidOperation,
2219 'exponent of quantize result too large for current context')
2220 if len(ans._int) > context.prec:
2221 return context._raise_error(InvalidOperation,
2222 'quantize result has too many digits for current context')
2223
2224 # raise appropriate flags
2225 if ans._exp > self._exp:
2226 context._raise_error(Rounded)
2227 if ans != self:
2228 context._raise_error(Inexact)
2229 if ans and ans.adjusted() < context.Emin:
2230 context._raise_error(Subnormal)
2231
2232 # call to fix takes care of any necessary folddown
2233 ans = ans._fix(context)
2234 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002235
2236 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002237 """Return True if self and other have the same exponent; otherwise
2238 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002239
Facundo Batista1a191df2007-10-02 17:01:24 +00002240 If either operand is a special value, the following rules are used:
2241 * return True if both operands are infinities
2242 * return True if both operands are NaNs
2243 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002244 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002245 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002246 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002247 return (self.is_nan() and other.is_nan() or
2248 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002249 return self._exp == other._exp
2250
Facundo Batista353750c2007-09-13 18:13:15 +00002251 def _rescale(self, exp, rounding):
2252 """Rescale self so that the exponent is exp, either by padding with zeros
2253 or by truncating digits, using the given rounding mode.
2254
2255 Specials are returned without change. This operation is
2256 quiet: it raises no flags, and uses no information from the
2257 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002258
2259 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002260 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002261 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002262 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002263 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002264 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002265 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002266
Facundo Batista353750c2007-09-13 18:13:15 +00002267 if self._exp >= exp:
2268 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002269 return _dec_from_triple(self._sign,
2270 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002271
Facundo Batista353750c2007-09-13 18:13:15 +00002272 # too many digits; round and lose data. If self.adjusted() <
2273 # exp-1, replace self by 10**(exp-1) before rounding
2274 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002275 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002276 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002277 digits = 0
2278 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002279 changed = this_function(digits)
2280 coeff = self._int[:digits] or '0'
2281 if changed == 1:
2282 coeff = str(int(coeff)+1)
2283 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002284
Facundo Batista353750c2007-09-13 18:13:15 +00002285 def to_integral_exact(self, rounding=None, context=None):
2286 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002287
Facundo Batista353750c2007-09-13 18:13:15 +00002288 If no rounding mode is specified, take the rounding mode from
2289 the context. This method raises the Rounded and Inexact flags
2290 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002291
Facundo Batista353750c2007-09-13 18:13:15 +00002292 See also: to_integral_value, which does exactly the same as
2293 this method except that it doesn't raise Inexact or Rounded.
2294 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002295 if self._is_special:
2296 ans = self._check_nans(context=context)
2297 if ans:
2298 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002299 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002300 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002301 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002302 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002303 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002304 if context is None:
2305 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002306 if rounding is None:
2307 rounding = context.rounding
2308 context._raise_error(Rounded)
2309 ans = self._rescale(0, rounding)
2310 if ans != self:
2311 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002312 return ans
2313
Facundo Batista353750c2007-09-13 18:13:15 +00002314 def to_integral_value(self, rounding=None, context=None):
2315 """Rounds to the nearest integer, without raising inexact, rounded."""
2316 if context is None:
2317 context = getcontext()
2318 if rounding is None:
2319 rounding = context.rounding
2320 if self._is_special:
2321 ans = self._check_nans(context=context)
2322 if ans:
2323 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002324 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002325 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002326 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002327 else:
2328 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002329
Facundo Batista353750c2007-09-13 18:13:15 +00002330 # the method name changed, but we provide also the old one, for compatibility
2331 to_integral = to_integral_value
2332
2333 def sqrt(self, context=None):
2334 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002335 if self._is_special:
2336 ans = self._check_nans(context=context)
2337 if ans:
2338 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002339
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002340 if self._isinfinity() and self._sign == 0:
2341 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002342
2343 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002344 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002345 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002346 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002347
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002348 if context is None:
2349 context = getcontext()
2350
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002351 if self._sign == 1:
2352 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2353
Facundo Batista353750c2007-09-13 18:13:15 +00002354 # At this point self represents a positive number. Let p be
2355 # the desired precision and express self in the form c*100**e
2356 # with c a positive real number and e an integer, c and e
2357 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2358 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2359 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2360 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2361 # the closest integer to sqrt(c) with the even integer chosen
2362 # in the case of a tie.
2363 #
2364 # To ensure correct rounding in all cases, we use the
2365 # following trick: we compute the square root to an extra
2366 # place (precision p+1 instead of precision p), rounding down.
2367 # Then, if the result is inexact and its last digit is 0 or 5,
2368 # we increase the last digit to 1 or 6 respectively; if it's
2369 # exact we leave the last digit alone. Now the final round to
2370 # p places (or fewer in the case of underflow) will round
2371 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002372
Facundo Batista353750c2007-09-13 18:13:15 +00002373 # use an extra digit of precision
2374 prec = context.prec+1
2375
2376 # write argument in the form c*100**e where e = self._exp//2
2377 # is the 'ideal' exponent, to be used if the square root is
2378 # exactly representable. l is the number of 'digits' of c in
2379 # base 100, so that 100**(l-1) <= c < 100**l.
2380 op = _WorkRep(self)
2381 e = op.exp >> 1
2382 if op.exp & 1:
2383 c = op.int * 10
2384 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002385 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002386 c = op.int
2387 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002388
Facundo Batista353750c2007-09-13 18:13:15 +00002389 # rescale so that c has exactly prec base 100 'digits'
2390 shift = prec-l
2391 if shift >= 0:
2392 c *= 100**shift
2393 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002394 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002395 c, remainder = divmod(c, 100**-shift)
2396 exact = not remainder
2397 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002398
Facundo Batista353750c2007-09-13 18:13:15 +00002399 # find n = floor(sqrt(c)) using Newton's method
2400 n = 10**prec
2401 while True:
2402 q = c//n
2403 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002404 break
Facundo Batista353750c2007-09-13 18:13:15 +00002405 else:
2406 n = n + q >> 1
2407 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002408
Facundo Batista353750c2007-09-13 18:13:15 +00002409 if exact:
2410 # result is exact; rescale to use ideal exponent e
2411 if shift >= 0:
2412 # assert n % 10**shift == 0
2413 n //= 10**shift
2414 else:
2415 n *= 10**-shift
2416 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002417 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002418 # result is not exact; fix last digit as described above
2419 if n % 5 == 0:
2420 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002421
Facundo Batista72bc54f2007-11-23 17:59:00 +00002422 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002423
Facundo Batista353750c2007-09-13 18:13:15 +00002424 # round, and fit to current context
2425 context = context._shallow_copy()
2426 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002427 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002428 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002429
Facundo Batista353750c2007-09-13 18:13:15 +00002430 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002431
2432 def max(self, other, context=None):
2433 """Returns the larger value.
2434
Facundo Batista353750c2007-09-13 18:13:15 +00002435 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002436 NaN (and signals if one is sNaN). Also rounds.
2437 """
Facundo Batista353750c2007-09-13 18:13:15 +00002438 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002439
Facundo Batista6c398da2007-09-17 17:30:13 +00002440 if context is None:
2441 context = getcontext()
2442
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002443 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002444 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002445 # number is always returned
2446 sn = self._isnan()
2447 on = other._isnan()
2448 if sn or on:
2449 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002450 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002451 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002452 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002453 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002454
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002455 c = self.__cmp__(other)
2456 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002457 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002458 # then an ordering is applied:
2459 #
Facundo Batista59c58842007-04-10 12:58:45 +00002460 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002461 # positive sign and min returns the operand with the negative sign
2462 #
Facundo Batista59c58842007-04-10 12:58:45 +00002463 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002464 # the result. This is exactly the ordering used in compare_total.
2465 c = self.compare_total(other)
2466
2467 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002468 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002469 else:
2470 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002471
Facundo Batistae64acfa2007-12-17 14:18:42 +00002472 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002473
2474 def min(self, other, context=None):
2475 """Returns the smaller value.
2476
Facundo Batista59c58842007-04-10 12:58:45 +00002477 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002478 NaN (and signals if one is sNaN). Also rounds.
2479 """
Facundo Batista353750c2007-09-13 18:13:15 +00002480 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002481
Facundo Batista6c398da2007-09-17 17:30:13 +00002482 if context is None:
2483 context = getcontext()
2484
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002485 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002486 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002487 # number is always returned
2488 sn = self._isnan()
2489 on = other._isnan()
2490 if sn or on:
2491 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002492 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002493 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002494 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002495 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002496
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002497 c = self.__cmp__(other)
2498 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002499 c = self.compare_total(other)
2500
2501 if c == -1:
2502 ans = self
2503 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002504 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002505
Facundo Batistae64acfa2007-12-17 14:18:42 +00002506 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002507
2508 def _isinteger(self):
2509 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002510 if self._is_special:
2511 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002512 if self._exp >= 0:
2513 return True
2514 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002515 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002516
2517 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002518 """Returns True if self is even. Assumes self is an integer."""
2519 if not self or self._exp > 0:
2520 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002521 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002522
2523 def adjusted(self):
2524 """Return the adjusted exponent of self"""
2525 try:
2526 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002527 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002528 except TypeError:
2529 return 0
2530
Facundo Batista353750c2007-09-13 18:13:15 +00002531 def canonical(self, context=None):
2532 """Returns the same Decimal object.
2533
2534 As we do not have different encodings for the same number, the
2535 received object already is in its canonical form.
2536 """
2537 return self
2538
2539 def compare_signal(self, other, context=None):
2540 """Compares self to the other operand numerically.
2541
2542 It's pretty much like compare(), but all NaNs signal, with signaling
2543 NaNs taking precedence over quiet NaNs.
2544 """
2545 if context is None:
2546 context = getcontext()
2547
2548 self_is_nan = self._isnan()
2549 other_is_nan = other._isnan()
2550 if self_is_nan == 2:
2551 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002552 self)
Facundo Batista353750c2007-09-13 18:13:15 +00002553 if other_is_nan == 2:
2554 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002555 other)
Facundo Batista353750c2007-09-13 18:13:15 +00002556 if self_is_nan:
2557 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002558 self)
Facundo Batista353750c2007-09-13 18:13:15 +00002559 if other_is_nan:
2560 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002561 other)
Facundo Batista353750c2007-09-13 18:13:15 +00002562 return self.compare(other, context=context)
2563
2564 def compare_total(self, other):
2565 """Compares self to other using the abstract representations.
2566
2567 This is not like the standard compare, which use their numerical
2568 value. Note that a total ordering is defined for all possible abstract
2569 representations.
2570 """
2571 # if one is negative and the other is positive, it's easy
2572 if self._sign and not other._sign:
2573 return Dec_n1
2574 if not self._sign and other._sign:
2575 return Dec_p1
2576 sign = self._sign
2577
2578 # let's handle both NaN types
2579 self_nan = self._isnan()
2580 other_nan = other._isnan()
2581 if self_nan or other_nan:
2582 if self_nan == other_nan:
2583 if self._int < other._int:
2584 if sign:
2585 return Dec_p1
2586 else:
2587 return Dec_n1
2588 if self._int > other._int:
2589 if sign:
2590 return Dec_n1
2591 else:
2592 return Dec_p1
2593 return Dec_0
2594
2595 if sign:
2596 if self_nan == 1:
2597 return Dec_n1
2598 if other_nan == 1:
2599 return Dec_p1
2600 if self_nan == 2:
2601 return Dec_n1
2602 if other_nan == 2:
2603 return Dec_p1
2604 else:
2605 if self_nan == 1:
2606 return Dec_p1
2607 if other_nan == 1:
2608 return Dec_n1
2609 if self_nan == 2:
2610 return Dec_p1
2611 if other_nan == 2:
2612 return Dec_n1
2613
2614 if self < other:
2615 return Dec_n1
2616 if self > other:
2617 return Dec_p1
2618
2619 if self._exp < other._exp:
2620 if sign:
2621 return Dec_p1
2622 else:
2623 return Dec_n1
2624 if self._exp > other._exp:
2625 if sign:
2626 return Dec_n1
2627 else:
2628 return Dec_p1
2629 return Dec_0
2630
2631
2632 def compare_total_mag(self, other):
2633 """Compares self to other using abstract repr., ignoring sign.
2634
2635 Like compare_total, but with operand's sign ignored and assumed to be 0.
2636 """
2637 s = self.copy_abs()
2638 o = other.copy_abs()
2639 return s.compare_total(o)
2640
2641 def copy_abs(self):
2642 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002643 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002644
2645 def copy_negate(self):
2646 """Returns a copy with the sign inverted."""
2647 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002648 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002649 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002650 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002651
2652 def copy_sign(self, other):
2653 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002654 return _dec_from_triple(other._sign, self._int,
2655 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002656
2657 def exp(self, context=None):
2658 """Returns e ** self."""
2659
2660 if context is None:
2661 context = getcontext()
2662
2663 # exp(NaN) = NaN
2664 ans = self._check_nans(context=context)
2665 if ans:
2666 return ans
2667
2668 # exp(-Infinity) = 0
2669 if self._isinfinity() == -1:
2670 return Dec_0
2671
2672 # exp(0) = 1
2673 if not self:
2674 return Dec_p1
2675
2676 # exp(Infinity) = Infinity
2677 if self._isinfinity() == 1:
2678 return Decimal(self)
2679
2680 # the result is now guaranteed to be inexact (the true
2681 # mathematical result is transcendental). There's no need to
2682 # raise Rounded and Inexact here---they'll always be raised as
2683 # a result of the call to _fix.
2684 p = context.prec
2685 adj = self.adjusted()
2686
2687 # we only need to do any computation for quite a small range
2688 # of adjusted exponents---for example, -29 <= adj <= 10 for
2689 # the default context. For smaller exponent the result is
2690 # indistinguishable from 1 at the given precision, while for
2691 # larger exponent the result either overflows or underflows.
2692 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2693 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002694 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002695 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2696 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002697 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002698 elif self._sign == 0 and adj < -p:
2699 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002700 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002701 elif self._sign == 1 and adj < -p-1:
2702 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002703 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002704 # general case
2705 else:
2706 op = _WorkRep(self)
2707 c, e = op.int, op.exp
2708 if op.sign == 1:
2709 c = -c
2710
2711 # compute correctly rounded result: increase precision by
2712 # 3 digits at a time until we get an unambiguously
2713 # roundable result
2714 extra = 3
2715 while True:
2716 coeff, exp = _dexp(c, e, p+extra)
2717 if coeff % (5*10**(len(str(coeff))-p-1)):
2718 break
2719 extra += 3
2720
Facundo Batista72bc54f2007-11-23 17:59:00 +00002721 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002722
2723 # at this stage, ans should round correctly with *any*
2724 # rounding mode, not just with ROUND_HALF_EVEN
2725 context = context._shallow_copy()
2726 rounding = context._set_rounding(ROUND_HALF_EVEN)
2727 ans = ans._fix(context)
2728 context.rounding = rounding
2729
2730 return ans
2731
2732 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002733 """Return True if self is canonical; otherwise return False.
2734
2735 Currently, the encoding of a Decimal instance is always
2736 canonical, so this method returns True for any Decimal.
2737 """
2738 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002739
2740 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002741 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002742
Facundo Batista1a191df2007-10-02 17:01:24 +00002743 A Decimal instance is considered finite if it is neither
2744 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002745 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002746 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002747
2748 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002749 """Return True if self is infinite; otherwise return False."""
2750 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002751
2752 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002753 """Return True if self is a qNaN or sNaN; otherwise return False."""
2754 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002755
2756 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002757 """Return True if self is a normal number; otherwise return False."""
2758 if self._is_special or not self:
2759 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002760 if context is None:
2761 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002762 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002763
2764 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002765 """Return True if self is a quiet NaN; otherwise return False."""
2766 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002767
2768 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002769 """Return True if self is negative; otherwise return False."""
2770 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002771
2772 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002773 """Return True if self is a signaling NaN; otherwise return False."""
2774 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002775
2776 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002777 """Return True if self is subnormal; otherwise return False."""
2778 if self._is_special or not self:
2779 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002780 if context is None:
2781 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002782 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002783
2784 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002785 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002786 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002787
2788 def _ln_exp_bound(self):
2789 """Compute a lower bound for the adjusted exponent of self.ln().
2790 In other words, compute r such that self.ln() >= 10**r. Assumes
2791 that self is finite and positive and that self != 1.
2792 """
2793
2794 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2795 adj = self._exp + len(self._int) - 1
2796 if adj >= 1:
2797 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2798 return len(str(adj*23//10)) - 1
2799 if adj <= -2:
2800 # argument <= 0.1
2801 return len(str((-1-adj)*23//10)) - 1
2802 op = _WorkRep(self)
2803 c, e = op.int, op.exp
2804 if adj == 0:
2805 # 1 < self < 10
2806 num = str(c-10**-e)
2807 den = str(c)
2808 return len(num) - len(den) - (num < den)
2809 # adj == -1, 0.1 <= self < 1
2810 return e + len(str(10**-e - c)) - 1
2811
2812
2813 def ln(self, context=None):
2814 """Returns the natural (base e) logarithm of self."""
2815
2816 if context is None:
2817 context = getcontext()
2818
2819 # ln(NaN) = NaN
2820 ans = self._check_nans(context=context)
2821 if ans:
2822 return ans
2823
2824 # ln(0.0) == -Infinity
2825 if not self:
2826 return negInf
2827
2828 # ln(Infinity) = Infinity
2829 if self._isinfinity() == 1:
2830 return Inf
2831
2832 # ln(1.0) == 0.0
2833 if self == Dec_p1:
2834 return Dec_0
2835
2836 # ln(negative) raises InvalidOperation
2837 if self._sign == 1:
2838 return context._raise_error(InvalidOperation,
2839 'ln of a negative value')
2840
2841 # result is irrational, so necessarily inexact
2842 op = _WorkRep(self)
2843 c, e = op.int, op.exp
2844 p = context.prec
2845
2846 # correctly rounded result: repeatedly increase precision by 3
2847 # until we get an unambiguously roundable result
2848 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2849 while True:
2850 coeff = _dlog(c, e, places)
2851 # assert len(str(abs(coeff)))-p >= 1
2852 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2853 break
2854 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002855 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002856
2857 context = context._shallow_copy()
2858 rounding = context._set_rounding(ROUND_HALF_EVEN)
2859 ans = ans._fix(context)
2860 context.rounding = rounding
2861 return ans
2862
2863 def _log10_exp_bound(self):
2864 """Compute a lower bound for the adjusted exponent of self.log10().
2865 In other words, find r such that self.log10() >= 10**r.
2866 Assumes that self is finite and positive and that self != 1.
2867 """
2868
2869 # For x >= 10 or x < 0.1 we only need a bound on the integer
2870 # part of log10(self), and this comes directly from the
2871 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2872 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2873 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2874
2875 adj = self._exp + len(self._int) - 1
2876 if adj >= 1:
2877 # self >= 10
2878 return len(str(adj))-1
2879 if adj <= -2:
2880 # self < 0.1
2881 return len(str(-1-adj))-1
2882 op = _WorkRep(self)
2883 c, e = op.int, op.exp
2884 if adj == 0:
2885 # 1 < self < 10
2886 num = str(c-10**-e)
2887 den = str(231*c)
2888 return len(num) - len(den) - (num < den) + 2
2889 # adj == -1, 0.1 <= self < 1
2890 num = str(10**-e-c)
2891 return len(num) + e - (num < "231") - 1
2892
2893 def log10(self, context=None):
2894 """Returns the base 10 logarithm of self."""
2895
2896 if context is None:
2897 context = getcontext()
2898
2899 # log10(NaN) = NaN
2900 ans = self._check_nans(context=context)
2901 if ans:
2902 return ans
2903
2904 # log10(0.0) == -Infinity
2905 if not self:
2906 return negInf
2907
2908 # log10(Infinity) = Infinity
2909 if self._isinfinity() == 1:
2910 return Inf
2911
2912 # log10(negative or -Infinity) raises InvalidOperation
2913 if self._sign == 1:
2914 return context._raise_error(InvalidOperation,
2915 'log10 of a negative value')
2916
2917 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00002918 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00002919 # answer may need rounding
2920 ans = Decimal(self._exp + len(self._int) - 1)
2921 else:
2922 # result is irrational, so necessarily inexact
2923 op = _WorkRep(self)
2924 c, e = op.int, op.exp
2925 p = context.prec
2926
2927 # correctly rounded result: repeatedly increase precision
2928 # until result is unambiguously roundable
2929 places = p-self._log10_exp_bound()+2
2930 while True:
2931 coeff = _dlog10(c, e, places)
2932 # assert len(str(abs(coeff)))-p >= 1
2933 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2934 break
2935 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002936 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002937
2938 context = context._shallow_copy()
2939 rounding = context._set_rounding(ROUND_HALF_EVEN)
2940 ans = ans._fix(context)
2941 context.rounding = rounding
2942 return ans
2943
2944 def logb(self, context=None):
2945 """ Returns the exponent of the magnitude of self's MSD.
2946
2947 The result is the integer which is the exponent of the magnitude
2948 of the most significant digit of self (as though it were truncated
2949 to a single digit while maintaining the value of that digit and
2950 without limiting the resulting exponent).
2951 """
2952 # logb(NaN) = NaN
2953 ans = self._check_nans(context=context)
2954 if ans:
2955 return ans
2956
2957 if context is None:
2958 context = getcontext()
2959
2960 # logb(+/-Inf) = +Inf
2961 if self._isinfinity():
2962 return Inf
2963
2964 # logb(0) = -Inf, DivisionByZero
2965 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00002966 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00002967
2968 # otherwise, simply return the adjusted exponent of self, as a
2969 # Decimal. Note that no attempt is made to fit the result
2970 # into the current context.
2971 return Decimal(self.adjusted())
2972
2973 def _islogical(self):
2974 """Return True if self is a logical operand.
2975
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00002976 For being logical, it must be a finite number with a sign of 0,
Facundo Batista353750c2007-09-13 18:13:15 +00002977 an exponent of 0, and a coefficient whose digits must all be
2978 either 0 or 1.
2979 """
2980 if self._sign != 0 or self._exp != 0:
2981 return False
2982 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002983 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00002984 return False
2985 return True
2986
2987 def _fill_logical(self, context, opa, opb):
2988 dif = context.prec - len(opa)
2989 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002990 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00002991 elif dif < 0:
2992 opa = opa[-context.prec:]
2993 dif = context.prec - len(opb)
2994 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002995 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00002996 elif dif < 0:
2997 opb = opb[-context.prec:]
2998 return opa, opb
2999
3000 def logical_and(self, other, context=None):
3001 """Applies an 'and' operation between self and other's digits."""
3002 if context is None:
3003 context = getcontext()
3004 if not self._islogical() or not other._islogical():
3005 return context._raise_error(InvalidOperation)
3006
3007 # fill to context.prec
3008 (opa, opb) = self._fill_logical(context, self._int, other._int)
3009
3010 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003011 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3012 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003013
3014 def logical_invert(self, context=None):
3015 """Invert all its digits."""
3016 if context is None:
3017 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003018 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3019 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003020
3021 def logical_or(self, other, context=None):
3022 """Applies an 'or' operation between self and other's digits."""
3023 if context is None:
3024 context = getcontext()
3025 if not self._islogical() or not other._islogical():
3026 return context._raise_error(InvalidOperation)
3027
3028 # fill to context.prec
3029 (opa, opb) = self._fill_logical(context, self._int, other._int)
3030
3031 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003032 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3033 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003034
3035 def logical_xor(self, other, context=None):
3036 """Applies an 'xor' operation between self and other's digits."""
3037 if context is None:
3038 context = getcontext()
3039 if not self._islogical() or not other._islogical():
3040 return context._raise_error(InvalidOperation)
3041
3042 # fill to context.prec
3043 (opa, opb) = self._fill_logical(context, self._int, other._int)
3044
3045 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003046 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3047 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003048
3049 def max_mag(self, other, context=None):
3050 """Compares the values numerically with their sign ignored."""
3051 other = _convert_other(other, raiseit=True)
3052
Facundo Batista6c398da2007-09-17 17:30:13 +00003053 if context is None:
3054 context = getcontext()
3055
Facundo Batista353750c2007-09-13 18:13:15 +00003056 if self._is_special or other._is_special:
3057 # If one operand is a quiet NaN and the other is number, then the
3058 # number is always returned
3059 sn = self._isnan()
3060 on = other._isnan()
3061 if sn or on:
3062 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003063 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003064 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003065 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003066 return self._check_nans(other, context)
3067
3068 c = self.copy_abs().__cmp__(other.copy_abs())
3069 if c == 0:
3070 c = self.compare_total(other)
3071
3072 if c == -1:
3073 ans = other
3074 else:
3075 ans = self
3076
Facundo Batistae64acfa2007-12-17 14:18:42 +00003077 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003078
3079 def min_mag(self, other, context=None):
3080 """Compares the values numerically with their sign ignored."""
3081 other = _convert_other(other, raiseit=True)
3082
Facundo Batista6c398da2007-09-17 17:30:13 +00003083 if context is None:
3084 context = getcontext()
3085
Facundo Batista353750c2007-09-13 18:13:15 +00003086 if self._is_special or other._is_special:
3087 # If one operand is a quiet NaN and the other is number, then the
3088 # number is always returned
3089 sn = self._isnan()
3090 on = other._isnan()
3091 if sn or on:
3092 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003093 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003094 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003095 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003096 return self._check_nans(other, context)
3097
3098 c = self.copy_abs().__cmp__(other.copy_abs())
3099 if c == 0:
3100 c = self.compare_total(other)
3101
3102 if c == -1:
3103 ans = self
3104 else:
3105 ans = other
3106
Facundo Batistae64acfa2007-12-17 14:18:42 +00003107 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003108
3109 def next_minus(self, context=None):
3110 """Returns the largest representable number smaller than itself."""
3111 if context is None:
3112 context = getcontext()
3113
3114 ans = self._check_nans(context=context)
3115 if ans:
3116 return ans
3117
3118 if self._isinfinity() == -1:
3119 return negInf
3120 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003121 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003122
3123 context = context.copy()
3124 context._set_rounding(ROUND_FLOOR)
3125 context._ignore_all_flags()
3126 new_self = self._fix(context)
3127 if new_self != self:
3128 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003129 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3130 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003131
3132 def next_plus(self, context=None):
3133 """Returns the smallest representable number larger than itself."""
3134 if context is None:
3135 context = getcontext()
3136
3137 ans = self._check_nans(context=context)
3138 if ans:
3139 return ans
3140
3141 if self._isinfinity() == 1:
3142 return Inf
3143 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003144 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003145
3146 context = context.copy()
3147 context._set_rounding(ROUND_CEILING)
3148 context._ignore_all_flags()
3149 new_self = self._fix(context)
3150 if new_self != self:
3151 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003152 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3153 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003154
3155 def next_toward(self, other, context=None):
3156 """Returns the number closest to self, in the direction towards other.
3157
3158 The result is the closest representable number to self
3159 (excluding self) that is in the direction towards other,
3160 unless both have the same value. If the two operands are
3161 numerically equal, then the result is a copy of self with the
3162 sign set to be the same as the sign of other.
3163 """
3164 other = _convert_other(other, raiseit=True)
3165
3166 if context is None:
3167 context = getcontext()
3168
3169 ans = self._check_nans(other, context)
3170 if ans:
3171 return ans
3172
3173 comparison = self.__cmp__(other)
3174 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003175 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003176
3177 if comparison == -1:
3178 ans = self.next_plus(context)
3179 else: # comparison == 1
3180 ans = self.next_minus(context)
3181
3182 # decide which flags to raise using value of ans
3183 if ans._isinfinity():
3184 context._raise_error(Overflow,
3185 'Infinite result from next_toward',
3186 ans._sign)
3187 context._raise_error(Rounded)
3188 context._raise_error(Inexact)
3189 elif ans.adjusted() < context.Emin:
3190 context._raise_error(Underflow)
3191 context._raise_error(Subnormal)
3192 context._raise_error(Rounded)
3193 context._raise_error(Inexact)
3194 # if precision == 1 then we don't raise Clamped for a
3195 # result 0E-Etiny.
3196 if not ans:
3197 context._raise_error(Clamped)
3198
3199 return ans
3200
3201 def number_class(self, context=None):
3202 """Returns an indication of the class of self.
3203
3204 The class is one of the following strings:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00003205 sNaN
3206 NaN
Facundo Batista353750c2007-09-13 18:13:15 +00003207 -Infinity
3208 -Normal
3209 -Subnormal
3210 -Zero
3211 +Zero
3212 +Subnormal
3213 +Normal
3214 +Infinity
3215 """
3216 if self.is_snan():
3217 return "sNaN"
3218 if self.is_qnan():
3219 return "NaN"
3220 inf = self._isinfinity()
3221 if inf == 1:
3222 return "+Infinity"
3223 if inf == -1:
3224 return "-Infinity"
3225 if self.is_zero():
3226 if self._sign:
3227 return "-Zero"
3228 else:
3229 return "+Zero"
3230 if context is None:
3231 context = getcontext()
3232 if self.is_subnormal(context=context):
3233 if self._sign:
3234 return "-Subnormal"
3235 else:
3236 return "+Subnormal"
3237 # just a normal, regular, boring number, :)
3238 if self._sign:
3239 return "-Normal"
3240 else:
3241 return "+Normal"
3242
3243 def radix(self):
3244 """Just returns 10, as this is Decimal, :)"""
3245 return Decimal(10)
3246
3247 def rotate(self, other, context=None):
3248 """Returns a rotated copy of self, value-of-other times."""
3249 if context is None:
3250 context = getcontext()
3251
3252 ans = self._check_nans(other, context)
3253 if ans:
3254 return ans
3255
3256 if other._exp != 0:
3257 return context._raise_error(InvalidOperation)
3258 if not (-context.prec <= int(other) <= context.prec):
3259 return context._raise_error(InvalidOperation)
3260
3261 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003262 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003263
3264 # get values, pad if necessary
3265 torot = int(other)
3266 rotdig = self._int
3267 topad = context.prec - len(rotdig)
3268 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003269 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003270
3271 # let's rotate!
3272 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003273 return _dec_from_triple(self._sign,
3274 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003275
3276 def scaleb (self, other, context=None):
3277 """Returns self operand after adding the second value to its exp."""
3278 if context is None:
3279 context = getcontext()
3280
3281 ans = self._check_nans(other, context)
3282 if ans:
3283 return ans
3284
3285 if other._exp != 0:
3286 return context._raise_error(InvalidOperation)
3287 liminf = -2 * (context.Emax + context.prec)
3288 limsup = 2 * (context.Emax + context.prec)
3289 if not (liminf <= int(other) <= limsup):
3290 return context._raise_error(InvalidOperation)
3291
3292 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003293 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003294
Facundo Batista72bc54f2007-11-23 17:59:00 +00003295 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003296 d = d._fix(context)
3297 return d
3298
3299 def shift(self, other, context=None):
3300 """Returns a shifted copy of self, value-of-other times."""
3301 if context is None:
3302 context = getcontext()
3303
3304 ans = self._check_nans(other, context)
3305 if ans:
3306 return ans
3307
3308 if other._exp != 0:
3309 return context._raise_error(InvalidOperation)
3310 if not (-context.prec <= int(other) <= context.prec):
3311 return context._raise_error(InvalidOperation)
3312
3313 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003314 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003315
3316 # get values, pad if necessary
3317 torot = int(other)
3318 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003319 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003320 rotdig = self._int
3321 topad = context.prec - len(rotdig)
3322 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003323 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003324
3325 # let's shift!
3326 if torot < 0:
3327 rotated = rotdig[:torot]
3328 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003329 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003330 rotated = rotated[-context.prec:]
3331
Facundo Batista72bc54f2007-11-23 17:59:00 +00003332 return _dec_from_triple(self._sign,
3333 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003334
Facundo Batista59c58842007-04-10 12:58:45 +00003335 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003336 def __reduce__(self):
3337 return (self.__class__, (str(self),))
3338
3339 def __copy__(self):
3340 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003341 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003342 return self.__class__(str(self))
3343
3344 def __deepcopy__(self, memo):
3345 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003346 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003347 return self.__class__(str(self))
3348
Facundo Batista72bc54f2007-11-23 17:59:00 +00003349def _dec_from_triple(sign, coefficient, exponent, special=False):
3350 """Create a decimal instance directly, without any validation,
3351 normalization (e.g. removal of leading zeros) or argument
3352 conversion.
3353
3354 This function is for *internal use only*.
3355 """
3356
3357 self = object.__new__(Decimal)
3358 self._sign = sign
3359 self._int = coefficient
3360 self._exp = exponent
3361 self._is_special = special
3362
3363 return self
3364
Facundo Batista59c58842007-04-10 12:58:45 +00003365##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003366
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003367
3368# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003369rounding_functions = [name for name in Decimal.__dict__.keys()
3370 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003371for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003372 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003373 globalname = name[1:].upper()
3374 val = globals()[globalname]
3375 Decimal._pick_rounding_function[val] = name
3376
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003377del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003378
Nick Coghlanced12182006-09-02 03:54:17 +00003379class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003380 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003381
Nick Coghlanced12182006-09-02 03:54:17 +00003382 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003383 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003384 """
3385 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003386 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003387 def __enter__(self):
3388 self.saved_context = getcontext()
3389 setcontext(self.new_context)
3390 return self.new_context
3391 def __exit__(self, t, v, tb):
3392 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003393
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003394class Context(object):
3395 """Contains the context for a Decimal instance.
3396
3397 Contains:
3398 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003399 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003400 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003401 raised when it is caused. Otherwise, a value is
3402 substituted in.
3403 flags - When an exception is caused, flags[exception] is incremented.
3404 (Whether or not the trap_enabler is set)
3405 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003406 Emin - Minimum exponent
3407 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003408 capitals - If 1, 1*10^1 is printed as 1E+1.
3409 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003410 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003411 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003412
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003413 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003414 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003415 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003416 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003417 _ignored_flags=None):
3418 if flags is None:
3419 flags = []
3420 if _ignored_flags is None:
3421 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003422 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003423 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003424 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003425 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003426 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003427 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003428 for name, val in locals().items():
3429 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003430 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003431 else:
3432 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003433 del self.self
3434
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003435 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003436 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003437 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003438 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3439 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3440 % vars(self))
3441 names = [f.__name__ for f, v in self.flags.items() if v]
3442 s.append('flags=[' + ', '.join(names) + ']')
3443 names = [t.__name__ for t, v in self.traps.items() if v]
3444 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003445 return ', '.join(s) + ')'
3446
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003447 def clear_flags(self):
3448 """Reset all flags to zero"""
3449 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003450 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003451
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003452 def _shallow_copy(self):
3453 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003454 nc = Context(self.prec, self.rounding, self.traps,
3455 self.flags, self.Emin, self.Emax,
3456 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003457 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003458
3459 def copy(self):
3460 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003461 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003462 self.flags.copy(), self.Emin, self.Emax,
3463 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003464 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003465 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003466
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003467 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003468 """Handles an error
3469
3470 If the flag is in _ignored_flags, returns the default response.
3471 Otherwise, it increments the flag, then, if the corresponding
3472 trap_enabler is set, it reaises the exception. Otherwise, it returns
3473 the default value after incrementing the flag.
3474 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003475 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003476 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003477 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003478 return error().handle(self, *args)
3479
3480 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003481 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003482 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003483 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003484
3485 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003486 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003487 raise error, explanation
3488
3489 def _ignore_all_flags(self):
3490 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003491 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003492
3493 def _ignore_flags(self, *flags):
3494 """Ignore the flags, if they are raised"""
3495 # Do not mutate-- This way, copies of a context leave the original
3496 # alone.
3497 self._ignored_flags = (self._ignored_flags + list(flags))
3498 return list(flags)
3499
3500 def _regard_flags(self, *flags):
3501 """Stop ignoring the flags, if they are raised"""
3502 if flags and isinstance(flags[0], (tuple,list)):
3503 flags = flags[0]
3504 for flag in flags:
3505 self._ignored_flags.remove(flag)
3506
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003507 def __hash__(self):
3508 """A Context cannot be hashed."""
3509 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003510 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003511
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003512 def Etiny(self):
3513 """Returns Etiny (= Emin - prec + 1)"""
3514 return int(self.Emin - self.prec + 1)
3515
3516 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003517 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003518 return int(self.Emax - self.prec + 1)
3519
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003520 def _set_rounding(self, type):
3521 """Sets the rounding type.
3522
3523 Sets the rounding type, and returns the current (previous)
3524 rounding type. Often used like:
3525
3526 context = context.copy()
3527 # so you don't change the calling context
3528 # if an error occurs in the middle.
3529 rounding = context._set_rounding(ROUND_UP)
3530 val = self.__sub__(other, context=context)
3531 context._set_rounding(rounding)
3532
3533 This will make it round up for that operation.
3534 """
3535 rounding = self.rounding
3536 self.rounding= type
3537 return rounding
3538
Raymond Hettingerfed52962004-07-14 15:41:57 +00003539 def create_decimal(self, num='0'):
Mark Dickinson59bc20b2008-01-12 01:56:00 +00003540 """Creates a new Decimal instance but using self as context.
3541
3542 This method implements the to-number operation of the
3543 IBM Decimal specification."""
3544
3545 if isinstance(num, basestring) and num != num.strip():
3546 return self._raise_error(ConversionSyntax,
3547 "no trailing or leading whitespace is "
3548 "permitted.")
3549
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003550 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003551 if d._isnan() and len(d._int) > self.prec - self._clamp:
3552 return self._raise_error(ConversionSyntax,
3553 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003554 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003555
Facundo Batista59c58842007-04-10 12:58:45 +00003556 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003557 def abs(self, a):
3558 """Returns the absolute value of the operand.
3559
3560 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003561 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003562 the plus operation on the operand.
3563
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003564 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003565 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003566 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003567 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003568 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003569 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003570 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003571 Decimal("101.5")
3572 """
3573 return a.__abs__(context=self)
3574
3575 def add(self, a, b):
3576 """Return the sum of the two operands.
3577
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003578 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003579 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003580 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003581 Decimal("1.02E+4")
3582 """
3583 return a.__add__(b, context=self)
3584
3585 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003586 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003587
Facundo Batista353750c2007-09-13 18:13:15 +00003588 def canonical(self, a):
3589 """Returns the same Decimal object.
3590
3591 As we do not have different encodings for the same number, the
3592 received object already is in its canonical form.
3593
3594 >>> ExtendedContext.canonical(Decimal('2.50'))
3595 Decimal("2.50")
3596 """
3597 return a.canonical(context=self)
3598
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003599 def compare(self, a, b):
3600 """Compares values numerically.
3601
3602 If the signs of the operands differ, a value representing each operand
3603 ('-1' if the operand is less than zero, '0' if the operand is zero or
3604 negative zero, or '1' if the operand is greater than zero) is used in
3605 place of that operand for the comparison instead of the actual
3606 operand.
3607
3608 The comparison is then effected by subtracting the second operand from
3609 the first and then returning a value according to the result of the
3610 subtraction: '-1' if the result is less than zero, '0' if the result is
3611 zero or negative zero, or '1' if the result is greater than zero.
3612
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003613 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003614 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003615 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003616 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003617 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003618 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003619 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003620 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003621 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003622 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003623 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003624 Decimal("-1")
3625 """
3626 return a.compare(b, context=self)
3627
Facundo Batista353750c2007-09-13 18:13:15 +00003628 def compare_signal(self, a, b):
3629 """Compares the values of the two operands numerically.
3630
3631 It's pretty much like compare(), but all NaNs signal, with signaling
3632 NaNs taking precedence over quiet NaNs.
3633
3634 >>> c = ExtendedContext
3635 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3636 Decimal("-1")
3637 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3638 Decimal("0")
3639 >>> c.flags[InvalidOperation] = 0
3640 >>> print c.flags[InvalidOperation]
3641 0
3642 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3643 Decimal("NaN")
3644 >>> print c.flags[InvalidOperation]
3645 1
3646 >>> c.flags[InvalidOperation] = 0
3647 >>> print c.flags[InvalidOperation]
3648 0
3649 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3650 Decimal("NaN")
3651 >>> print c.flags[InvalidOperation]
3652 1
3653 """
3654 return a.compare_signal(b, context=self)
3655
3656 def compare_total(self, a, b):
3657 """Compares two operands using their abstract representation.
3658
3659 This is not like the standard compare, which use their numerical
3660 value. Note that a total ordering is defined for all possible abstract
3661 representations.
3662
3663 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3664 Decimal("-1")
3665 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3666 Decimal("-1")
3667 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3668 Decimal("-1")
3669 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3670 Decimal("0")
3671 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3672 Decimal("1")
3673 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3674 Decimal("-1")
3675 """
3676 return a.compare_total(b)
3677
3678 def compare_total_mag(self, a, b):
3679 """Compares two operands using their abstract representation ignoring sign.
3680
3681 Like compare_total, but with operand's sign ignored and assumed to be 0.
3682 """
3683 return a.compare_total_mag(b)
3684
3685 def copy_abs(self, a):
3686 """Returns a copy of the operand with the sign set to 0.
3687
3688 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3689 Decimal("2.1")
3690 >>> ExtendedContext.copy_abs(Decimal('-100'))
3691 Decimal("100")
3692 """
3693 return a.copy_abs()
3694
3695 def copy_decimal(self, a):
3696 """Returns a copy of the decimal objet.
3697
3698 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3699 Decimal("2.1")
3700 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3701 Decimal("-1.00")
3702 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003703 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003704
3705 def copy_negate(self, a):
3706 """Returns a copy of the operand with the sign inverted.
3707
3708 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3709 Decimal("-101.5")
3710 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3711 Decimal("101.5")
3712 """
3713 return a.copy_negate()
3714
3715 def copy_sign(self, a, b):
3716 """Copies the second operand's sign to the first one.
3717
3718 In detail, it returns a copy of the first operand with the sign
3719 equal to the sign of the second operand.
3720
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 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3728 Decimal("-1.50")
3729 """
3730 return a.copy_sign(b)
3731
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003732 def divide(self, a, b):
3733 """Decimal division in a specified context.
3734
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003735 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003736 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003737 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003738 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003739 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003740 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003741 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003742 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003743 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003744 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003745 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003746 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003747 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003748 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003749 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003750 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003751 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003752 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003753 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003754 Decimal("1.20E+6")
3755 """
3756 return a.__div__(b, context=self)
3757
3758 def divide_int(self, a, b):
3759 """Divides two numbers and returns the integer part of the result.
3760
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003761 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003762 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003763 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003764 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003765 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003766 Decimal("3")
3767 """
3768 return a.__floordiv__(b, context=self)
3769
3770 def divmod(self, a, b):
3771 return a.__divmod__(b, context=self)
3772
Facundo Batista353750c2007-09-13 18:13:15 +00003773 def exp(self, a):
3774 """Returns e ** a.
3775
3776 >>> c = ExtendedContext.copy()
3777 >>> c.Emin = -999
3778 >>> c.Emax = 999
3779 >>> c.exp(Decimal('-Infinity'))
3780 Decimal("0")
3781 >>> c.exp(Decimal('-1'))
3782 Decimal("0.367879441")
3783 >>> c.exp(Decimal('0'))
3784 Decimal("1")
3785 >>> c.exp(Decimal('1'))
3786 Decimal("2.71828183")
3787 >>> c.exp(Decimal('0.693147181'))
3788 Decimal("2.00000000")
3789 >>> c.exp(Decimal('+Infinity'))
3790 Decimal("Infinity")
3791 """
3792 return a.exp(context=self)
3793
3794 def fma(self, a, b, c):
3795 """Returns a multiplied by b, plus c.
3796
3797 The first two operands are multiplied together, using multiply,
3798 the third operand is then added to the result of that
3799 multiplication, using add, all with only one final rounding.
3800
3801 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3802 Decimal("22")
3803 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3804 Decimal("-8")
3805 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3806 Decimal("1.38435736E+12")
3807 """
3808 return a.fma(b, c, context=self)
3809
3810 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003811 """Return True if the operand is canonical; otherwise return False.
3812
3813 Currently, the encoding of a Decimal instance is always
3814 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00003815
3816 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003817 True
Facundo Batista353750c2007-09-13 18:13:15 +00003818 """
Facundo Batista1a191df2007-10-02 17:01:24 +00003819 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00003820
3821 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003822 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003823
Facundo Batista1a191df2007-10-02 17:01:24 +00003824 A Decimal instance is considered finite if it is neither
3825 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00003826
3827 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003828 True
Facundo Batista353750c2007-09-13 18:13:15 +00003829 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003830 True
Facundo Batista353750c2007-09-13 18:13:15 +00003831 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003832 True
Facundo Batista353750c2007-09-13 18:13:15 +00003833 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003834 False
Facundo Batista353750c2007-09-13 18:13:15 +00003835 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003836 False
Facundo Batista353750c2007-09-13 18:13:15 +00003837 """
3838 return a.is_finite()
3839
3840 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003841 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003842
3843 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003844 False
Facundo Batista353750c2007-09-13 18:13:15 +00003845 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003846 True
Facundo Batista353750c2007-09-13 18:13:15 +00003847 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003848 False
Facundo Batista353750c2007-09-13 18:13:15 +00003849 """
3850 return a.is_infinite()
3851
3852 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003853 """Return True if the operand is a qNaN or sNaN;
3854 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003855
3856 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003857 False
Facundo Batista353750c2007-09-13 18:13:15 +00003858 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003859 True
Facundo Batista353750c2007-09-13 18:13:15 +00003860 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003861 True
Facundo Batista353750c2007-09-13 18:13:15 +00003862 """
3863 return a.is_nan()
3864
3865 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003866 """Return True if the operand is a normal number;
3867 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003868
3869 >>> c = ExtendedContext.copy()
3870 >>> c.Emin = -999
3871 >>> c.Emax = 999
3872 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003873 True
Facundo Batista353750c2007-09-13 18:13:15 +00003874 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003875 False
Facundo Batista353750c2007-09-13 18:13:15 +00003876 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003877 False
Facundo Batista353750c2007-09-13 18:13:15 +00003878 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003879 False
Facundo Batista353750c2007-09-13 18:13:15 +00003880 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003881 False
Facundo Batista353750c2007-09-13 18:13:15 +00003882 """
3883 return a.is_normal(context=self)
3884
3885 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003886 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003887
3888 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003889 False
Facundo Batista353750c2007-09-13 18:13:15 +00003890 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003891 True
Facundo Batista353750c2007-09-13 18:13:15 +00003892 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003893 False
Facundo Batista353750c2007-09-13 18:13:15 +00003894 """
3895 return a.is_qnan()
3896
3897 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003898 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003899
3900 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003901 False
Facundo Batista353750c2007-09-13 18:13:15 +00003902 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003903 True
Facundo Batista353750c2007-09-13 18:13:15 +00003904 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003905 True
Facundo Batista353750c2007-09-13 18:13:15 +00003906 """
3907 return a.is_signed()
3908
3909 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003910 """Return True if the operand is a signaling NaN;
3911 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003912
3913 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003914 False
Facundo Batista353750c2007-09-13 18:13:15 +00003915 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003916 False
Facundo Batista353750c2007-09-13 18:13:15 +00003917 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003918 True
Facundo Batista353750c2007-09-13 18:13:15 +00003919 """
3920 return a.is_snan()
3921
3922 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003923 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003924
3925 >>> c = ExtendedContext.copy()
3926 >>> c.Emin = -999
3927 >>> c.Emax = 999
3928 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003929 False
Facundo Batista353750c2007-09-13 18:13:15 +00003930 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003931 True
Facundo Batista353750c2007-09-13 18:13:15 +00003932 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003933 False
Facundo Batista353750c2007-09-13 18:13:15 +00003934 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003935 False
Facundo Batista353750c2007-09-13 18:13:15 +00003936 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003937 False
Facundo Batista353750c2007-09-13 18:13:15 +00003938 """
3939 return a.is_subnormal(context=self)
3940
3941 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003942 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003943
3944 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003945 True
Facundo Batista353750c2007-09-13 18:13:15 +00003946 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003947 False
Facundo Batista353750c2007-09-13 18:13:15 +00003948 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003949 True
Facundo Batista353750c2007-09-13 18:13:15 +00003950 """
3951 return a.is_zero()
3952
3953 def ln(self, a):
3954 """Returns the natural (base e) logarithm of the operand.
3955
3956 >>> c = ExtendedContext.copy()
3957 >>> c.Emin = -999
3958 >>> c.Emax = 999
3959 >>> c.ln(Decimal('0'))
3960 Decimal("-Infinity")
3961 >>> c.ln(Decimal('1.000'))
3962 Decimal("0")
3963 >>> c.ln(Decimal('2.71828183'))
3964 Decimal("1.00000000")
3965 >>> c.ln(Decimal('10'))
3966 Decimal("2.30258509")
3967 >>> c.ln(Decimal('+Infinity'))
3968 Decimal("Infinity")
3969 """
3970 return a.ln(context=self)
3971
3972 def log10(self, a):
3973 """Returns the base 10 logarithm of the operand.
3974
3975 >>> c = ExtendedContext.copy()
3976 >>> c.Emin = -999
3977 >>> c.Emax = 999
3978 >>> c.log10(Decimal('0'))
3979 Decimal("-Infinity")
3980 >>> c.log10(Decimal('0.001'))
3981 Decimal("-3")
3982 >>> c.log10(Decimal('1.000'))
3983 Decimal("0")
3984 >>> c.log10(Decimal('2'))
3985 Decimal("0.301029996")
3986 >>> c.log10(Decimal('10'))
3987 Decimal("1")
3988 >>> c.log10(Decimal('70'))
3989 Decimal("1.84509804")
3990 >>> c.log10(Decimal('+Infinity'))
3991 Decimal("Infinity")
3992 """
3993 return a.log10(context=self)
3994
3995 def logb(self, a):
3996 """ Returns the exponent of the magnitude of the operand's MSD.
3997
3998 The result is the integer which is the exponent of the magnitude
3999 of the most significant digit of the operand (as though the
4000 operand were truncated to a single digit while maintaining the
4001 value of that digit and without limiting the resulting exponent).
4002
4003 >>> ExtendedContext.logb(Decimal('250'))
4004 Decimal("2")
4005 >>> ExtendedContext.logb(Decimal('2.50'))
4006 Decimal("0")
4007 >>> ExtendedContext.logb(Decimal('0.03'))
4008 Decimal("-2")
4009 >>> ExtendedContext.logb(Decimal('0'))
4010 Decimal("-Infinity")
4011 """
4012 return a.logb(context=self)
4013
4014 def logical_and(self, a, b):
4015 """Applies the logical operation 'and' between each operand's digits.
4016
4017 The operands must be both logical numbers.
4018
4019 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4020 Decimal("0")
4021 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4022 Decimal("0")
4023 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4024 Decimal("0")
4025 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4026 Decimal("1")
4027 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4028 Decimal("1000")
4029 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4030 Decimal("10")
4031 """
4032 return a.logical_and(b, context=self)
4033
4034 def logical_invert(self, a):
4035 """Invert all the digits in the operand.
4036
4037 The operand must be a logical number.
4038
4039 >>> ExtendedContext.logical_invert(Decimal('0'))
4040 Decimal("111111111")
4041 >>> ExtendedContext.logical_invert(Decimal('1'))
4042 Decimal("111111110")
4043 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4044 Decimal("0")
4045 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4046 Decimal("10101010")
4047 """
4048 return a.logical_invert(context=self)
4049
4050 def logical_or(self, a, b):
4051 """Applies the logical operation 'or' between each operand's digits.
4052
4053 The operands must be both logical numbers.
4054
4055 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4056 Decimal("0")
4057 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4058 Decimal("1")
4059 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4060 Decimal("1")
4061 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4062 Decimal("1")
4063 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4064 Decimal("1110")
4065 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4066 Decimal("1110")
4067 """
4068 return a.logical_or(b, context=self)
4069
4070 def logical_xor(self, a, b):
4071 """Applies the logical operation 'xor' between each operand's digits.
4072
4073 The operands must be both logical numbers.
4074
4075 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4076 Decimal("0")
4077 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4078 Decimal("1")
4079 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4080 Decimal("1")
4081 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4082 Decimal("0")
4083 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4084 Decimal("110")
4085 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4086 Decimal("1101")
4087 """
4088 return a.logical_xor(b, context=self)
4089
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004090 def max(self, a,b):
4091 """max compares two values numerically and returns the maximum.
4092
4093 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004094 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004095 operation. If they are numerically equal then the left-hand operand
4096 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004097 infinity) of the two operands is chosen as the result.
4098
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004099 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004100 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004101 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004102 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004103 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004104 Decimal("1")
4105 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4106 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004107 """
4108 return a.max(b, context=self)
4109
Facundo Batista353750c2007-09-13 18:13:15 +00004110 def max_mag(self, a, b):
4111 """Compares the values numerically with their sign ignored."""
4112 return a.max_mag(b, context=self)
4113
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004114 def min(self, a,b):
4115 """min compares two values numerically and returns the minimum.
4116
4117 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004118 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004119 operation. If they are numerically equal then the left-hand operand
4120 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004121 infinity) of the two operands is chosen as the result.
4122
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004123 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004124 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004125 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004126 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004127 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004128 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004129 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4130 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004131 """
4132 return a.min(b, context=self)
4133
Facundo Batista353750c2007-09-13 18:13:15 +00004134 def min_mag(self, a, b):
4135 """Compares the values numerically with their sign ignored."""
4136 return a.min_mag(b, context=self)
4137
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004138 def minus(self, a):
4139 """Minus corresponds to unary prefix minus in Python.
4140
4141 The operation is evaluated using the same rules as subtract; the
4142 operation minus(a) is calculated as subtract('0', a) where the '0'
4143 has the same exponent as the operand.
4144
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004145 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004146 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004147 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004148 Decimal("1.3")
4149 """
4150 return a.__neg__(context=self)
4151
4152 def multiply(self, a, b):
4153 """multiply multiplies two operands.
4154
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004155 If either operand is a special value then the general rules apply.
4156 Otherwise, the operands are multiplied together ('long multiplication'),
4157 resulting in a number which may be as long as the sum of the lengths
4158 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004159
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004160 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004161 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004162 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004163 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004164 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004165 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004166 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004167 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004168 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004169 Decimal("4.28135971E+11")
4170 """
4171 return a.__mul__(b, context=self)
4172
Facundo Batista353750c2007-09-13 18:13:15 +00004173 def next_minus(self, a):
4174 """Returns the largest representable number smaller than a.
4175
4176 >>> c = ExtendedContext.copy()
4177 >>> c.Emin = -999
4178 >>> c.Emax = 999
4179 >>> ExtendedContext.next_minus(Decimal('1'))
4180 Decimal("0.999999999")
4181 >>> c.next_minus(Decimal('1E-1007'))
4182 Decimal("0E-1007")
4183 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4184 Decimal("-1.00000004")
4185 >>> c.next_minus(Decimal('Infinity'))
4186 Decimal("9.99999999E+999")
4187 """
4188 return a.next_minus(context=self)
4189
4190 def next_plus(self, a):
4191 """Returns the smallest representable number larger than a.
4192
4193 >>> c = ExtendedContext.copy()
4194 >>> c.Emin = -999
4195 >>> c.Emax = 999
4196 >>> ExtendedContext.next_plus(Decimal('1'))
4197 Decimal("1.00000001")
4198 >>> c.next_plus(Decimal('-1E-1007'))
4199 Decimal("-0E-1007")
4200 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4201 Decimal("-1.00000002")
4202 >>> c.next_plus(Decimal('-Infinity'))
4203 Decimal("-9.99999999E+999")
4204 """
4205 return a.next_plus(context=self)
4206
4207 def next_toward(self, a, b):
4208 """Returns the number closest to a, in direction towards b.
4209
4210 The result is the closest representable number from the first
4211 operand (but not the first operand) that is in the direction
4212 towards the second operand, unless the operands have the same
4213 value.
4214
4215 >>> c = ExtendedContext.copy()
4216 >>> c.Emin = -999
4217 >>> c.Emax = 999
4218 >>> c.next_toward(Decimal('1'), Decimal('2'))
4219 Decimal("1.00000001")
4220 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4221 Decimal("-0E-1007")
4222 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4223 Decimal("-1.00000002")
4224 >>> c.next_toward(Decimal('1'), Decimal('0'))
4225 Decimal("0.999999999")
4226 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4227 Decimal("0E-1007")
4228 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4229 Decimal("-1.00000004")
4230 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4231 Decimal("-0.00")
4232 """
4233 return a.next_toward(b, context=self)
4234
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004235 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004236 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004237
4238 Essentially a plus operation with all trailing zeros removed from the
4239 result.
4240
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004241 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004242 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004243 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004244 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004245 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004246 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004247 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004248 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004249 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004250 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004251 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004252 Decimal("0")
4253 """
4254 return a.normalize(context=self)
4255
Facundo Batista353750c2007-09-13 18:13:15 +00004256 def number_class(self, a):
4257 """Returns an indication of the class of the operand.
4258
4259 The class is one of the following strings:
4260 -sNaN
4261 -NaN
4262 -Infinity
4263 -Normal
4264 -Subnormal
4265 -Zero
4266 +Zero
4267 +Subnormal
4268 +Normal
4269 +Infinity
4270
4271 >>> c = Context(ExtendedContext)
4272 >>> c.Emin = -999
4273 >>> c.Emax = 999
4274 >>> c.number_class(Decimal('Infinity'))
4275 '+Infinity'
4276 >>> c.number_class(Decimal('1E-10'))
4277 '+Normal'
4278 >>> c.number_class(Decimal('2.50'))
4279 '+Normal'
4280 >>> c.number_class(Decimal('0.1E-999'))
4281 '+Subnormal'
4282 >>> c.number_class(Decimal('0'))
4283 '+Zero'
4284 >>> c.number_class(Decimal('-0'))
4285 '-Zero'
4286 >>> c.number_class(Decimal('-0.1E-999'))
4287 '-Subnormal'
4288 >>> c.number_class(Decimal('-1E-10'))
4289 '-Normal'
4290 >>> c.number_class(Decimal('-2.50'))
4291 '-Normal'
4292 >>> c.number_class(Decimal('-Infinity'))
4293 '-Infinity'
4294 >>> c.number_class(Decimal('NaN'))
4295 'NaN'
4296 >>> c.number_class(Decimal('-NaN'))
4297 'NaN'
4298 >>> c.number_class(Decimal('sNaN'))
4299 'sNaN'
4300 """
4301 return a.number_class(context=self)
4302
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004303 def plus(self, a):
4304 """Plus corresponds to unary prefix plus in Python.
4305
4306 The operation is evaluated using the same rules as add; the
4307 operation plus(a) is calculated as add('0', a) where the '0'
4308 has the same exponent as the operand.
4309
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004310 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004311 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004312 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004313 Decimal("-1.3")
4314 """
4315 return a.__pos__(context=self)
4316
4317 def power(self, a, b, modulo=None):
4318 """Raises a to the power of b, to modulo if given.
4319
Facundo Batista353750c2007-09-13 18:13:15 +00004320 With two arguments, compute a**b. If a is negative then b
4321 must be integral. The result will be inexact unless b is
4322 integral and the result is finite and can be expressed exactly
4323 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004324
Facundo Batista353750c2007-09-13 18:13:15 +00004325 With three arguments, compute (a**b) % modulo. For the
4326 three argument form, the following restrictions on the
4327 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004328
Facundo Batista353750c2007-09-13 18:13:15 +00004329 - all three arguments must be integral
4330 - b must be nonnegative
4331 - at least one of a or b must be nonzero
4332 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004333
Facundo Batista353750c2007-09-13 18:13:15 +00004334 The result of pow(a, b, modulo) is identical to the result
4335 that would be obtained by computing (a**b) % modulo with
4336 unbounded precision, but is computed more efficiently. It is
4337 always exact.
4338
4339 >>> c = ExtendedContext.copy()
4340 >>> c.Emin = -999
4341 >>> c.Emax = 999
4342 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004343 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004344 >>> c.power(Decimal('-2'), Decimal('3'))
4345 Decimal("-8")
4346 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004347 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004348 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004349 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004350 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4351 Decimal("2.00000000")
4352 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004353 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004354 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004355 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004356 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004357 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004358 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004359 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004360 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004361 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004362 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004363 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004364 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004365 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004366 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004367 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004368
4369 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4370 Decimal("11")
4371 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4372 Decimal("-11")
4373 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4374 Decimal("1")
4375 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4376 Decimal("11")
4377 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4378 Decimal("11729830")
4379 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4380 Decimal("-0")
4381 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4382 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004383 """
4384 return a.__pow__(b, modulo, context=self)
4385
4386 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004387 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004388
4389 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004390 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004391 exponent is being increased), multiplied by a positive power of ten (if
4392 the exponent is being decreased), or is unchanged (if the exponent is
4393 already equal to that of the right-hand operand).
4394
4395 Unlike other operations, if the length of the coefficient after the
4396 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004397 operation condition is raised. This guarantees that, unless there is
4398 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004399 equal to that of the right-hand operand.
4400
4401 Also unlike other operations, quantize will never raise Underflow, even
4402 if the result is subnormal and inexact.
4403
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004404 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004405 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004406 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004407 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004408 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004409 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004410 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004411 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004412 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004413 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004414 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004415 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004416 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004417 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004418 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004419 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004420 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004421 Decimal("-0E+5")
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('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004425 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004426 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004427 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004428 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004429 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004430 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004431 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004432 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004433 Decimal("2E+2")
4434 """
4435 return a.quantize(b, context=self)
4436
Facundo Batista353750c2007-09-13 18:13:15 +00004437 def radix(self):
4438 """Just returns 10, as this is Decimal, :)
4439
4440 >>> ExtendedContext.radix()
4441 Decimal("10")
4442 """
4443 return Decimal(10)
4444
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004445 def remainder(self, a, b):
4446 """Returns the remainder from integer division.
4447
4448 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004449 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004450 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004451 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004452
4453 This operation will fail under the same conditions as integer division
4454 (that is, if integer division on the same two operands would fail, the
4455 remainder cannot be calculated).
4456
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004457 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004458 Decimal("2.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'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004462 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004463 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004464 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004465 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004466 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004467 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004468 Decimal("1.0")
4469 """
4470 return a.__mod__(b, context=self)
4471
4472 def remainder_near(self, a, b):
4473 """Returns to be "a - b * n", where n is the integer nearest the exact
4474 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004475 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004476 sign of a.
4477
4478 This operation will fail under the same conditions as integer division
4479 (that is, if integer division on the same two operands would fail, the
4480 remainder cannot be calculated).
4481
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004482 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004483 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004484 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004485 Decimal("-2")
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'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004489 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004490 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004491 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004492 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004493 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004494 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004495 Decimal("-0.3")
4496 """
4497 return a.remainder_near(b, context=self)
4498
Facundo Batista353750c2007-09-13 18:13:15 +00004499 def rotate(self, a, b):
4500 """Returns a rotated copy of a, b times.
4501
4502 The coefficient of the result is a rotated copy of the digits in
4503 the coefficient of the first operand. The number of places of
4504 rotation is taken from the absolute value of the second operand,
4505 with the rotation being to the left if the second operand is
4506 positive or to the right otherwise.
4507
4508 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4509 Decimal("400000003")
4510 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4511 Decimal("12")
4512 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4513 Decimal("891234567")
4514 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4515 Decimal("123456789")
4516 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4517 Decimal("345678912")
4518 """
4519 return a.rotate(b, context=self)
4520
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004521 def same_quantum(self, a, b):
4522 """Returns True if the two operands have the same exponent.
4523
4524 The result is never affected by either the sign or the coefficient of
4525 either operand.
4526
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004527 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004528 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004529 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004530 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004531 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004532 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004533 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004534 True
4535 """
4536 return a.same_quantum(b)
4537
Facundo Batista353750c2007-09-13 18:13:15 +00004538 def scaleb (self, a, b):
4539 """Returns the first operand after adding the second value its exp.
4540
4541 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4542 Decimal("0.0750")
4543 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4544 Decimal("7.50")
4545 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4546 Decimal("7.50E+3")
4547 """
4548 return a.scaleb (b, context=self)
4549
4550 def shift(self, a, b):
4551 """Returns a shifted copy of a, b times.
4552
4553 The coefficient of the result is a shifted copy of the digits
4554 in the coefficient of the first operand. The number of places
4555 to shift is taken from the absolute value of the second operand,
4556 with the shift being to the left if the second operand is
4557 positive or to the right otherwise. Digits shifted into the
4558 coefficient are zeros.
4559
4560 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4561 Decimal("400000000")
4562 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4563 Decimal("0")
4564 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4565 Decimal("1234567")
4566 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4567 Decimal("123456789")
4568 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4569 Decimal("345678900")
4570 """
4571 return a.shift(b, context=self)
4572
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004573 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004574 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004575
4576 If the result must be inexact, it is rounded using the round-half-even
4577 algorithm.
4578
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'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004582 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004583 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004584 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004585 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004586 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004587 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004588 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004589 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004590 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004591 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004592 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004593 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004594 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004595 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004596 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004597 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004598 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004599 """
4600 return a.sqrt(context=self)
4601
4602 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004603 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004604
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004605 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004606 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004607 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004608 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004609 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004610 Decimal("-0.77")
4611 """
4612 return a.__sub__(b, context=self)
4613
4614 def to_eng_string(self, a):
4615 """Converts a number to a string, using scientific notation.
4616
4617 The operation is not affected by the context.
4618 """
4619 return a.to_eng_string(context=self)
4620
4621 def to_sci_string(self, a):
4622 """Converts a number to a string, using scientific notation.
4623
4624 The operation is not affected by the context.
4625 """
4626 return a.__str__(context=self)
4627
Facundo Batista353750c2007-09-13 18:13:15 +00004628 def to_integral_exact(self, a):
4629 """Rounds to an integer.
4630
4631 When the operand has a negative exponent, the result is the same
4632 as using the quantize() operation using the given operand as the
4633 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4634 of the operand as the precision setting; Inexact and Rounded flags
4635 are allowed in this operation. The rounding mode is taken from the
4636 context.
4637
4638 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4639 Decimal("2")
4640 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4641 Decimal("100")
4642 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4643 Decimal("100")
4644 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4645 Decimal("102")
4646 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4647 Decimal("-102")
4648 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4649 Decimal("1.0E+6")
4650 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4651 Decimal("7.89E+77")
4652 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4653 Decimal("-Infinity")
4654 """
4655 return a.to_integral_exact(context=self)
4656
4657 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004658 """Rounds to an integer.
4659
4660 When the operand has a negative exponent, the result is the same
4661 as using the quantize() operation using the given operand as the
4662 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4663 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004664 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004665
Facundo Batista353750c2007-09-13 18:13:15 +00004666 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004667 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004668 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004669 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004670 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004671 Decimal("100")
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('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004675 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004676 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004677 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004678 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004679 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004680 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004681 Decimal("-Infinity")
4682 """
Facundo Batista353750c2007-09-13 18:13:15 +00004683 return a.to_integral_value(context=self)
4684
4685 # the method name changed, but we provide also the old one, for compatibility
4686 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004687
4688class _WorkRep(object):
4689 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004690 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004691 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004692 # exp: None, int, or string
4693
4694 def __init__(self, value=None):
4695 if value is None:
4696 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004697 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004698 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004699 elif isinstance(value, Decimal):
4700 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004701 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004702 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004703 else:
4704 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004705 self.sign = value[0]
4706 self.int = value[1]
4707 self.exp = value[2]
4708
4709 def __repr__(self):
4710 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4711
4712 __str__ = __repr__
4713
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004714
4715
Facundo Batistae64acfa2007-12-17 14:18:42 +00004716def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004717 """Normalizes op1, op2 to have the same exp and length of coefficient.
4718
4719 Done during addition.
4720 """
Facundo Batista353750c2007-09-13 18:13:15 +00004721 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004722 tmp = op2
4723 other = op1
4724 else:
4725 tmp = op1
4726 other = op2
4727
Facundo Batista353750c2007-09-13 18:13:15 +00004728 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4729 # Then adding 10**exp to tmp has the same effect (after rounding)
4730 # as adding any positive quantity smaller than 10**exp; similarly
4731 # for subtraction. So if other is smaller than 10**exp we replace
4732 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00004733 tmp_len = len(str(tmp.int))
4734 other_len = len(str(other.int))
4735 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4736 if other_len + other.exp - 1 < exp:
4737 other.int = 1
4738 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004739
Facundo Batista353750c2007-09-13 18:13:15 +00004740 tmp.int *= 10 ** (tmp.exp - other.exp)
4741 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004742 return op1, op2
4743
Facundo Batista353750c2007-09-13 18:13:15 +00004744##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4745
4746# This function from Tim Peters was taken from here:
4747# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4748# The correction being in the function definition is for speed, and
4749# the whole function is not resolved with math.log because of avoiding
4750# the use of floats.
4751def _nbits(n, correction = {
4752 '0': 4, '1': 3, '2': 2, '3': 2,
4753 '4': 1, '5': 1, '6': 1, '7': 1,
4754 '8': 0, '9': 0, 'a': 0, 'b': 0,
4755 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4756 """Number of bits in binary representation of the positive integer n,
4757 or 0 if n == 0.
4758 """
4759 if n < 0:
4760 raise ValueError("The argument to _nbits should be nonnegative.")
4761 hex_n = "%x" % n
4762 return 4*len(hex_n) - correction[hex_n[0]]
4763
4764def _sqrt_nearest(n, a):
4765 """Closest integer to the square root of the positive integer n. a is
4766 an initial approximation to the square root. Any positive integer
4767 will do for a, but the closer a is to the square root of n the
4768 faster convergence will be.
4769
4770 """
4771 if n <= 0 or a <= 0:
4772 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4773
4774 b=0
4775 while a != b:
4776 b, a = a, a--n//a>>1
4777 return a
4778
4779def _rshift_nearest(x, shift):
4780 """Given an integer x and a nonnegative integer shift, return closest
4781 integer to x / 2**shift; use round-to-even in case of a tie.
4782
4783 """
4784 b, q = 1L << shift, x >> shift
4785 return q + (2*(x & (b-1)) + (q&1) > b)
4786
4787def _div_nearest(a, b):
4788 """Closest integer to a/b, a and b positive integers; rounds to even
4789 in the case of a tie.
4790
4791 """
4792 q, r = divmod(a, b)
4793 return q + (2*r + (q&1) > b)
4794
4795def _ilog(x, M, L = 8):
4796 """Integer approximation to M*log(x/M), with absolute error boundable
4797 in terms only of x/M.
4798
4799 Given positive integers x and M, return an integer approximation to
4800 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4801 between the approximation and the exact result is at most 22. For
4802 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4803 both cases these are upper bounds on the error; it will usually be
4804 much smaller."""
4805
4806 # The basic algorithm is the following: let log1p be the function
4807 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4808 # the reduction
4809 #
4810 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4811 #
4812 # repeatedly until the argument to log1p is small (< 2**-L in
4813 # absolute value). For small y we can use the Taylor series
4814 # expansion
4815 #
4816 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4817 #
4818 # truncating at T such that y**T is small enough. The whole
4819 # computation is carried out in a form of fixed-point arithmetic,
4820 # with a real number z being represented by an integer
4821 # approximation to z*M. To avoid loss of precision, the y below
4822 # is actually an integer approximation to 2**R*y*M, where R is the
4823 # number of reductions performed so far.
4824
4825 y = x-M
4826 # argument reduction; R = number of reductions performed
4827 R = 0
4828 while (R <= L and long(abs(y)) << L-R >= M or
4829 R > L and abs(y) >> R-L >= M):
4830 y = _div_nearest(long(M*y) << 1,
4831 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4832 R += 1
4833
4834 # Taylor series with T terms
4835 T = -int(-10*len(str(M))//(3*L))
4836 yshift = _rshift_nearest(y, R)
4837 w = _div_nearest(M, T)
4838 for k in xrange(T-1, 0, -1):
4839 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4840
4841 return _div_nearest(w*y, M)
4842
4843def _dlog10(c, e, p):
4844 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4845 approximation to 10**p * log10(c*10**e), with an absolute error of
4846 at most 1. Assumes that c*10**e is not exactly 1."""
4847
4848 # increase precision by 2; compensate for this by dividing
4849 # final result by 100
4850 p += 2
4851
4852 # write c*10**e as d*10**f with either:
4853 # f >= 0 and 1 <= d <= 10, or
4854 # f <= 0 and 0.1 <= d <= 1.
4855 # Thus for c*10**e close to 1, f = 0
4856 l = len(str(c))
4857 f = e+l - (e+l >= 1)
4858
4859 if p > 0:
4860 M = 10**p
4861 k = e+p-f
4862 if k >= 0:
4863 c *= 10**k
4864 else:
4865 c = _div_nearest(c, 10**-k)
4866
4867 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004868 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004869 log_d = _div_nearest(log_d*M, log_10)
4870 log_tenpower = f*M # exact
4871 else:
4872 log_d = 0 # error < 2.31
4873 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4874
4875 return _div_nearest(log_tenpower+log_d, 100)
4876
4877def _dlog(c, e, p):
4878 """Given integers c, e and p with c > 0, compute an integer
4879 approximation to 10**p * log(c*10**e), with an absolute error of
4880 at most 1. Assumes that c*10**e is not exactly 1."""
4881
4882 # Increase precision by 2. The precision increase is compensated
4883 # for at the end with a division by 100.
4884 p += 2
4885
4886 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4887 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4888 # as 10**p * log(d) + 10**p*f * log(10).
4889 l = len(str(c))
4890 f = e+l - (e+l >= 1)
4891
4892 # compute approximation to 10**p*log(d), with error < 27
4893 if p > 0:
4894 k = e+p-f
4895 if k >= 0:
4896 c *= 10**k
4897 else:
4898 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4899
4900 # _ilog magnifies existing error in c by a factor of at most 10
4901 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4902 else:
4903 # p <= 0: just approximate the whole thing by 0; error < 2.31
4904 log_d = 0
4905
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004906 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00004907 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004908 extra = len(str(abs(f)))-1
4909 if p + extra >= 0:
4910 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4911 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4912 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00004913 else:
4914 f_log_ten = 0
4915 else:
4916 f_log_ten = 0
4917
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004918 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004919 return _div_nearest(f_log_ten + log_d, 100)
4920
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004921class _Log10Memoize(object):
4922 """Class to compute, store, and allow retrieval of, digits of the
4923 constant log(10) = 2.302585.... This constant is needed by
4924 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4925 def __init__(self):
4926 self.digits = "23025850929940456840179914546843642076011014886"
4927
4928 def getdigits(self, p):
4929 """Given an integer p >= 0, return floor(10**p)*log(10).
4930
4931 For example, self.getdigits(3) returns 2302.
4932 """
4933 # digits are stored as a string, for quick conversion to
4934 # integer in the case that we've already computed enough
4935 # digits; the stored digits should always be correct
4936 # (truncated, not rounded to nearest).
4937 if p < 0:
4938 raise ValueError("p should be nonnegative")
4939
4940 if p >= len(self.digits):
4941 # compute p+3, p+6, p+9, ... digits; continue until at
4942 # least one of the extra digits is nonzero
4943 extra = 3
4944 while True:
4945 # compute p+extra digits, correct to within 1ulp
4946 M = 10**(p+extra+2)
4947 digits = str(_div_nearest(_ilog(10*M, M), 100))
4948 if digits[-extra:] != '0'*extra:
4949 break
4950 extra += 3
4951 # keep all reliable digits so far; remove trailing zeros
4952 # and next nonzero digit
4953 self.digits = digits.rstrip('0')[:-1]
4954 return int(self.digits[:p+1])
4955
4956_log10_digits = _Log10Memoize().getdigits
4957
Facundo Batista353750c2007-09-13 18:13:15 +00004958def _iexp(x, M, L=8):
4959 """Given integers x and M, M > 0, such that x/M is small in absolute
4960 value, compute an integer approximation to M*exp(x/M). For 0 <=
4961 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4962 is usually much smaller)."""
4963
4964 # Algorithm: to compute exp(z) for a real number z, first divide z
4965 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4966 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4967 # series
4968 #
4969 # expm1(x) = x + x**2/2! + x**3/3! + ...
4970 #
4971 # Now use the identity
4972 #
4973 # expm1(2x) = expm1(x)*(expm1(x)+2)
4974 #
4975 # R times to compute the sequence expm1(z/2**R),
4976 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
4977
4978 # Find R such that x/2**R/M <= 2**-L
4979 R = _nbits((long(x)<<L)//M)
4980
4981 # Taylor series. (2**L)**T > M
4982 T = -int(-10*len(str(M))//(3*L))
4983 y = _div_nearest(x, T)
4984 Mshift = long(M)<<R
4985 for i in xrange(T-1, 0, -1):
4986 y = _div_nearest(x*(Mshift + y), Mshift * i)
4987
4988 # Expansion
4989 for k in xrange(R-1, -1, -1):
4990 Mshift = long(M)<<(k+2)
4991 y = _div_nearest(y*(y+Mshift), Mshift)
4992
4993 return M+y
4994
4995def _dexp(c, e, p):
4996 """Compute an approximation to exp(c*10**e), with p decimal places of
4997 precision.
4998
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004999 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005000
5001 10**(p-1) <= d <= 10**p, and
5002 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5003
5004 In other words, d*10**f is an approximation to exp(c*10**e) with p
5005 digits of precision, and with an error in d of at most 1. This is
5006 almost, but not quite, the same as the error being < 1ulp: when d
5007 = 10**(p-1) the error could be up to 10 ulp."""
5008
5009 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5010 p += 2
5011
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005012 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005013 extra = max(0, e + len(str(c)) - 1)
5014 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005015
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005016 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005017 # rounding down
5018 shift = e+q
5019 if shift >= 0:
5020 cshift = c*10**shift
5021 else:
5022 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005023 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005024
5025 # reduce remainder back to original precision
5026 rem = _div_nearest(rem, 10**extra)
5027
5028 # error in result of _iexp < 120; error after division < 0.62
5029 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5030
5031def _dpower(xc, xe, yc, ye, p):
5032 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5033 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5034
5035 10**(p-1) <= c <= 10**p, and
5036 (c-1)*10**e < x**y < (c+1)*10**e
5037
5038 in other words, c*10**e is an approximation to x**y with p digits
5039 of precision, and with an error in c of at most 1. (This is
5040 almost, but not quite, the same as the error being < 1ulp: when c
5041 == 10**(p-1) we can only guarantee error < 10ulp.)
5042
5043 We assume that: x is positive and not equal to 1, and y is nonzero.
5044 """
5045
5046 # Find b such that 10**(b-1) <= |y| <= 10**b
5047 b = len(str(abs(yc))) + ye
5048
5049 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5050 lxc = _dlog(xc, xe, p+b+1)
5051
5052 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5053 shift = ye-b
5054 if shift >= 0:
5055 pc = lxc*yc*10**shift
5056 else:
5057 pc = _div_nearest(lxc*yc, 10**-shift)
5058
5059 if pc == 0:
5060 # we prefer a result that isn't exactly 1; this makes it
5061 # easier to compute a correctly rounded result in __pow__
5062 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5063 coeff, exp = 10**(p-1)+1, 1-p
5064 else:
5065 coeff, exp = 10**p-1, -p
5066 else:
5067 coeff, exp = _dexp(pc, -(p+1), p+1)
5068 coeff = _div_nearest(coeff, 10)
5069 exp += 1
5070
5071 return coeff, exp
5072
5073def _log10_lb(c, correction = {
5074 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5075 '6': 23, '7': 16, '8': 10, '9': 5}):
5076 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5077 if c <= 0:
5078 raise ValueError("The argument to _log10_lb should be nonnegative.")
5079 str_c = str(c)
5080 return 100*len(str_c) - correction[str_c[0]]
5081
Facundo Batista59c58842007-04-10 12:58:45 +00005082##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005083
Facundo Batista353750c2007-09-13 18:13:15 +00005084def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005085 """Convert other to Decimal.
5086
5087 Verifies that it's ok to use in an implicit construction.
5088 """
5089 if isinstance(other, Decimal):
5090 return other
5091 if isinstance(other, (int, long)):
5092 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005093 if raiseit:
5094 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005095 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005096
Facundo Batista59c58842007-04-10 12:58:45 +00005097##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005098
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005099# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005100# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005101
5102DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005103 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005104 traps=[DivisionByZero, Overflow, InvalidOperation],
5105 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005106 Emax=999999999,
5107 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005108 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005109)
5110
5111# Pre-made alternate contexts offered by the specification
5112# Don't change these; the user should be able to select these
5113# contexts and be able to reproduce results from other implementations
5114# of the spec.
5115
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005116BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005117 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005118 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5119 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005120)
5121
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005122ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005123 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005124 traps=[],
5125 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005126)
5127
5128
Facundo Batista72bc54f2007-11-23 17:59:00 +00005129##### crud for parsing strings #############################################
5130import re
5131
5132# Regular expression used for parsing numeric strings. Additional
5133# comments:
5134#
5135# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5136# whitespace. But note that the specification disallows whitespace in
5137# a numeric string.
5138#
5139# 2. For finite numbers (not infinities and NaNs) the body of the
5140# number between the optional sign and the optional exponent must have
5141# at least one decimal digit, possibly after the decimal point. The
5142# lookahead expression '(?=\d|\.\d)' checks this.
5143#
5144# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5145# other meaning for \d than the numbers [0-9].
5146
5147import re
5148_parser = re.compile(r""" # A numeric string consists of:
5149# \s*
5150 (?P<sign>[-+])? # an optional sign, followed by either...
5151 (
5152 (?=\d|\.\d) # ...a number (with at least one digit)
5153 (?P<int>\d*) # consisting of a (possibly empty) integer part
5154 (\.(?P<frac>\d*))? # followed by an optional fractional part
5155 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5156 |
5157 Inf(inity)? # ...an infinity, or...
5158 |
5159 (?P<signal>s)? # ...an (optionally signaling)
5160 NaN # NaN
5161 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5162 )
5163# \s*
Mark Dickinson59bc20b2008-01-12 01:56:00 +00005164 \Z
Facundo Batista72bc54f2007-11-23 17:59:00 +00005165""", re.VERBOSE | re.IGNORECASE).match
5166
Facundo Batista2ec74152007-12-03 17:55:00 +00005167_all_zeros = re.compile('0*$').match
5168_exact_half = re.compile('50*$').match
Facundo Batista72bc54f2007-11-23 17:59:00 +00005169del re
5170
5171
Facundo Batista59c58842007-04-10 12:58:45 +00005172##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005173
Facundo Batista59c58842007-04-10 12:58:45 +00005174# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005175Inf = Decimal('Inf')
5176negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005177NaN = Decimal('NaN')
5178Dec_0 = Decimal(0)
5179Dec_p1 = Decimal(1)
5180Dec_n1 = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005181
Facundo Batista59c58842007-04-10 12:58:45 +00005182# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005183Infsign = (Inf, negInf)
5184
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005185
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005186
5187if __name__ == '__main__':
5188 import doctest, sys
5189 doctest.testmod(sys.modules[__name__])