blob: 8b548216143486ba7f21543adba4e6492c3759e0 [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")
526 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000527
Facundo Batista72bc54f2007-11-23 17:59:00 +0000528 # Note that the coefficient, self._int, is actually stored as
529 # a string rather than as a tuple of digits. This speeds up
530 # the "digits to integer" and "integer to digits" conversions
531 # that are used in almost every arithmetic operation on
532 # Decimals. This is an internal detail: the as_tuple function
533 # and the Decimal constructor still deal with tuples of
534 # digits.
535
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000536 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000537
Facundo Batista0d157a02007-11-30 17:15:25 +0000538 # From a string
539 # REs insist on real strings, so we can too.
540 if isinstance(value, basestring):
541 m = _parser(value)
542 if m is None:
543 if context is None:
544 context = getcontext()
545 return context._raise_error(ConversionSyntax,
546 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000547
Facundo Batista0d157a02007-11-30 17:15:25 +0000548 if m.group('sign') == "-":
549 self._sign = 1
550 else:
551 self._sign = 0
552 intpart = m.group('int')
553 if intpart is not None:
554 # finite number
555 fracpart = m.group('frac')
556 exp = int(m.group('exp') or '0')
557 if fracpart is not None:
558 self._int = (intpart+fracpart).lstrip('0') or '0'
559 self._exp = exp - len(fracpart)
560 else:
561 self._int = intpart.lstrip('0') or '0'
562 self._exp = exp
563 self._is_special = False
564 else:
565 diag = m.group('diag')
566 if diag is not None:
567 # NaN
568 self._int = diag.lstrip('0')
569 if m.group('signal'):
570 self._exp = 'N'
571 else:
572 self._exp = 'n'
573 else:
574 # infinity
575 self._int = '0'
576 self._exp = 'F'
577 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000578 return self
579
580 # From an integer
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000581 if isinstance(value, (int,long)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000582 if value >= 0:
583 self._sign = 0
584 else:
585 self._sign = 1
586 self._exp = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +0000587 self._int = str(abs(value))
Facundo Batista0d157a02007-11-30 17:15:25 +0000588 self._is_special = False
589 return self
590
591 # From another decimal
592 if isinstance(value, Decimal):
593 self._exp = value._exp
594 self._sign = value._sign
595 self._int = value._int
596 self._is_special = value._is_special
597 return self
598
599 # From an internal working value
600 if isinstance(value, _WorkRep):
601 self._sign = value.sign
602 self._int = str(value.int)
603 self._exp = int(value.exp)
604 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000605 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000606
607 # tuple/list conversion (possibly from as_tuple())
608 if isinstance(value, (list,tuple)):
609 if len(value) != 3:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000610 raise ValueError('Invalid tuple size in creation of Decimal '
611 'from list or tuple. The list or tuple '
612 'should have exactly three elements.')
613 # process sign. The isinstance test rejects floats
614 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
615 raise ValueError("Invalid sign. The first value in the tuple "
616 "should be an integer; either 0 for a "
617 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000618 self._sign = value[0]
Facundo Batista9b5e2312007-10-19 19:25:57 +0000619 if value[2] == 'F':
620 # infinity: value[1] is ignored
Facundo Batista72bc54f2007-11-23 17:59:00 +0000621 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000622 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000623 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000624 else:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000625 # process and validate the digits in value[1]
626 digits = []
627 for digit in value[1]:
628 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
629 # skip leading zeros
630 if digits or digit != 0:
631 digits.append(digit)
632 else:
633 raise ValueError("The second value in the tuple must "
634 "be composed of integers in the range "
635 "0 through 9.")
636 if value[2] in ('n', 'N'):
637 # NaN: digits form the diagnostic
Facundo Batista72bc54f2007-11-23 17:59:00 +0000638 self._int = ''.join(map(str, digits))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000639 self._exp = value[2]
640 self._is_special = True
641 elif isinstance(value[2], (int, long)):
642 # finite number: digits give the coefficient
Facundo Batista72bc54f2007-11-23 17:59:00 +0000643 self._int = ''.join(map(str, digits or [0]))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000644 self._exp = value[2]
645 self._is_special = False
646 else:
647 raise ValueError("The third value in the tuple must "
648 "be an integer, or one of the "
649 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000650 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000651
Raymond Hettingerbf440692004-07-10 14:14:37 +0000652 if isinstance(value, float):
653 raise TypeError("Cannot convert float to Decimal. " +
654 "First convert the float to a string")
655
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000656 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000657
658 def _isnan(self):
659 """Returns whether the number is not actually one.
660
661 0 if a number
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000662 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000663 2 if sNaN
664 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000665 if self._is_special:
666 exp = self._exp
667 if exp == 'n':
668 return 1
669 elif exp == 'N':
670 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000671 return 0
672
673 def _isinfinity(self):
674 """Returns whether the number is infinite
675
676 0 if finite or not a number
677 1 if +INF
678 -1 if -INF
679 """
680 if self._exp == 'F':
681 if self._sign:
682 return -1
683 return 1
684 return 0
685
Facundo Batista353750c2007-09-13 18:13:15 +0000686 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000687 """Returns whether the number is not actually one.
688
689 if self, other are sNaN, signal
690 if self, other are NaN return nan
691 return 0
692
693 Done before operations.
694 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000695
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000696 self_is_nan = self._isnan()
697 if other is None:
698 other_is_nan = False
699 else:
700 other_is_nan = other._isnan()
701
702 if self_is_nan or other_is_nan:
703 if context is None:
704 context = getcontext()
705
706 if self_is_nan == 2:
707 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000708 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000709 if other_is_nan == 2:
710 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000711 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000712 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000713 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000714
Facundo Batista353750c2007-09-13 18:13:15 +0000715 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000716 return 0
717
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000718 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000719 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000720
Facundo Batista1a191df2007-10-02 17:01:24 +0000721 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000722 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000723 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000724
Facundo Batista353750c2007-09-13 18:13:15 +0000725 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000726 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000727 if other is NotImplemented:
Facundo Batista353750c2007-09-13 18:13:15 +0000728 # Never return NotImplemented
729 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000730
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000731 if self._is_special or other._is_special:
Facundo Batista353750c2007-09-13 18:13:15 +0000732 # check for nans, without raising on a signaling nan
733 if self._isnan() or other._isnan():
Facundo Batista59c58842007-04-10 12:58:45 +0000734 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000735
736 # INF = INF
737 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000738
Facundo Batista353750c2007-09-13 18:13:15 +0000739 # check for zeros; note that cmp(0, -0) should return 0
740 if not self:
741 if not other:
742 return 0
743 else:
744 return -((-1)**other._sign)
745 if not other:
746 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000747
Facundo Batista59c58842007-04-10 12:58:45 +0000748 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000749 if other._sign < self._sign:
750 return -1
751 if self._sign < other._sign:
752 return 1
753
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000754 self_adjusted = self.adjusted()
755 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000756 if self_adjusted == other_adjusted:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000757 self_padded = self._int + '0'*(self._exp - other._exp)
758 other_padded = other._int + '0'*(other._exp - self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +0000759 return cmp(self_padded, other_padded) * (-1)**self._sign
760 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000761 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000762 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000763 return -((-1)**self._sign)
764
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000765 def __eq__(self, other):
766 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000767 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000768 return self.__cmp__(other) == 0
769
770 def __ne__(self, other):
771 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000772 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000773 return self.__cmp__(other) != 0
774
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000775 def compare(self, other, context=None):
776 """Compares one to another.
777
778 -1 => a < b
779 0 => a = b
780 1 => a > b
781 NaN => one is NaN
782 Like __cmp__, but returns Decimal instances.
783 """
Facundo Batista353750c2007-09-13 18:13:15 +0000784 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000785
Facundo Batista59c58842007-04-10 12:58:45 +0000786 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000787 if (self._is_special or other and other._is_special):
788 ans = self._check_nans(other, context)
789 if ans:
790 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000791
Facundo Batista353750c2007-09-13 18:13:15 +0000792 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000793
794 def __hash__(self):
795 """x.__hash__() <==> hash(x)"""
796 # Decimal integers must hash the same as the ints
Facundo Batista52b25792008-01-08 12:25:20 +0000797 #
798 # The hash of a nonspecial noninteger Decimal must depend only
799 # on the value of that Decimal, and not on its representation.
800 # For example: hash(Decimal("100E-1")) == hash(Decimal("10")).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000801 if self._is_special:
802 if self._isnan():
803 raise TypeError('Cannot hash a NaN value.')
804 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000805 if not self:
806 return 0
807 if self._isinteger():
808 op = _WorkRep(self.to_integral_value())
809 # to make computation feasible for Decimals with large
810 # exponent, we use the fact that hash(n) == hash(m) for
811 # any two nonzero integers n and m such that (i) n and m
812 # have the same sign, and (ii) n is congruent to m modulo
813 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
814 # hash((-1)**s*c*pow(10, e, 2**64-1).
815 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Facundo Batista52b25792008-01-08 12:25:20 +0000816 # The value of a nonzero nonspecial Decimal instance is
817 # faithfully represented by the triple consisting of its sign,
818 # its adjusted exponent, and its coefficient with trailing
819 # zeros removed.
820 return hash((self._sign,
821 self._exp+len(self._int),
822 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000823
824 def as_tuple(self):
825 """Represents the number as a triple tuple.
826
827 To show the internals exactly as they are.
828 """
Raymond Hettinger097a1902008-01-11 02:24:13 +0000829 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000830
831 def __repr__(self):
832 """Represents the number as an instance of Decimal."""
833 # Invariant: eval(repr(d)) == d
834 return 'Decimal("%s")' % str(self)
835
Facundo Batista353750c2007-09-13 18:13:15 +0000836 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000837 """Return string representation of the number in scientific notation.
838
839 Captures all of the information in the underlying representation.
840 """
841
Facundo Batista62edb712007-12-03 16:29:52 +0000842 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000843 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +0000844 if self._exp == 'F':
845 return sign + 'Infinity'
846 elif self._exp == 'n':
847 return sign + 'NaN' + self._int
848 else: # self._exp == 'N'
849 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000850
Facundo Batista62edb712007-12-03 16:29:52 +0000851 # number of digits of self._int to left of decimal point
852 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000853
Facundo Batista62edb712007-12-03 16:29:52 +0000854 # dotplace is number of digits of self._int to the left of the
855 # decimal point in the mantissa of the output string (that is,
856 # after adjusting the exponent)
857 if self._exp <= 0 and leftdigits > -6:
858 # no exponent required
859 dotplace = leftdigits
860 elif not eng:
861 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000862 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +0000863 elif self._int == '0':
864 # engineering notation, zero
865 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000866 else:
Facundo Batista62edb712007-12-03 16:29:52 +0000867 # engineering notation, nonzero
868 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000869
Facundo Batista62edb712007-12-03 16:29:52 +0000870 if dotplace <= 0:
871 intpart = '0'
872 fracpart = '.' + '0'*(-dotplace) + self._int
873 elif dotplace >= len(self._int):
874 intpart = self._int+'0'*(dotplace-len(self._int))
875 fracpart = ''
876 else:
877 intpart = self._int[:dotplace]
878 fracpart = '.' + self._int[dotplace:]
879 if leftdigits == dotplace:
880 exp = ''
881 else:
882 if context is None:
883 context = getcontext()
884 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
885
886 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000887
888 def to_eng_string(self, context=None):
889 """Convert to engineering-type string.
890
891 Engineering notation has an exponent which is a multiple of 3, so there
892 are up to 3 digits left of the decimal place.
893
894 Same rules for when in exponential and when as a value as in __str__.
895 """
Facundo Batista353750c2007-09-13 18:13:15 +0000896 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000897
898 def __neg__(self, context=None):
899 """Returns a copy with the sign switched.
900
901 Rounds, if it has reason.
902 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000903 if self._is_special:
904 ans = self._check_nans(context=context)
905 if ans:
906 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000907
908 if not self:
909 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000910 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000911 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000912 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000913
914 if context is None:
915 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +0000916 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000917
918 def __pos__(self, context=None):
919 """Returns a copy, unless it is a sNaN.
920
921 Rounds the number (if more then precision digits)
922 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000923 if self._is_special:
924 ans = self._check_nans(context=context)
925 if ans:
926 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000927
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000928 if not self:
929 # + (-0) = 0
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000930 ans = self.copy_abs()
Facundo Batista353750c2007-09-13 18:13:15 +0000931 else:
932 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000933
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000934 if context is None:
935 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +0000936 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000937
Facundo Batistae64acfa2007-12-17 14:18:42 +0000938 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000939 """Returns the absolute value of self.
940
Facundo Batistae64acfa2007-12-17 14:18:42 +0000941 If the keyword argument 'round' is false, do not round. The
942 expression self.__abs__(round=False) is equivalent to
943 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000944 """
Facundo Batistae64acfa2007-12-17 14:18:42 +0000945 if not round:
946 return self.copy_abs()
947
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000948 if self._is_special:
949 ans = self._check_nans(context=context)
950 if ans:
951 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000952
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000953 if self._sign:
954 ans = self.__neg__(context=context)
955 else:
956 ans = self.__pos__(context=context)
957
958 return ans
959
960 def __add__(self, other, context=None):
961 """Returns self + other.
962
963 -INF + INF (or the reverse) cause InvalidOperation errors.
964 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000965 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000966 if other is NotImplemented:
967 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000968
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000969 if context is None:
970 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000972 if self._is_special or other._is_special:
973 ans = self._check_nans(other, context)
974 if ans:
975 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000976
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000977 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000978 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000979 if self._sign != other._sign and other._isinfinity():
980 return context._raise_error(InvalidOperation, '-INF + INF')
981 return Decimal(self)
982 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000983 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000984
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000985 exp = min(self._exp, other._exp)
986 negativezero = 0
987 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +0000988 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000989 negativezero = 1
990
991 if not self and not other:
992 sign = min(self._sign, other._sign)
993 if negativezero:
994 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +0000995 ans = _dec_from_triple(sign, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +0000996 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +0000997 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000998 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +0000999 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001000 ans = other._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001001 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001002 return ans
1003 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001004 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001005 ans = self._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001006 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001007 return ans
1008
1009 op1 = _WorkRep(self)
1010 op2 = _WorkRep(other)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001011 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001012
1013 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001014 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001015 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001016 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001017 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001018 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001019 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001020 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001021 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001022 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001023 if op1.sign == 1:
1024 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001025 op1.sign, op2.sign = op2.sign, op1.sign
1026 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001027 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001028 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001029 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001030 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001031 op1.sign, op2.sign = (0, 0)
1032 else:
1033 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001034 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001035
Raymond Hettinger17931de2004-10-27 06:21:46 +00001036 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001037 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001038 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001039 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001040
1041 result.exp = op1.exp
1042 ans = Decimal(result)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001043 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001044 return ans
1045
1046 __radd__ = __add__
1047
1048 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001049 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001050 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001051 if other is NotImplemented:
1052 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001053
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001054 if self._is_special or other._is_special:
1055 ans = self._check_nans(other, context=context)
1056 if ans:
1057 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001058
Facundo Batista353750c2007-09-13 18:13:15 +00001059 # self - other is computed as self + other.copy_negate()
1060 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001061
1062 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001063 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001064 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001065 if other is NotImplemented:
1066 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001067
Facundo Batista353750c2007-09-13 18:13:15 +00001068 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001069
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001070 def __mul__(self, other, context=None):
1071 """Return self * other.
1072
1073 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1074 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001075 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001076 if other is NotImplemented:
1077 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001078
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001079 if context is None:
1080 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001082 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001083
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001084 if self._is_special or other._is_special:
1085 ans = self._check_nans(other, context)
1086 if ans:
1087 return ans
1088
1089 if self._isinfinity():
1090 if not other:
1091 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1092 return Infsign[resultsign]
1093
1094 if other._isinfinity():
1095 if not self:
1096 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1097 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001098
1099 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001100
1101 # Special case for multiplying by zero
1102 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001103 ans = _dec_from_triple(resultsign, '0', resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001104 # Fixing in case the exponent is out of bounds
1105 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001106 return ans
1107
1108 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001109 if self._int == '1':
1110 ans = _dec_from_triple(resultsign, other._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001111 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001112 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001113 if other._int == '1':
1114 ans = _dec_from_triple(resultsign, self._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001115 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001116 return ans
1117
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001118 op1 = _WorkRep(self)
1119 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001120
Facundo Batista72bc54f2007-11-23 17:59:00 +00001121 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001122 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001123
1124 return ans
1125 __rmul__ = __mul__
1126
1127 def __div__(self, other, context=None):
1128 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001129 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001130 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001131 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001132
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001133 if context is None:
1134 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001135
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001136 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001137
1138 if self._is_special or other._is_special:
1139 ans = self._check_nans(other, context)
1140 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001141 return ans
1142
1143 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001144 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001145
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001146 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001147 return Infsign[sign]
1148
1149 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001150 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001151 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001152
1153 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001154 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001155 if not self:
1156 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001157 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001158
Facundo Batistacce8df22007-09-18 16:53:18 +00001159 if not self:
1160 exp = self._exp - other._exp
1161 coeff = 0
1162 else:
1163 # OK, so neither = 0, INF or NaN
1164 shift = len(other._int) - len(self._int) + context.prec + 1
1165 exp = self._exp - other._exp - shift
1166 op1 = _WorkRep(self)
1167 op2 = _WorkRep(other)
1168 if shift >= 0:
1169 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1170 else:
1171 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1172 if remainder:
1173 # result is not exact; adjust to ensure correct rounding
1174 if coeff % 5 == 0:
1175 coeff += 1
1176 else:
1177 # result is exact; get as close to ideal exponent as possible
1178 ideal_exp = self._exp - other._exp
1179 while exp < ideal_exp and coeff % 10 == 0:
1180 coeff //= 10
1181 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001182
Facundo Batista72bc54f2007-11-23 17:59:00 +00001183 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001184 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001185
Facundo Batistacce8df22007-09-18 16:53:18 +00001186 __truediv__ = __div__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001187
Facundo Batistacce8df22007-09-18 16:53:18 +00001188 def _divide(self, other, context):
1189 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001190
Facundo Batistacce8df22007-09-18 16:53:18 +00001191 Assumes that neither self nor other is a NaN, that self is not
1192 infinite and that other is nonzero.
1193 """
1194 sign = self._sign ^ other._sign
1195 if other._isinfinity():
1196 ideal_exp = self._exp
1197 else:
1198 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001199
Facundo Batistacce8df22007-09-18 16:53:18 +00001200 expdiff = self.adjusted() - other.adjusted()
1201 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001202 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001203 self._rescale(ideal_exp, context.rounding))
1204 if expdiff <= context.prec:
1205 op1 = _WorkRep(self)
1206 op2 = _WorkRep(other)
1207 if op1.exp >= op2.exp:
1208 op1.int *= 10**(op1.exp - op2.exp)
1209 else:
1210 op2.int *= 10**(op2.exp - op1.exp)
1211 q, r = divmod(op1.int, op2.int)
1212 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001213 return (_dec_from_triple(sign, str(q), 0),
1214 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001215
Facundo Batistacce8df22007-09-18 16:53:18 +00001216 # Here the quotient is too large to be representable
1217 ans = context._raise_error(DivisionImpossible,
1218 'quotient too large in //, % or divmod')
1219 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001220
1221 def __rdiv__(self, other, context=None):
1222 """Swaps self/other and returns __div__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001223 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001224 if other is NotImplemented:
1225 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001226 return other.__div__(self, context=context)
1227 __rtruediv__ = __rdiv__
1228
1229 def __divmod__(self, other, context=None):
1230 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001231 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001232 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001233 other = _convert_other(other)
1234 if other is NotImplemented:
1235 return other
1236
1237 if context is None:
1238 context = getcontext()
1239
1240 ans = self._check_nans(other, context)
1241 if ans:
1242 return (ans, ans)
1243
1244 sign = self._sign ^ other._sign
1245 if self._isinfinity():
1246 if other._isinfinity():
1247 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1248 return ans, ans
1249 else:
1250 return (Infsign[sign],
1251 context._raise_error(InvalidOperation, 'INF % x'))
1252
1253 if not other:
1254 if not self:
1255 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1256 return ans, ans
1257 else:
1258 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1259 context._raise_error(InvalidOperation, 'x % 0'))
1260
1261 quotient, remainder = self._divide(other, context)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001262 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001263 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001264
1265 def __rdivmod__(self, other, context=None):
1266 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001267 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001268 if other is NotImplemented:
1269 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001270 return other.__divmod__(self, context=context)
1271
1272 def __mod__(self, other, context=None):
1273 """
1274 self % other
1275 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001276 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001277 if other is NotImplemented:
1278 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001279
Facundo Batistacce8df22007-09-18 16:53:18 +00001280 if context is None:
1281 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001282
Facundo Batistacce8df22007-09-18 16:53:18 +00001283 ans = self._check_nans(other, context)
1284 if ans:
1285 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001286
Facundo Batistacce8df22007-09-18 16:53:18 +00001287 if self._isinfinity():
1288 return context._raise_error(InvalidOperation, 'INF % x')
1289 elif not other:
1290 if self:
1291 return context._raise_error(InvalidOperation, 'x % 0')
1292 else:
1293 return context._raise_error(DivisionUndefined, '0 % 0')
1294
1295 remainder = self._divide(other, context)[1]
Facundo Batistae64acfa2007-12-17 14:18:42 +00001296 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001297 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001298
1299 def __rmod__(self, other, context=None):
1300 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001301 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001302 if other is NotImplemented:
1303 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001304 return other.__mod__(self, context=context)
1305
1306 def remainder_near(self, other, context=None):
1307 """
1308 Remainder nearest to 0- abs(remainder-near) <= other/2
1309 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001310 if context is None:
1311 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001312
Facundo Batista353750c2007-09-13 18:13:15 +00001313 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001314
Facundo Batista353750c2007-09-13 18:13:15 +00001315 ans = self._check_nans(other, context)
1316 if ans:
1317 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001318
Facundo Batista353750c2007-09-13 18:13:15 +00001319 # self == +/-infinity -> InvalidOperation
1320 if self._isinfinity():
1321 return context._raise_error(InvalidOperation,
1322 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001323
Facundo Batista353750c2007-09-13 18:13:15 +00001324 # other == 0 -> either InvalidOperation or DivisionUndefined
1325 if not other:
1326 if self:
1327 return context._raise_error(InvalidOperation,
1328 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001329 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001330 return context._raise_error(DivisionUndefined,
1331 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001332
Facundo Batista353750c2007-09-13 18:13:15 +00001333 # other = +/-infinity -> remainder = self
1334 if other._isinfinity():
1335 ans = Decimal(self)
1336 return ans._fix(context)
1337
1338 # self = 0 -> remainder = self, with ideal exponent
1339 ideal_exponent = min(self._exp, other._exp)
1340 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001341 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001342 return ans._fix(context)
1343
1344 # catch most cases of large or small quotient
1345 expdiff = self.adjusted() - other.adjusted()
1346 if expdiff >= context.prec + 1:
1347 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001348 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001349 if expdiff <= -2:
1350 # expdiff <= -2 => abs(self/other) < 0.1
1351 ans = self._rescale(ideal_exponent, context.rounding)
1352 return ans._fix(context)
1353
1354 # adjust both arguments to have the same exponent, then divide
1355 op1 = _WorkRep(self)
1356 op2 = _WorkRep(other)
1357 if op1.exp >= op2.exp:
1358 op1.int *= 10**(op1.exp - op2.exp)
1359 else:
1360 op2.int *= 10**(op2.exp - op1.exp)
1361 q, r = divmod(op1.int, op2.int)
1362 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1363 # 10**ideal_exponent. Apply correction to ensure that
1364 # abs(remainder) <= abs(other)/2
1365 if 2*r + (q&1) > op2.int:
1366 r -= op2.int
1367 q += 1
1368
1369 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001370 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001371
1372 # result has same sign as self unless r is negative
1373 sign = self._sign
1374 if r < 0:
1375 sign = 1-sign
1376 r = -r
1377
Facundo Batista72bc54f2007-11-23 17:59:00 +00001378 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001379 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001380
1381 def __floordiv__(self, other, context=None):
1382 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001383 other = _convert_other(other)
1384 if other is NotImplemented:
1385 return other
1386
1387 if context is None:
1388 context = getcontext()
1389
1390 ans = self._check_nans(other, context)
1391 if ans:
1392 return ans
1393
1394 if self._isinfinity():
1395 if other._isinfinity():
1396 return context._raise_error(InvalidOperation, 'INF // INF')
1397 else:
1398 return Infsign[self._sign ^ other._sign]
1399
1400 if not other:
1401 if self:
1402 return context._raise_error(DivisionByZero, 'x // 0',
1403 self._sign ^ other._sign)
1404 else:
1405 return context._raise_error(DivisionUndefined, '0 // 0')
1406
1407 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001408
1409 def __rfloordiv__(self, other, context=None):
1410 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001411 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001412 if other is NotImplemented:
1413 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001414 return other.__floordiv__(self, context=context)
1415
1416 def __float__(self):
1417 """Float representation."""
1418 return float(str(self))
1419
1420 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001421 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001422 if self._is_special:
1423 if self._isnan():
1424 context = getcontext()
1425 return context._raise_error(InvalidContext)
1426 elif self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001427 raise OverflowError("Cannot convert infinity to long")
Facundo Batista353750c2007-09-13 18:13:15 +00001428 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001429 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001430 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001431 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001432 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001433
1434 def __long__(self):
1435 """Converts to a long.
1436
1437 Equivalent to long(int(self))
1438 """
1439 return long(self.__int__())
1440
Facundo Batista353750c2007-09-13 18:13:15 +00001441 def _fix_nan(self, context):
1442 """Decapitate the payload of a NaN to fit the context"""
1443 payload = self._int
1444
1445 # maximum length of payload is precision if _clamp=0,
1446 # precision-1 if _clamp=1.
1447 max_payload_len = context.prec - context._clamp
1448 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001449 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1450 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001451 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001452
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001453 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001454 """Round if it is necessary to keep self within prec precision.
1455
1456 Rounds and fixes the exponent. Does not raise on a sNaN.
1457
1458 Arguments:
1459 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001460 context - context used.
1461 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001462
Facundo Batista353750c2007-09-13 18:13:15 +00001463 if self._is_special:
1464 if self._isnan():
1465 # decapitate payload if necessary
1466 return self._fix_nan(context)
1467 else:
1468 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001469 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001470
Facundo Batista353750c2007-09-13 18:13:15 +00001471 # if self is zero then exponent should be between Etiny and
1472 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1473 Etiny = context.Etiny()
1474 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001475 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001476 exp_max = [context.Emax, Etop][context._clamp]
1477 new_exp = min(max(self._exp, Etiny), exp_max)
1478 if new_exp != self._exp:
1479 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001480 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001481 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001482 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001483
1484 # exp_min is the smallest allowable exponent of the result,
1485 # equal to max(self.adjusted()-context.prec+1, Etiny)
1486 exp_min = len(self._int) + self._exp - context.prec
1487 if exp_min > Etop:
1488 # overflow: exp_min > Etop iff self.adjusted() > Emax
1489 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001490 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001491 return context._raise_error(Overflow, 'above Emax', self._sign)
1492 self_is_subnormal = exp_min < Etiny
1493 if self_is_subnormal:
1494 context._raise_error(Subnormal)
1495 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001496
Facundo Batista353750c2007-09-13 18:13:15 +00001497 # round if self has too many digits
1498 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001499 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001500 digits = len(self._int) + self._exp - exp_min
1501 if digits < 0:
1502 self = _dec_from_triple(self._sign, '1', exp_min-1)
1503 digits = 0
1504 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1505 changed = this_function(digits)
1506 coeff = self._int[:digits] or '0'
1507 if changed == 1:
1508 coeff = str(int(coeff)+1)
1509 ans = _dec_from_triple(self._sign, coeff, exp_min)
1510
1511 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001512 context._raise_error(Inexact)
1513 if self_is_subnormal:
1514 context._raise_error(Underflow)
1515 if not ans:
1516 # raise Clamped on underflow to 0
1517 context._raise_error(Clamped)
1518 elif len(ans._int) == context.prec+1:
1519 # we get here only if rescaling rounds the
1520 # cofficient up to exactly 10**context.prec
1521 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001522 ans = _dec_from_triple(ans._sign,
1523 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001524 else:
1525 # Inexact and Rounded have already been raised
1526 ans = context._raise_error(Overflow, 'above Emax',
1527 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001528 return ans
1529
Facundo Batista353750c2007-09-13 18:13:15 +00001530 # fold down if _clamp == 1 and self has too few digits
1531 if context._clamp == 1 and self._exp > Etop:
1532 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001533 self_padded = self._int + '0'*(self._exp - Etop)
1534 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001535
Facundo Batista353750c2007-09-13 18:13:15 +00001536 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001537 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001538
1539 _pick_rounding_function = {}
1540
Facundo Batista353750c2007-09-13 18:13:15 +00001541 # for each of the rounding functions below:
1542 # self is a finite, nonzero Decimal
1543 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001544 #
1545 # each function returns either -1, 0, or 1, as follows:
1546 # 1 indicates that self should be rounded up (away from zero)
1547 # 0 indicates that self should be truncated, and that all the
1548 # digits to be truncated are zeros (so the value is unchanged)
1549 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001550
1551 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001552 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001553 if _all_zeros(self._int, prec):
1554 return 0
1555 else:
1556 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001557
Facundo Batista353750c2007-09-13 18:13:15 +00001558 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001559 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001560 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001561
Facundo Batista353750c2007-09-13 18:13:15 +00001562 def _round_half_up(self, prec):
1563 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001564 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001565 return 1
1566 elif _all_zeros(self._int, prec):
1567 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001568 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001569 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001570
1571 def _round_half_down(self, prec):
1572 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001573 if _exact_half(self._int, prec):
1574 return -1
1575 else:
1576 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001577
1578 def _round_half_even(self, prec):
1579 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001580 if _exact_half(self._int, prec) and \
1581 (prec == 0 or self._int[prec-1] in '02468'):
1582 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001583 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001584 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001585
1586 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001587 """Rounds up (not away from 0 if negative.)"""
1588 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001589 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001590 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001591 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001592
Facundo Batista353750c2007-09-13 18:13:15 +00001593 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001594 """Rounds down (not towards 0 if negative)"""
1595 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001596 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001597 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001598 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001599
Facundo Batista353750c2007-09-13 18:13:15 +00001600 def _round_05up(self, prec):
1601 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001602 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001603 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001604 else:
1605 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001606
Facundo Batista353750c2007-09-13 18:13:15 +00001607 def fma(self, other, third, context=None):
1608 """Fused multiply-add.
1609
1610 Returns self*other+third with no rounding of the intermediate
1611 product self*other.
1612
1613 self and other are multiplied together, with no rounding of
1614 the result. The third operand is then added to the result,
1615 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001616 """
Facundo Batista353750c2007-09-13 18:13:15 +00001617
1618 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001619
1620 # compute product; raise InvalidOperation if either operand is
1621 # a signaling NaN or if the product is zero times infinity.
1622 if self._is_special or other._is_special:
1623 if context is None:
1624 context = getcontext()
1625 if self._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001626 return context._raise_error(InvalidOperation, 'sNaN', self)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001627 if other._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001628 return context._raise_error(InvalidOperation, 'sNaN', other)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001629 if self._exp == 'n':
1630 product = self
1631 elif other._exp == 'n':
1632 product = other
1633 elif self._exp == 'F':
1634 if not other:
1635 return context._raise_error(InvalidOperation,
1636 'INF * 0 in fma')
1637 product = Infsign[self._sign ^ other._sign]
1638 elif other._exp == 'F':
1639 if not self:
1640 return context._raise_error(InvalidOperation,
1641 '0 * INF in fma')
1642 product = Infsign[self._sign ^ other._sign]
1643 else:
1644 product = _dec_from_triple(self._sign ^ other._sign,
1645 str(int(self._int) * int(other._int)),
1646 self._exp + other._exp)
1647
Facundo Batista353750c2007-09-13 18:13:15 +00001648 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001649 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001650
Facundo Batista353750c2007-09-13 18:13:15 +00001651 def _power_modulo(self, other, modulo, context=None):
1652 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001653
Facundo Batista353750c2007-09-13 18:13:15 +00001654 # if can't convert other and modulo to Decimal, raise
1655 # TypeError; there's no point returning NotImplemented (no
1656 # equivalent of __rpow__ for three argument pow)
1657 other = _convert_other(other, raiseit=True)
1658 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001659
Facundo Batista353750c2007-09-13 18:13:15 +00001660 if context is None:
1661 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001662
Facundo Batista353750c2007-09-13 18:13:15 +00001663 # deal with NaNs: if there are any sNaNs then first one wins,
1664 # (i.e. behaviour for NaNs is identical to that of fma)
1665 self_is_nan = self._isnan()
1666 other_is_nan = other._isnan()
1667 modulo_is_nan = modulo._isnan()
1668 if self_is_nan or other_is_nan or modulo_is_nan:
1669 if self_is_nan == 2:
1670 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001671 self)
Facundo Batista353750c2007-09-13 18:13:15 +00001672 if other_is_nan == 2:
1673 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001674 other)
Facundo Batista353750c2007-09-13 18:13:15 +00001675 if modulo_is_nan == 2:
1676 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001677 modulo)
Facundo Batista353750c2007-09-13 18:13:15 +00001678 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001679 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001680 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001681 return other._fix_nan(context)
1682 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001683
Facundo Batista353750c2007-09-13 18:13:15 +00001684 # check inputs: we apply same restrictions as Python's pow()
1685 if not (self._isinteger() and
1686 other._isinteger() and
1687 modulo._isinteger()):
1688 return context._raise_error(InvalidOperation,
1689 'pow() 3rd argument not allowed '
1690 'unless all arguments are integers')
1691 if other < 0:
1692 return context._raise_error(InvalidOperation,
1693 'pow() 2nd argument cannot be '
1694 'negative when 3rd argument specified')
1695 if not modulo:
1696 return context._raise_error(InvalidOperation,
1697 'pow() 3rd argument cannot be 0')
1698
1699 # additional restriction for decimal: the modulus must be less
1700 # than 10**prec in absolute value
1701 if modulo.adjusted() >= context.prec:
1702 return context._raise_error(InvalidOperation,
1703 'insufficient precision: pow() 3rd '
1704 'argument must not have more than '
1705 'precision digits')
1706
1707 # define 0**0 == NaN, for consistency with two-argument pow
1708 # (even though it hurts!)
1709 if not other and not self:
1710 return context._raise_error(InvalidOperation,
1711 'at least one of pow() 1st argument '
1712 'and 2nd argument must be nonzero ;'
1713 '0**0 is not defined')
1714
1715 # compute sign of result
1716 if other._iseven():
1717 sign = 0
1718 else:
1719 sign = self._sign
1720
1721 # convert modulo to a Python integer, and self and other to
1722 # Decimal integers (i.e. force their exponents to be >= 0)
1723 modulo = abs(int(modulo))
1724 base = _WorkRep(self.to_integral_value())
1725 exponent = _WorkRep(other.to_integral_value())
1726
1727 # compute result using integer pow()
1728 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1729 for i in xrange(exponent.exp):
1730 base = pow(base, 10, modulo)
1731 base = pow(base, exponent.int, modulo)
1732
Facundo Batista72bc54f2007-11-23 17:59:00 +00001733 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001734
1735 def _power_exact(self, other, p):
1736 """Attempt to compute self**other exactly.
1737
1738 Given Decimals self and other and an integer p, attempt to
1739 compute an exact result for the power self**other, with p
1740 digits of precision. Return None if self**other is not
1741 exactly representable in p digits.
1742
1743 Assumes that elimination of special cases has already been
1744 performed: self and other must both be nonspecial; self must
1745 be positive and not numerically equal to 1; other must be
1746 nonzero. For efficiency, other._exp should not be too large,
1747 so that 10**abs(other._exp) is a feasible calculation."""
1748
1749 # In the comments below, we write x for the value of self and
1750 # y for the value of other. Write x = xc*10**xe and y =
1751 # yc*10**ye.
1752
1753 # The main purpose of this method is to identify the *failure*
1754 # of x**y to be exactly representable with as little effort as
1755 # possible. So we look for cheap and easy tests that
1756 # eliminate the possibility of x**y being exact. Only if all
1757 # these tests are passed do we go on to actually compute x**y.
1758
1759 # Here's the main idea. First normalize both x and y. We
1760 # express y as a rational m/n, with m and n relatively prime
1761 # and n>0. Then for x**y to be exactly representable (at
1762 # *any* precision), xc must be the nth power of a positive
1763 # integer and xe must be divisible by n. If m is negative
1764 # then additionally xc must be a power of either 2 or 5, hence
1765 # a power of 2**n or 5**n.
1766 #
1767 # There's a limit to how small |y| can be: if y=m/n as above
1768 # then:
1769 #
1770 # (1) if xc != 1 then for the result to be representable we
1771 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1772 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1773 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1774 # representable.
1775 #
1776 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1777 # |y| < 1/|xe| then the result is not representable.
1778 #
1779 # Note that since x is not equal to 1, at least one of (1) and
1780 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1781 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1782 #
1783 # There's also a limit to how large y can be, at least if it's
1784 # positive: the normalized result will have coefficient xc**y,
1785 # so if it's representable then xc**y < 10**p, and y <
1786 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1787 # not exactly representable.
1788
1789 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1790 # so |y| < 1/xe and the result is not representable.
1791 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1792 # < 1/nbits(xc).
1793
1794 x = _WorkRep(self)
1795 xc, xe = x.int, x.exp
1796 while xc % 10 == 0:
1797 xc //= 10
1798 xe += 1
1799
1800 y = _WorkRep(other)
1801 yc, ye = y.int, y.exp
1802 while yc % 10 == 0:
1803 yc //= 10
1804 ye += 1
1805
1806 # case where xc == 1: result is 10**(xe*y), with xe*y
1807 # required to be an integer
1808 if xc == 1:
1809 if ye >= 0:
1810 exponent = xe*yc*10**ye
1811 else:
1812 exponent, remainder = divmod(xe*yc, 10**-ye)
1813 if remainder:
1814 return None
1815 if y.sign == 1:
1816 exponent = -exponent
1817 # if other is a nonnegative integer, use ideal exponent
1818 if other._isinteger() and other._sign == 0:
1819 ideal_exponent = self._exp*int(other)
1820 zeros = min(exponent-ideal_exponent, p-1)
1821 else:
1822 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001823 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001824
1825 # case where y is negative: xc must be either a power
1826 # of 2 or a power of 5.
1827 if y.sign == 1:
1828 last_digit = xc % 10
1829 if last_digit in (2,4,6,8):
1830 # quick test for power of 2
1831 if xc & -xc != xc:
1832 return None
1833 # now xc is a power of 2; e is its exponent
1834 e = _nbits(xc)-1
1835 # find e*y and xe*y; both must be integers
1836 if ye >= 0:
1837 y_as_int = yc*10**ye
1838 e = e*y_as_int
1839 xe = xe*y_as_int
1840 else:
1841 ten_pow = 10**-ye
1842 e, remainder = divmod(e*yc, ten_pow)
1843 if remainder:
1844 return None
1845 xe, remainder = divmod(xe*yc, ten_pow)
1846 if remainder:
1847 return None
1848
1849 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1850 return None
1851 xc = 5**e
1852
1853 elif last_digit == 5:
1854 # e >= log_5(xc) if xc is a power of 5; we have
1855 # equality all the way up to xc=5**2658
1856 e = _nbits(xc)*28//65
1857 xc, remainder = divmod(5**e, xc)
1858 if remainder:
1859 return None
1860 while xc % 5 == 0:
1861 xc //= 5
1862 e -= 1
1863 if ye >= 0:
1864 y_as_integer = yc*10**ye
1865 e = e*y_as_integer
1866 xe = xe*y_as_integer
1867 else:
1868 ten_pow = 10**-ye
1869 e, remainder = divmod(e*yc, ten_pow)
1870 if remainder:
1871 return None
1872 xe, remainder = divmod(xe*yc, ten_pow)
1873 if remainder:
1874 return None
1875 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1876 return None
1877 xc = 2**e
1878 else:
1879 return None
1880
1881 if xc >= 10**p:
1882 return None
1883 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00001884 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00001885
1886 # now y is positive; find m and n such that y = m/n
1887 if ye >= 0:
1888 m, n = yc*10**ye, 1
1889 else:
1890 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1891 return None
1892 xc_bits = _nbits(xc)
1893 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1894 return None
1895 m, n = yc, 10**(-ye)
1896 while m % 2 == n % 2 == 0:
1897 m //= 2
1898 n //= 2
1899 while m % 5 == n % 5 == 0:
1900 m //= 5
1901 n //= 5
1902
1903 # compute nth root of xc*10**xe
1904 if n > 1:
1905 # if 1 < xc < 2**n then xc isn't an nth power
1906 if xc != 1 and xc_bits <= n:
1907 return None
1908
1909 xe, rem = divmod(xe, n)
1910 if rem != 0:
1911 return None
1912
1913 # compute nth root of xc using Newton's method
1914 a = 1L << -(-_nbits(xc)//n) # initial estimate
1915 while True:
1916 q, r = divmod(xc, a**(n-1))
1917 if a <= q:
1918 break
1919 else:
1920 a = (a*(n-1) + q)//n
1921 if not (a == q and r == 0):
1922 return None
1923 xc = a
1924
1925 # now xc*10**xe is the nth root of the original xc*10**xe
1926 # compute mth power of xc*10**xe
1927
1928 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1929 # 10**p and the result is not representable.
1930 if xc > 1 and m > p*100//_log10_lb(xc):
1931 return None
1932 xc = xc**m
1933 xe *= m
1934 if xc > 10**p:
1935 return None
1936
1937 # by this point the result *is* exactly representable
1938 # adjust the exponent to get as close as possible to the ideal
1939 # exponent, if necessary
1940 str_xc = str(xc)
1941 if other._isinteger() and other._sign == 0:
1942 ideal_exponent = self._exp*int(other)
1943 zeros = min(xe-ideal_exponent, p-len(str_xc))
1944 else:
1945 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001946 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001947
1948 def __pow__(self, other, modulo=None, context=None):
1949 """Return self ** other [ % modulo].
1950
1951 With two arguments, compute self**other.
1952
1953 With three arguments, compute (self**other) % modulo. For the
1954 three argument form, the following restrictions on the
1955 arguments hold:
1956
1957 - all three arguments must be integral
1958 - other must be nonnegative
1959 - either self or other (or both) must be nonzero
1960 - modulo must be nonzero and must have at most p digits,
1961 where p is the context precision.
1962
1963 If any of these restrictions is violated the InvalidOperation
1964 flag is raised.
1965
1966 The result of pow(self, other, modulo) is identical to the
1967 result that would be obtained by computing (self**other) %
1968 modulo with unbounded precision, but is computed more
1969 efficiently. It is always exact.
1970 """
1971
1972 if modulo is not None:
1973 return self._power_modulo(other, modulo, context)
1974
1975 other = _convert_other(other)
1976 if other is NotImplemented:
1977 return other
1978
1979 if context is None:
1980 context = getcontext()
1981
1982 # either argument is a NaN => result is NaN
1983 ans = self._check_nans(other, context)
1984 if ans:
1985 return ans
1986
1987 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1988 if not other:
1989 if not self:
1990 return context._raise_error(InvalidOperation, '0 ** 0')
1991 else:
1992 return Dec_p1
1993
1994 # result has sign 1 iff self._sign is 1 and other is an odd integer
1995 result_sign = 0
1996 if self._sign == 1:
1997 if other._isinteger():
1998 if not other._iseven():
1999 result_sign = 1
2000 else:
2001 # -ve**noninteger = NaN
2002 # (-0)**noninteger = 0**noninteger
2003 if self:
2004 return context._raise_error(InvalidOperation,
2005 'x ** y with x negative and y not an integer')
2006 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002007 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002008
2009 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2010 if not self:
2011 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002012 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002013 else:
2014 return Infsign[result_sign]
2015
2016 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002017 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002018 if other._sign == 0:
2019 return Infsign[result_sign]
2020 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002021 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002022
Facundo Batista353750c2007-09-13 18:13:15 +00002023 # 1**other = 1, but the choice of exponent and the flags
2024 # depend on the exponent of self, and on whether other is a
2025 # positive integer, a negative integer, or neither
2026 if self == Dec_p1:
2027 if other._isinteger():
2028 # exp = max(self._exp*max(int(other), 0),
2029 # 1-context.prec) but evaluating int(other) directly
2030 # is dangerous until we know other is small (other
2031 # could be 1e999999999)
2032 if other._sign == 1:
2033 multiplier = 0
2034 elif other > context.prec:
2035 multiplier = context.prec
2036 else:
2037 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002038
Facundo Batista353750c2007-09-13 18:13:15 +00002039 exp = self._exp * multiplier
2040 if exp < 1-context.prec:
2041 exp = 1-context.prec
2042 context._raise_error(Rounded)
2043 else:
2044 context._raise_error(Inexact)
2045 context._raise_error(Rounded)
2046 exp = 1-context.prec
2047
Facundo Batista72bc54f2007-11-23 17:59:00 +00002048 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002049
2050 # compute adjusted exponent of self
2051 self_adj = self.adjusted()
2052
2053 # self ** infinity is infinity if self > 1, 0 if self < 1
2054 # self ** -infinity is infinity if self < 1, 0 if self > 1
2055 if other._isinfinity():
2056 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002057 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002058 else:
2059 return Infsign[result_sign]
2060
2061 # from here on, the result always goes through the call
2062 # to _fix at the end of this function.
2063 ans = None
2064
2065 # crude test to catch cases of extreme overflow/underflow. If
2066 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2067 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2068 # self**other >= 10**(Emax+1), so overflow occurs. The test
2069 # for underflow is similar.
2070 bound = self._log10_exp_bound() + other.adjusted()
2071 if (self_adj >= 0) == (other._sign == 0):
2072 # self > 1 and other +ve, or self < 1 and other -ve
2073 # possibility of overflow
2074 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002075 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002076 else:
2077 # self > 1 and other -ve, or self < 1 and other +ve
2078 # possibility of underflow to 0
2079 Etiny = context.Etiny()
2080 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002081 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002082
2083 # try for an exact result with precision +1
2084 if ans is None:
2085 ans = self._power_exact(other, context.prec + 1)
2086 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002087 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002088
2089 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2090 if ans is None:
2091 p = context.prec
2092 x = _WorkRep(self)
2093 xc, xe = x.int, x.exp
2094 y = _WorkRep(other)
2095 yc, ye = y.int, y.exp
2096 if y.sign == 1:
2097 yc = -yc
2098
2099 # compute correctly rounded result: start with precision +3,
2100 # then increase precision until result is unambiguously roundable
2101 extra = 3
2102 while True:
2103 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2104 if coeff % (5*10**(len(str(coeff))-p-1)):
2105 break
2106 extra += 3
2107
Facundo Batista72bc54f2007-11-23 17:59:00 +00002108 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002109
2110 # the specification says that for non-integer other we need to
2111 # raise Inexact, even when the result is actually exact. In
2112 # the same way, we need to raise Underflow here if the result
2113 # is subnormal. (The call to _fix will take care of raising
2114 # Rounded and Subnormal, as usual.)
2115 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002116 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002117 # pad with zeros up to length context.prec+1 if necessary
2118 if len(ans._int) <= context.prec:
2119 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002120 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2121 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002122 if ans.adjusted() < context.Emin:
2123 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002124
Facundo Batista353750c2007-09-13 18:13:15 +00002125 # unlike exp, ln and log10, the power function respects the
2126 # rounding mode; no need to use ROUND_HALF_EVEN here
2127 ans = ans._fix(context)
2128 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002129
2130 def __rpow__(self, other, context=None):
2131 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002132 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002133 if other is NotImplemented:
2134 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002135 return other.__pow__(self, context=context)
2136
2137 def normalize(self, context=None):
2138 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002139
Facundo Batista353750c2007-09-13 18:13:15 +00002140 if context is None:
2141 context = getcontext()
2142
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002143 if self._is_special:
2144 ans = self._check_nans(context=context)
2145 if ans:
2146 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002147
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002148 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002149 if dup._isinfinity():
2150 return dup
2151
2152 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002153 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002154 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002155 end = len(dup._int)
2156 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002157 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002158 exp += 1
2159 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002160 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002161
Facundo Batistabd2fe832007-09-13 18:42:09 +00002162 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002163 """Quantize self so its exponent is the same as that of exp.
2164
2165 Similar to self._rescale(exp._exp) but with error checking.
2166 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002167 exp = _convert_other(exp, raiseit=True)
2168
Facundo Batista353750c2007-09-13 18:13:15 +00002169 if context is None:
2170 context = getcontext()
2171 if rounding is None:
2172 rounding = context.rounding
2173
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002174 if self._is_special or exp._is_special:
2175 ans = self._check_nans(exp, context)
2176 if ans:
2177 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002178
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002179 if exp._isinfinity() or self._isinfinity():
2180 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002181 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002182 return context._raise_error(InvalidOperation,
2183 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002184
Facundo Batistabd2fe832007-09-13 18:42:09 +00002185 # if we're not watching exponents, do a simple rescale
2186 if not watchexp:
2187 ans = self._rescale(exp._exp, rounding)
2188 # raise Inexact and Rounded where appropriate
2189 if ans._exp > self._exp:
2190 context._raise_error(Rounded)
2191 if ans != self:
2192 context._raise_error(Inexact)
2193 return ans
2194
Facundo Batista353750c2007-09-13 18:13:15 +00002195 # exp._exp should be between Etiny and Emax
2196 if not (context.Etiny() <= exp._exp <= context.Emax):
2197 return context._raise_error(InvalidOperation,
2198 'target exponent out of bounds in quantize')
2199
2200 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002201 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002202 return ans._fix(context)
2203
2204 self_adjusted = self.adjusted()
2205 if self_adjusted > context.Emax:
2206 return context._raise_error(InvalidOperation,
2207 'exponent of quantize result too large for current context')
2208 if self_adjusted - exp._exp + 1 > context.prec:
2209 return context._raise_error(InvalidOperation,
2210 'quantize result has too many digits for current context')
2211
2212 ans = self._rescale(exp._exp, rounding)
2213 if ans.adjusted() > context.Emax:
2214 return context._raise_error(InvalidOperation,
2215 'exponent of quantize result too large for current context')
2216 if len(ans._int) > context.prec:
2217 return context._raise_error(InvalidOperation,
2218 'quantize result has too many digits for current context')
2219
2220 # raise appropriate flags
2221 if ans._exp > self._exp:
2222 context._raise_error(Rounded)
2223 if ans != self:
2224 context._raise_error(Inexact)
2225 if ans and ans.adjusted() < context.Emin:
2226 context._raise_error(Subnormal)
2227
2228 # call to fix takes care of any necessary folddown
2229 ans = ans._fix(context)
2230 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002231
2232 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002233 """Return True if self and other have the same exponent; otherwise
2234 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002235
Facundo Batista1a191df2007-10-02 17:01:24 +00002236 If either operand is a special value, the following rules are used:
2237 * return True if both operands are infinities
2238 * return True if both operands are NaNs
2239 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002240 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002241 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002242 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002243 return (self.is_nan() and other.is_nan() or
2244 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002245 return self._exp == other._exp
2246
Facundo Batista353750c2007-09-13 18:13:15 +00002247 def _rescale(self, exp, rounding):
2248 """Rescale self so that the exponent is exp, either by padding with zeros
2249 or by truncating digits, using the given rounding mode.
2250
2251 Specials are returned without change. This operation is
2252 quiet: it raises no flags, and uses no information from the
2253 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002254
2255 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002256 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002257 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002258 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002259 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002260 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002261 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002262
Facundo Batista353750c2007-09-13 18:13:15 +00002263 if self._exp >= exp:
2264 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002265 return _dec_from_triple(self._sign,
2266 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002267
Facundo Batista353750c2007-09-13 18:13:15 +00002268 # too many digits; round and lose data. If self.adjusted() <
2269 # exp-1, replace self by 10**(exp-1) before rounding
2270 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002271 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002272 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002273 digits = 0
2274 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002275 changed = this_function(digits)
2276 coeff = self._int[:digits] or '0'
2277 if changed == 1:
2278 coeff = str(int(coeff)+1)
2279 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002280
Facundo Batista353750c2007-09-13 18:13:15 +00002281 def to_integral_exact(self, rounding=None, context=None):
2282 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002283
Facundo Batista353750c2007-09-13 18:13:15 +00002284 If no rounding mode is specified, take the rounding mode from
2285 the context. This method raises the Rounded and Inexact flags
2286 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002287
Facundo Batista353750c2007-09-13 18:13:15 +00002288 See also: to_integral_value, which does exactly the same as
2289 this method except that it doesn't raise Inexact or Rounded.
2290 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002291 if self._is_special:
2292 ans = self._check_nans(context=context)
2293 if ans:
2294 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002295 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002296 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002297 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002298 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002299 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002300 if context is None:
2301 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002302 if rounding is None:
2303 rounding = context.rounding
2304 context._raise_error(Rounded)
2305 ans = self._rescale(0, rounding)
2306 if ans != self:
2307 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002308 return ans
2309
Facundo Batista353750c2007-09-13 18:13:15 +00002310 def to_integral_value(self, rounding=None, context=None):
2311 """Rounds to the nearest integer, without raising inexact, rounded."""
2312 if context is None:
2313 context = getcontext()
2314 if rounding is None:
2315 rounding = context.rounding
2316 if self._is_special:
2317 ans = self._check_nans(context=context)
2318 if ans:
2319 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002320 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002321 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002322 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002323 else:
2324 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002325
Facundo Batista353750c2007-09-13 18:13:15 +00002326 # the method name changed, but we provide also the old one, for compatibility
2327 to_integral = to_integral_value
2328
2329 def sqrt(self, context=None):
2330 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002331 if self._is_special:
2332 ans = self._check_nans(context=context)
2333 if ans:
2334 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002335
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002336 if self._isinfinity() and self._sign == 0:
2337 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002338
2339 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002340 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002341 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002342 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002343
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002344 if context is None:
2345 context = getcontext()
2346
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002347 if self._sign == 1:
2348 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2349
Facundo Batista353750c2007-09-13 18:13:15 +00002350 # At this point self represents a positive number. Let p be
2351 # the desired precision and express self in the form c*100**e
2352 # with c a positive real number and e an integer, c and e
2353 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2354 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2355 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2356 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2357 # the closest integer to sqrt(c) with the even integer chosen
2358 # in the case of a tie.
2359 #
2360 # To ensure correct rounding in all cases, we use the
2361 # following trick: we compute the square root to an extra
2362 # place (precision p+1 instead of precision p), rounding down.
2363 # Then, if the result is inexact and its last digit is 0 or 5,
2364 # we increase the last digit to 1 or 6 respectively; if it's
2365 # exact we leave the last digit alone. Now the final round to
2366 # p places (or fewer in the case of underflow) will round
2367 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002368
Facundo Batista353750c2007-09-13 18:13:15 +00002369 # use an extra digit of precision
2370 prec = context.prec+1
2371
2372 # write argument in the form c*100**e where e = self._exp//2
2373 # is the 'ideal' exponent, to be used if the square root is
2374 # exactly representable. l is the number of 'digits' of c in
2375 # base 100, so that 100**(l-1) <= c < 100**l.
2376 op = _WorkRep(self)
2377 e = op.exp >> 1
2378 if op.exp & 1:
2379 c = op.int * 10
2380 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002381 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002382 c = op.int
2383 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002384
Facundo Batista353750c2007-09-13 18:13:15 +00002385 # rescale so that c has exactly prec base 100 'digits'
2386 shift = prec-l
2387 if shift >= 0:
2388 c *= 100**shift
2389 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002390 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002391 c, remainder = divmod(c, 100**-shift)
2392 exact = not remainder
2393 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002394
Facundo Batista353750c2007-09-13 18:13:15 +00002395 # find n = floor(sqrt(c)) using Newton's method
2396 n = 10**prec
2397 while True:
2398 q = c//n
2399 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002400 break
Facundo Batista353750c2007-09-13 18:13:15 +00002401 else:
2402 n = n + q >> 1
2403 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002404
Facundo Batista353750c2007-09-13 18:13:15 +00002405 if exact:
2406 # result is exact; rescale to use ideal exponent e
2407 if shift >= 0:
2408 # assert n % 10**shift == 0
2409 n //= 10**shift
2410 else:
2411 n *= 10**-shift
2412 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002413 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002414 # result is not exact; fix last digit as described above
2415 if n % 5 == 0:
2416 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002417
Facundo Batista72bc54f2007-11-23 17:59:00 +00002418 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002419
Facundo Batista353750c2007-09-13 18:13:15 +00002420 # round, and fit to current context
2421 context = context._shallow_copy()
2422 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002423 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002424 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002425
Facundo Batista353750c2007-09-13 18:13:15 +00002426 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002427
2428 def max(self, other, context=None):
2429 """Returns the larger value.
2430
Facundo Batista353750c2007-09-13 18:13:15 +00002431 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002432 NaN (and signals if one is sNaN). Also rounds.
2433 """
Facundo Batista353750c2007-09-13 18:13:15 +00002434 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002435
Facundo Batista6c398da2007-09-17 17:30:13 +00002436 if context is None:
2437 context = getcontext()
2438
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002439 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002440 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002441 # number is always returned
2442 sn = self._isnan()
2443 on = other._isnan()
2444 if sn or on:
2445 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002446 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002447 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002448 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002449 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002450
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002451 c = self.__cmp__(other)
2452 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002453 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002454 # then an ordering is applied:
2455 #
Facundo Batista59c58842007-04-10 12:58:45 +00002456 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002457 # positive sign and min returns the operand with the negative sign
2458 #
Facundo Batista59c58842007-04-10 12:58:45 +00002459 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002460 # the result. This is exactly the ordering used in compare_total.
2461 c = self.compare_total(other)
2462
2463 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002464 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002465 else:
2466 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002467
Facundo Batistae64acfa2007-12-17 14:18:42 +00002468 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002469
2470 def min(self, other, context=None):
2471 """Returns the smaller value.
2472
Facundo Batista59c58842007-04-10 12:58:45 +00002473 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002474 NaN (and signals if one is sNaN). Also rounds.
2475 """
Facundo Batista353750c2007-09-13 18:13:15 +00002476 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002477
Facundo Batista6c398da2007-09-17 17:30:13 +00002478 if context is None:
2479 context = getcontext()
2480
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002481 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002482 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002483 # number is always returned
2484 sn = self._isnan()
2485 on = other._isnan()
2486 if sn or on:
2487 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002488 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002489 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002490 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002491 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002492
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002493 c = self.__cmp__(other)
2494 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002495 c = self.compare_total(other)
2496
2497 if c == -1:
2498 ans = self
2499 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002500 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002501
Facundo Batistae64acfa2007-12-17 14:18:42 +00002502 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002503
2504 def _isinteger(self):
2505 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002506 if self._is_special:
2507 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002508 if self._exp >= 0:
2509 return True
2510 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002511 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002512
2513 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002514 """Returns True if self is even. Assumes self is an integer."""
2515 if not self or self._exp > 0:
2516 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002517 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002518
2519 def adjusted(self):
2520 """Return the adjusted exponent of self"""
2521 try:
2522 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002523 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002524 except TypeError:
2525 return 0
2526
Facundo Batista353750c2007-09-13 18:13:15 +00002527 def canonical(self, context=None):
2528 """Returns the same Decimal object.
2529
2530 As we do not have different encodings for the same number, the
2531 received object already is in its canonical form.
2532 """
2533 return self
2534
2535 def compare_signal(self, other, context=None):
2536 """Compares self to the other operand numerically.
2537
2538 It's pretty much like compare(), but all NaNs signal, with signaling
2539 NaNs taking precedence over quiet NaNs.
2540 """
2541 if context is None:
2542 context = getcontext()
2543
2544 self_is_nan = self._isnan()
2545 other_is_nan = other._isnan()
2546 if self_is_nan == 2:
2547 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002548 self)
Facundo Batista353750c2007-09-13 18:13:15 +00002549 if other_is_nan == 2:
2550 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002551 other)
Facundo Batista353750c2007-09-13 18:13:15 +00002552 if self_is_nan:
2553 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002554 self)
Facundo Batista353750c2007-09-13 18:13:15 +00002555 if other_is_nan:
2556 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002557 other)
Facundo Batista353750c2007-09-13 18:13:15 +00002558 return self.compare(other, context=context)
2559
2560 def compare_total(self, other):
2561 """Compares self to other using the abstract representations.
2562
2563 This is not like the standard compare, which use their numerical
2564 value. Note that a total ordering is defined for all possible abstract
2565 representations.
2566 """
2567 # if one is negative and the other is positive, it's easy
2568 if self._sign and not other._sign:
2569 return Dec_n1
2570 if not self._sign and other._sign:
2571 return Dec_p1
2572 sign = self._sign
2573
2574 # let's handle both NaN types
2575 self_nan = self._isnan()
2576 other_nan = other._isnan()
2577 if self_nan or other_nan:
2578 if self_nan == other_nan:
2579 if self._int < other._int:
2580 if sign:
2581 return Dec_p1
2582 else:
2583 return Dec_n1
2584 if self._int > other._int:
2585 if sign:
2586 return Dec_n1
2587 else:
2588 return Dec_p1
2589 return Dec_0
2590
2591 if sign:
2592 if self_nan == 1:
2593 return Dec_n1
2594 if other_nan == 1:
2595 return Dec_p1
2596 if self_nan == 2:
2597 return Dec_n1
2598 if other_nan == 2:
2599 return Dec_p1
2600 else:
2601 if self_nan == 1:
2602 return Dec_p1
2603 if other_nan == 1:
2604 return Dec_n1
2605 if self_nan == 2:
2606 return Dec_p1
2607 if other_nan == 2:
2608 return Dec_n1
2609
2610 if self < other:
2611 return Dec_n1
2612 if self > other:
2613 return Dec_p1
2614
2615 if self._exp < other._exp:
2616 if sign:
2617 return Dec_p1
2618 else:
2619 return Dec_n1
2620 if self._exp > other._exp:
2621 if sign:
2622 return Dec_n1
2623 else:
2624 return Dec_p1
2625 return Dec_0
2626
2627
2628 def compare_total_mag(self, other):
2629 """Compares self to other using abstract repr., ignoring sign.
2630
2631 Like compare_total, but with operand's sign ignored and assumed to be 0.
2632 """
2633 s = self.copy_abs()
2634 o = other.copy_abs()
2635 return s.compare_total(o)
2636
2637 def copy_abs(self):
2638 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002639 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002640
2641 def copy_negate(self):
2642 """Returns a copy with the sign inverted."""
2643 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002644 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002645 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002646 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002647
2648 def copy_sign(self, other):
2649 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002650 return _dec_from_triple(other._sign, self._int,
2651 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002652
2653 def exp(self, context=None):
2654 """Returns e ** self."""
2655
2656 if context is None:
2657 context = getcontext()
2658
2659 # exp(NaN) = NaN
2660 ans = self._check_nans(context=context)
2661 if ans:
2662 return ans
2663
2664 # exp(-Infinity) = 0
2665 if self._isinfinity() == -1:
2666 return Dec_0
2667
2668 # exp(0) = 1
2669 if not self:
2670 return Dec_p1
2671
2672 # exp(Infinity) = Infinity
2673 if self._isinfinity() == 1:
2674 return Decimal(self)
2675
2676 # the result is now guaranteed to be inexact (the true
2677 # mathematical result is transcendental). There's no need to
2678 # raise Rounded and Inexact here---they'll always be raised as
2679 # a result of the call to _fix.
2680 p = context.prec
2681 adj = self.adjusted()
2682
2683 # we only need to do any computation for quite a small range
2684 # of adjusted exponents---for example, -29 <= adj <= 10 for
2685 # the default context. For smaller exponent the result is
2686 # indistinguishable from 1 at the given precision, while for
2687 # larger exponent the result either overflows or underflows.
2688 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2689 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002690 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002691 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2692 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002693 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002694 elif self._sign == 0 and adj < -p:
2695 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002696 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002697 elif self._sign == 1 and adj < -p-1:
2698 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002699 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002700 # general case
2701 else:
2702 op = _WorkRep(self)
2703 c, e = op.int, op.exp
2704 if op.sign == 1:
2705 c = -c
2706
2707 # compute correctly rounded result: increase precision by
2708 # 3 digits at a time until we get an unambiguously
2709 # roundable result
2710 extra = 3
2711 while True:
2712 coeff, exp = _dexp(c, e, p+extra)
2713 if coeff % (5*10**(len(str(coeff))-p-1)):
2714 break
2715 extra += 3
2716
Facundo Batista72bc54f2007-11-23 17:59:00 +00002717 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002718
2719 # at this stage, ans should round correctly with *any*
2720 # rounding mode, not just with ROUND_HALF_EVEN
2721 context = context._shallow_copy()
2722 rounding = context._set_rounding(ROUND_HALF_EVEN)
2723 ans = ans._fix(context)
2724 context.rounding = rounding
2725
2726 return ans
2727
2728 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002729 """Return True if self is canonical; otherwise return False.
2730
2731 Currently, the encoding of a Decimal instance is always
2732 canonical, so this method returns True for any Decimal.
2733 """
2734 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002735
2736 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002737 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002738
Facundo Batista1a191df2007-10-02 17:01:24 +00002739 A Decimal instance is considered finite if it is neither
2740 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002741 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002742 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002743
2744 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002745 """Return True if self is infinite; otherwise return False."""
2746 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002747
2748 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002749 """Return True if self is a qNaN or sNaN; otherwise return False."""
2750 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002751
2752 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002753 """Return True if self is a normal number; otherwise return False."""
2754 if self._is_special or not self:
2755 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002756 if context is None:
2757 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002758 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002759
2760 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002761 """Return True if self is a quiet NaN; otherwise return False."""
2762 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002763
2764 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002765 """Return True if self is negative; otherwise return False."""
2766 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002767
2768 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002769 """Return True if self is a signaling NaN; otherwise return False."""
2770 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002771
2772 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002773 """Return True if self is subnormal; otherwise return False."""
2774 if self._is_special or not self:
2775 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002776 if context is None:
2777 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002778 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002779
2780 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002781 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002782 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002783
2784 def _ln_exp_bound(self):
2785 """Compute a lower bound for the adjusted exponent of self.ln().
2786 In other words, compute r such that self.ln() >= 10**r. Assumes
2787 that self is finite and positive and that self != 1.
2788 """
2789
2790 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2791 adj = self._exp + len(self._int) - 1
2792 if adj >= 1:
2793 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2794 return len(str(adj*23//10)) - 1
2795 if adj <= -2:
2796 # argument <= 0.1
2797 return len(str((-1-adj)*23//10)) - 1
2798 op = _WorkRep(self)
2799 c, e = op.int, op.exp
2800 if adj == 0:
2801 # 1 < self < 10
2802 num = str(c-10**-e)
2803 den = str(c)
2804 return len(num) - len(den) - (num < den)
2805 # adj == -1, 0.1 <= self < 1
2806 return e + len(str(10**-e - c)) - 1
2807
2808
2809 def ln(self, context=None):
2810 """Returns the natural (base e) logarithm of self."""
2811
2812 if context is None:
2813 context = getcontext()
2814
2815 # ln(NaN) = NaN
2816 ans = self._check_nans(context=context)
2817 if ans:
2818 return ans
2819
2820 # ln(0.0) == -Infinity
2821 if not self:
2822 return negInf
2823
2824 # ln(Infinity) = Infinity
2825 if self._isinfinity() == 1:
2826 return Inf
2827
2828 # ln(1.0) == 0.0
2829 if self == Dec_p1:
2830 return Dec_0
2831
2832 # ln(negative) raises InvalidOperation
2833 if self._sign == 1:
2834 return context._raise_error(InvalidOperation,
2835 'ln of a negative value')
2836
2837 # result is irrational, so necessarily inexact
2838 op = _WorkRep(self)
2839 c, e = op.int, op.exp
2840 p = context.prec
2841
2842 # correctly rounded result: repeatedly increase precision by 3
2843 # until we get an unambiguously roundable result
2844 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2845 while True:
2846 coeff = _dlog(c, e, places)
2847 # assert len(str(abs(coeff)))-p >= 1
2848 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2849 break
2850 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002851 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002852
2853 context = context._shallow_copy()
2854 rounding = context._set_rounding(ROUND_HALF_EVEN)
2855 ans = ans._fix(context)
2856 context.rounding = rounding
2857 return ans
2858
2859 def _log10_exp_bound(self):
2860 """Compute a lower bound for the adjusted exponent of self.log10().
2861 In other words, find r such that self.log10() >= 10**r.
2862 Assumes that self is finite and positive and that self != 1.
2863 """
2864
2865 # For x >= 10 or x < 0.1 we only need a bound on the integer
2866 # part of log10(self), and this comes directly from the
2867 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2868 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2869 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2870
2871 adj = self._exp + len(self._int) - 1
2872 if adj >= 1:
2873 # self >= 10
2874 return len(str(adj))-1
2875 if adj <= -2:
2876 # self < 0.1
2877 return len(str(-1-adj))-1
2878 op = _WorkRep(self)
2879 c, e = op.int, op.exp
2880 if adj == 0:
2881 # 1 < self < 10
2882 num = str(c-10**-e)
2883 den = str(231*c)
2884 return len(num) - len(den) - (num < den) + 2
2885 # adj == -1, 0.1 <= self < 1
2886 num = str(10**-e-c)
2887 return len(num) + e - (num < "231") - 1
2888
2889 def log10(self, context=None):
2890 """Returns the base 10 logarithm of self."""
2891
2892 if context is None:
2893 context = getcontext()
2894
2895 # log10(NaN) = NaN
2896 ans = self._check_nans(context=context)
2897 if ans:
2898 return ans
2899
2900 # log10(0.0) == -Infinity
2901 if not self:
2902 return negInf
2903
2904 # log10(Infinity) = Infinity
2905 if self._isinfinity() == 1:
2906 return Inf
2907
2908 # log10(negative or -Infinity) raises InvalidOperation
2909 if self._sign == 1:
2910 return context._raise_error(InvalidOperation,
2911 'log10 of a negative value')
2912
2913 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00002914 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00002915 # answer may need rounding
2916 ans = Decimal(self._exp + len(self._int) - 1)
2917 else:
2918 # result is irrational, so necessarily inexact
2919 op = _WorkRep(self)
2920 c, e = op.int, op.exp
2921 p = context.prec
2922
2923 # correctly rounded result: repeatedly increase precision
2924 # until result is unambiguously roundable
2925 places = p-self._log10_exp_bound()+2
2926 while True:
2927 coeff = _dlog10(c, e, places)
2928 # assert len(str(abs(coeff)))-p >= 1
2929 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2930 break
2931 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002932 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002933
2934 context = context._shallow_copy()
2935 rounding = context._set_rounding(ROUND_HALF_EVEN)
2936 ans = ans._fix(context)
2937 context.rounding = rounding
2938 return ans
2939
2940 def logb(self, context=None):
2941 """ Returns the exponent of the magnitude of self's MSD.
2942
2943 The result is the integer which is the exponent of the magnitude
2944 of the most significant digit of self (as though it were truncated
2945 to a single digit while maintaining the value of that digit and
2946 without limiting the resulting exponent).
2947 """
2948 # logb(NaN) = NaN
2949 ans = self._check_nans(context=context)
2950 if ans:
2951 return ans
2952
2953 if context is None:
2954 context = getcontext()
2955
2956 # logb(+/-Inf) = +Inf
2957 if self._isinfinity():
2958 return Inf
2959
2960 # logb(0) = -Inf, DivisionByZero
2961 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00002962 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00002963
2964 # otherwise, simply return the adjusted exponent of self, as a
2965 # Decimal. Note that no attempt is made to fit the result
2966 # into the current context.
2967 return Decimal(self.adjusted())
2968
2969 def _islogical(self):
2970 """Return True if self is a logical operand.
2971
2972 For being logical, it must be a finite numbers with a sign of 0,
2973 an exponent of 0, and a coefficient whose digits must all be
2974 either 0 or 1.
2975 """
2976 if self._sign != 0 or self._exp != 0:
2977 return False
2978 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002979 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00002980 return False
2981 return True
2982
2983 def _fill_logical(self, context, opa, opb):
2984 dif = context.prec - len(opa)
2985 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002986 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00002987 elif dif < 0:
2988 opa = opa[-context.prec:]
2989 dif = context.prec - len(opb)
2990 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002991 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00002992 elif dif < 0:
2993 opb = opb[-context.prec:]
2994 return opa, opb
2995
2996 def logical_and(self, other, context=None):
2997 """Applies an 'and' operation between self and other's digits."""
2998 if context is None:
2999 context = getcontext()
3000 if not self._islogical() or not other._islogical():
3001 return context._raise_error(InvalidOperation)
3002
3003 # fill to context.prec
3004 (opa, opb) = self._fill_logical(context, self._int, other._int)
3005
3006 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003007 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3008 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003009
3010 def logical_invert(self, context=None):
3011 """Invert all its digits."""
3012 if context is None:
3013 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003014 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3015 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003016
3017 def logical_or(self, other, context=None):
3018 """Applies an 'or' operation between self and other's digits."""
3019 if context is None:
3020 context = getcontext()
3021 if not self._islogical() or not other._islogical():
3022 return context._raise_error(InvalidOperation)
3023
3024 # fill to context.prec
3025 (opa, opb) = self._fill_logical(context, self._int, other._int)
3026
3027 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003028 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3029 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003030
3031 def logical_xor(self, other, context=None):
3032 """Applies an 'xor' operation between self and other's digits."""
3033 if context is None:
3034 context = getcontext()
3035 if not self._islogical() or not other._islogical():
3036 return context._raise_error(InvalidOperation)
3037
3038 # fill to context.prec
3039 (opa, opb) = self._fill_logical(context, self._int, other._int)
3040
3041 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003042 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3043 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003044
3045 def max_mag(self, other, context=None):
3046 """Compares the values numerically with their sign ignored."""
3047 other = _convert_other(other, raiseit=True)
3048
Facundo Batista6c398da2007-09-17 17:30:13 +00003049 if context is None:
3050 context = getcontext()
3051
Facundo Batista353750c2007-09-13 18:13:15 +00003052 if self._is_special or other._is_special:
3053 # If one operand is a quiet NaN and the other is number, then the
3054 # number is always returned
3055 sn = self._isnan()
3056 on = other._isnan()
3057 if sn or on:
3058 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003059 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003060 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003061 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003062 return self._check_nans(other, context)
3063
3064 c = self.copy_abs().__cmp__(other.copy_abs())
3065 if c == 0:
3066 c = self.compare_total(other)
3067
3068 if c == -1:
3069 ans = other
3070 else:
3071 ans = self
3072
Facundo Batistae64acfa2007-12-17 14:18:42 +00003073 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003074
3075 def min_mag(self, other, context=None):
3076 """Compares the values numerically with their sign ignored."""
3077 other = _convert_other(other, raiseit=True)
3078
Facundo Batista6c398da2007-09-17 17:30:13 +00003079 if context is None:
3080 context = getcontext()
3081
Facundo Batista353750c2007-09-13 18:13:15 +00003082 if self._is_special or other._is_special:
3083 # If one operand is a quiet NaN and the other is number, then the
3084 # number is always returned
3085 sn = self._isnan()
3086 on = other._isnan()
3087 if sn or on:
3088 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003089 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003090 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003091 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003092 return self._check_nans(other, context)
3093
3094 c = self.copy_abs().__cmp__(other.copy_abs())
3095 if c == 0:
3096 c = self.compare_total(other)
3097
3098 if c == -1:
3099 ans = self
3100 else:
3101 ans = other
3102
Facundo Batistae64acfa2007-12-17 14:18:42 +00003103 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003104
3105 def next_minus(self, context=None):
3106 """Returns the largest representable number smaller than itself."""
3107 if context is None:
3108 context = getcontext()
3109
3110 ans = self._check_nans(context=context)
3111 if ans:
3112 return ans
3113
3114 if self._isinfinity() == -1:
3115 return negInf
3116 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003117 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003118
3119 context = context.copy()
3120 context._set_rounding(ROUND_FLOOR)
3121 context._ignore_all_flags()
3122 new_self = self._fix(context)
3123 if new_self != self:
3124 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003125 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3126 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003127
3128 def next_plus(self, context=None):
3129 """Returns the smallest representable number larger than itself."""
3130 if context is None:
3131 context = getcontext()
3132
3133 ans = self._check_nans(context=context)
3134 if ans:
3135 return ans
3136
3137 if self._isinfinity() == 1:
3138 return Inf
3139 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003140 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003141
3142 context = context.copy()
3143 context._set_rounding(ROUND_CEILING)
3144 context._ignore_all_flags()
3145 new_self = self._fix(context)
3146 if new_self != self:
3147 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003148 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3149 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003150
3151 def next_toward(self, other, context=None):
3152 """Returns the number closest to self, in the direction towards other.
3153
3154 The result is the closest representable number to self
3155 (excluding self) that is in the direction towards other,
3156 unless both have the same value. If the two operands are
3157 numerically equal, then the result is a copy of self with the
3158 sign set to be the same as the sign of other.
3159 """
3160 other = _convert_other(other, raiseit=True)
3161
3162 if context is None:
3163 context = getcontext()
3164
3165 ans = self._check_nans(other, context)
3166 if ans:
3167 return ans
3168
3169 comparison = self.__cmp__(other)
3170 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003171 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003172
3173 if comparison == -1:
3174 ans = self.next_plus(context)
3175 else: # comparison == 1
3176 ans = self.next_minus(context)
3177
3178 # decide which flags to raise using value of ans
3179 if ans._isinfinity():
3180 context._raise_error(Overflow,
3181 'Infinite result from next_toward',
3182 ans._sign)
3183 context._raise_error(Rounded)
3184 context._raise_error(Inexact)
3185 elif ans.adjusted() < context.Emin:
3186 context._raise_error(Underflow)
3187 context._raise_error(Subnormal)
3188 context._raise_error(Rounded)
3189 context._raise_error(Inexact)
3190 # if precision == 1 then we don't raise Clamped for a
3191 # result 0E-Etiny.
3192 if not ans:
3193 context._raise_error(Clamped)
3194
3195 return ans
3196
3197 def number_class(self, context=None):
3198 """Returns an indication of the class of self.
3199
3200 The class is one of the following strings:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00003201 sNaN
3202 NaN
Facundo Batista353750c2007-09-13 18:13:15 +00003203 -Infinity
3204 -Normal
3205 -Subnormal
3206 -Zero
3207 +Zero
3208 +Subnormal
3209 +Normal
3210 +Infinity
3211 """
3212 if self.is_snan():
3213 return "sNaN"
3214 if self.is_qnan():
3215 return "NaN"
3216 inf = self._isinfinity()
3217 if inf == 1:
3218 return "+Infinity"
3219 if inf == -1:
3220 return "-Infinity"
3221 if self.is_zero():
3222 if self._sign:
3223 return "-Zero"
3224 else:
3225 return "+Zero"
3226 if context is None:
3227 context = getcontext()
3228 if self.is_subnormal(context=context):
3229 if self._sign:
3230 return "-Subnormal"
3231 else:
3232 return "+Subnormal"
3233 # just a normal, regular, boring number, :)
3234 if self._sign:
3235 return "-Normal"
3236 else:
3237 return "+Normal"
3238
3239 def radix(self):
3240 """Just returns 10, as this is Decimal, :)"""
3241 return Decimal(10)
3242
3243 def rotate(self, other, context=None):
3244 """Returns a rotated copy of self, value-of-other times."""
3245 if context is None:
3246 context = getcontext()
3247
3248 ans = self._check_nans(other, context)
3249 if ans:
3250 return ans
3251
3252 if other._exp != 0:
3253 return context._raise_error(InvalidOperation)
3254 if not (-context.prec <= int(other) <= context.prec):
3255 return context._raise_error(InvalidOperation)
3256
3257 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003258 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003259
3260 # get values, pad if necessary
3261 torot = int(other)
3262 rotdig = self._int
3263 topad = context.prec - len(rotdig)
3264 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003265 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003266
3267 # let's rotate!
3268 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003269 return _dec_from_triple(self._sign,
3270 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003271
3272 def scaleb (self, other, context=None):
3273 """Returns self operand after adding the second value to its exp."""
3274 if context is None:
3275 context = getcontext()
3276
3277 ans = self._check_nans(other, context)
3278 if ans:
3279 return ans
3280
3281 if other._exp != 0:
3282 return context._raise_error(InvalidOperation)
3283 liminf = -2 * (context.Emax + context.prec)
3284 limsup = 2 * (context.Emax + context.prec)
3285 if not (liminf <= int(other) <= limsup):
3286 return context._raise_error(InvalidOperation)
3287
3288 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003289 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003290
Facundo Batista72bc54f2007-11-23 17:59:00 +00003291 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003292 d = d._fix(context)
3293 return d
3294
3295 def shift(self, other, context=None):
3296 """Returns a shifted copy of self, value-of-other times."""
3297 if context is None:
3298 context = getcontext()
3299
3300 ans = self._check_nans(other, context)
3301 if ans:
3302 return ans
3303
3304 if other._exp != 0:
3305 return context._raise_error(InvalidOperation)
3306 if not (-context.prec <= int(other) <= context.prec):
3307 return context._raise_error(InvalidOperation)
3308
3309 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003310 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003311
3312 # get values, pad if necessary
3313 torot = int(other)
3314 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003315 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003316 rotdig = self._int
3317 topad = context.prec - len(rotdig)
3318 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003319 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003320
3321 # let's shift!
3322 if torot < 0:
3323 rotated = rotdig[:torot]
3324 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003325 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003326 rotated = rotated[-context.prec:]
3327
Facundo Batista72bc54f2007-11-23 17:59:00 +00003328 return _dec_from_triple(self._sign,
3329 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003330
Facundo Batista59c58842007-04-10 12:58:45 +00003331 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003332 def __reduce__(self):
3333 return (self.__class__, (str(self),))
3334
3335 def __copy__(self):
3336 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003337 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003338 return self.__class__(str(self))
3339
3340 def __deepcopy__(self, memo):
3341 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003342 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003343 return self.__class__(str(self))
3344
Facundo Batista72bc54f2007-11-23 17:59:00 +00003345def _dec_from_triple(sign, coefficient, exponent, special=False):
3346 """Create a decimal instance directly, without any validation,
3347 normalization (e.g. removal of leading zeros) or argument
3348 conversion.
3349
3350 This function is for *internal use only*.
3351 """
3352
3353 self = object.__new__(Decimal)
3354 self._sign = sign
3355 self._int = coefficient
3356 self._exp = exponent
3357 self._is_special = special
3358
3359 return self
3360
Facundo Batista59c58842007-04-10 12:58:45 +00003361##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003362
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003363
3364# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003365rounding_functions = [name for name in Decimal.__dict__.keys()
3366 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003367for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003368 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003369 globalname = name[1:].upper()
3370 val = globals()[globalname]
3371 Decimal._pick_rounding_function[val] = name
3372
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003373del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003374
Nick Coghlanced12182006-09-02 03:54:17 +00003375class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003376 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003377
Nick Coghlanced12182006-09-02 03:54:17 +00003378 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003379 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003380 """
3381 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003382 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003383 def __enter__(self):
3384 self.saved_context = getcontext()
3385 setcontext(self.new_context)
3386 return self.new_context
3387 def __exit__(self, t, v, tb):
3388 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003389
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003390class Context(object):
3391 """Contains the context for a Decimal instance.
3392
3393 Contains:
3394 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003395 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003396 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003397 raised when it is caused. Otherwise, a value is
3398 substituted in.
3399 flags - When an exception is caused, flags[exception] is incremented.
3400 (Whether or not the trap_enabler is set)
3401 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003402 Emin - Minimum exponent
3403 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003404 capitals - If 1, 1*10^1 is printed as 1E+1.
3405 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003406 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003407 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003408
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003409 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003410 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003411 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003412 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003413 _ignored_flags=None):
3414 if flags is None:
3415 flags = []
3416 if _ignored_flags is None:
3417 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003418 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003419 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003420 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003421 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003422 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003423 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003424 for name, val in locals().items():
3425 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003426 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003427 else:
3428 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003429 del self.self
3430
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003431 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003432 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003433 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003434 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3435 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3436 % vars(self))
3437 names = [f.__name__ for f, v in self.flags.items() if v]
3438 s.append('flags=[' + ', '.join(names) + ']')
3439 names = [t.__name__ for t, v in self.traps.items() if v]
3440 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003441 return ', '.join(s) + ')'
3442
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003443 def clear_flags(self):
3444 """Reset all flags to zero"""
3445 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003446 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003447
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003448 def _shallow_copy(self):
3449 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003450 nc = Context(self.prec, self.rounding, self.traps,
3451 self.flags, self.Emin, self.Emax,
3452 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003453 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003454
3455 def copy(self):
3456 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003457 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003458 self.flags.copy(), self.Emin, self.Emax,
3459 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003460 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003461 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003462
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003463 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003464 """Handles an error
3465
3466 If the flag is in _ignored_flags, returns the default response.
3467 Otherwise, it increments the flag, then, if the corresponding
3468 trap_enabler is set, it reaises the exception. Otherwise, it returns
3469 the default value after incrementing the flag.
3470 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003471 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003472 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003473 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003474 return error().handle(self, *args)
3475
3476 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003477 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003478 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003479 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003480
3481 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003482 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003483 raise error, explanation
3484
3485 def _ignore_all_flags(self):
3486 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003487 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003488
3489 def _ignore_flags(self, *flags):
3490 """Ignore the flags, if they are raised"""
3491 # Do not mutate-- This way, copies of a context leave the original
3492 # alone.
3493 self._ignored_flags = (self._ignored_flags + list(flags))
3494 return list(flags)
3495
3496 def _regard_flags(self, *flags):
3497 """Stop ignoring the flags, if they are raised"""
3498 if flags and isinstance(flags[0], (tuple,list)):
3499 flags = flags[0]
3500 for flag in flags:
3501 self._ignored_flags.remove(flag)
3502
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003503 def __hash__(self):
3504 """A Context cannot be hashed."""
3505 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003506 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003507
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003508 def Etiny(self):
3509 """Returns Etiny (= Emin - prec + 1)"""
3510 return int(self.Emin - self.prec + 1)
3511
3512 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003513 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003514 return int(self.Emax - self.prec + 1)
3515
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003516 def _set_rounding(self, type):
3517 """Sets the rounding type.
3518
3519 Sets the rounding type, and returns the current (previous)
3520 rounding type. Often used like:
3521
3522 context = context.copy()
3523 # so you don't change the calling context
3524 # if an error occurs in the middle.
3525 rounding = context._set_rounding(ROUND_UP)
3526 val = self.__sub__(other, context=context)
3527 context._set_rounding(rounding)
3528
3529 This will make it round up for that operation.
3530 """
3531 rounding = self.rounding
3532 self.rounding= type
3533 return rounding
3534
Raymond Hettingerfed52962004-07-14 15:41:57 +00003535 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003536 """Creates a new Decimal instance but using self as context."""
3537 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003538 if d._isnan() and len(d._int) > self.prec - self._clamp:
3539 return self._raise_error(ConversionSyntax,
3540 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003541 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003542
Facundo Batista59c58842007-04-10 12:58:45 +00003543 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003544 def abs(self, a):
3545 """Returns the absolute value of the operand.
3546
3547 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003548 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003549 the plus operation on the operand.
3550
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003551 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003552 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003553 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003554 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003555 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003556 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003557 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003558 Decimal("101.5")
3559 """
3560 return a.__abs__(context=self)
3561
3562 def add(self, a, b):
3563 """Return the sum of the two operands.
3564
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003565 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003566 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003567 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003568 Decimal("1.02E+4")
3569 """
3570 return a.__add__(b, context=self)
3571
3572 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003573 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003574
Facundo Batista353750c2007-09-13 18:13:15 +00003575 def canonical(self, a):
3576 """Returns the same Decimal object.
3577
3578 As we do not have different encodings for the same number, the
3579 received object already is in its canonical form.
3580
3581 >>> ExtendedContext.canonical(Decimal('2.50'))
3582 Decimal("2.50")
3583 """
3584 return a.canonical(context=self)
3585
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003586 def compare(self, a, b):
3587 """Compares values numerically.
3588
3589 If the signs of the operands differ, a value representing each operand
3590 ('-1' if the operand is less than zero, '0' if the operand is zero or
3591 negative zero, or '1' if the operand is greater than zero) is used in
3592 place of that operand for the comparison instead of the actual
3593 operand.
3594
3595 The comparison is then effected by subtracting the second operand from
3596 the first and then returning a value according to the result of the
3597 subtraction: '-1' if the result is less than zero, '0' if the result is
3598 zero or negative zero, or '1' if the result is greater than zero.
3599
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003600 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003601 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003602 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003603 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003604 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003605 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003606 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003607 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003608 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003609 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003610 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003611 Decimal("-1")
3612 """
3613 return a.compare(b, context=self)
3614
Facundo Batista353750c2007-09-13 18:13:15 +00003615 def compare_signal(self, a, b):
3616 """Compares the values of the two operands numerically.
3617
3618 It's pretty much like compare(), but all NaNs signal, with signaling
3619 NaNs taking precedence over quiet NaNs.
3620
3621 >>> c = ExtendedContext
3622 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3623 Decimal("-1")
3624 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3625 Decimal("0")
3626 >>> c.flags[InvalidOperation] = 0
3627 >>> print c.flags[InvalidOperation]
3628 0
3629 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3630 Decimal("NaN")
3631 >>> print c.flags[InvalidOperation]
3632 1
3633 >>> c.flags[InvalidOperation] = 0
3634 >>> print c.flags[InvalidOperation]
3635 0
3636 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3637 Decimal("NaN")
3638 >>> print c.flags[InvalidOperation]
3639 1
3640 """
3641 return a.compare_signal(b, context=self)
3642
3643 def compare_total(self, a, b):
3644 """Compares two operands using their abstract representation.
3645
3646 This is not like the standard compare, which use their numerical
3647 value. Note that a total ordering is defined for all possible abstract
3648 representations.
3649
3650 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3651 Decimal("-1")
3652 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3653 Decimal("-1")
3654 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3655 Decimal("-1")
3656 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3657 Decimal("0")
3658 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3659 Decimal("1")
3660 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3661 Decimal("-1")
3662 """
3663 return a.compare_total(b)
3664
3665 def compare_total_mag(self, a, b):
3666 """Compares two operands using their abstract representation ignoring sign.
3667
3668 Like compare_total, but with operand's sign ignored and assumed to be 0.
3669 """
3670 return a.compare_total_mag(b)
3671
3672 def copy_abs(self, a):
3673 """Returns a copy of the operand with the sign set to 0.
3674
3675 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3676 Decimal("2.1")
3677 >>> ExtendedContext.copy_abs(Decimal('-100'))
3678 Decimal("100")
3679 """
3680 return a.copy_abs()
3681
3682 def copy_decimal(self, a):
3683 """Returns a copy of the decimal objet.
3684
3685 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3686 Decimal("2.1")
3687 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3688 Decimal("-1.00")
3689 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003690 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003691
3692 def copy_negate(self, a):
3693 """Returns a copy of the operand with the sign inverted.
3694
3695 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3696 Decimal("-101.5")
3697 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3698 Decimal("101.5")
3699 """
3700 return a.copy_negate()
3701
3702 def copy_sign(self, a, b):
3703 """Copies the second operand's sign to the first one.
3704
3705 In detail, it returns a copy of the first operand with the sign
3706 equal to the sign of the second operand.
3707
3708 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3709 Decimal("1.50")
3710 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3711 Decimal("1.50")
3712 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3713 Decimal("-1.50")
3714 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3715 Decimal("-1.50")
3716 """
3717 return a.copy_sign(b)
3718
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003719 def divide(self, a, b):
3720 """Decimal division in a specified context.
3721
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003722 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003723 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003724 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003725 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003726 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003727 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003728 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003729 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003730 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003731 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003732 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003733 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003734 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003735 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003736 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003737 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003738 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003739 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003740 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003741 Decimal("1.20E+6")
3742 """
3743 return a.__div__(b, context=self)
3744
3745 def divide_int(self, a, b):
3746 """Divides two numbers and returns the integer part of the result.
3747
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003748 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003749 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003750 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003751 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003752 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003753 Decimal("3")
3754 """
3755 return a.__floordiv__(b, context=self)
3756
3757 def divmod(self, a, b):
3758 return a.__divmod__(b, context=self)
3759
Facundo Batista353750c2007-09-13 18:13:15 +00003760 def exp(self, a):
3761 """Returns e ** a.
3762
3763 >>> c = ExtendedContext.copy()
3764 >>> c.Emin = -999
3765 >>> c.Emax = 999
3766 >>> c.exp(Decimal('-Infinity'))
3767 Decimal("0")
3768 >>> c.exp(Decimal('-1'))
3769 Decimal("0.367879441")
3770 >>> c.exp(Decimal('0'))
3771 Decimal("1")
3772 >>> c.exp(Decimal('1'))
3773 Decimal("2.71828183")
3774 >>> c.exp(Decimal('0.693147181'))
3775 Decimal("2.00000000")
3776 >>> c.exp(Decimal('+Infinity'))
3777 Decimal("Infinity")
3778 """
3779 return a.exp(context=self)
3780
3781 def fma(self, a, b, c):
3782 """Returns a multiplied by b, plus c.
3783
3784 The first two operands are multiplied together, using multiply,
3785 the third operand is then added to the result of that
3786 multiplication, using add, all with only one final rounding.
3787
3788 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3789 Decimal("22")
3790 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3791 Decimal("-8")
3792 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3793 Decimal("1.38435736E+12")
3794 """
3795 return a.fma(b, c, context=self)
3796
3797 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003798 """Return True if the operand is canonical; otherwise return False.
3799
3800 Currently, the encoding of a Decimal instance is always
3801 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00003802
3803 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003804 True
Facundo Batista353750c2007-09-13 18:13:15 +00003805 """
Facundo Batista1a191df2007-10-02 17:01:24 +00003806 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00003807
3808 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003809 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003810
Facundo Batista1a191df2007-10-02 17:01:24 +00003811 A Decimal instance is considered finite if it is neither
3812 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00003813
3814 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003815 True
Facundo Batista353750c2007-09-13 18:13:15 +00003816 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003817 True
Facundo Batista353750c2007-09-13 18:13:15 +00003818 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003819 True
Facundo Batista353750c2007-09-13 18:13:15 +00003820 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003821 False
Facundo Batista353750c2007-09-13 18:13:15 +00003822 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003823 False
Facundo Batista353750c2007-09-13 18:13:15 +00003824 """
3825 return a.is_finite()
3826
3827 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003828 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003829
3830 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003831 False
Facundo Batista353750c2007-09-13 18:13:15 +00003832 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003833 True
Facundo Batista353750c2007-09-13 18:13:15 +00003834 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003835 False
Facundo Batista353750c2007-09-13 18:13:15 +00003836 """
3837 return a.is_infinite()
3838
3839 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003840 """Return True if the operand is a qNaN or sNaN;
3841 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003842
3843 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003844 False
Facundo Batista353750c2007-09-13 18:13:15 +00003845 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003846 True
Facundo Batista353750c2007-09-13 18:13:15 +00003847 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003848 True
Facundo Batista353750c2007-09-13 18:13:15 +00003849 """
3850 return a.is_nan()
3851
3852 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003853 """Return True if the operand is a normal number;
3854 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003855
3856 >>> c = ExtendedContext.copy()
3857 >>> c.Emin = -999
3858 >>> c.Emax = 999
3859 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003860 True
Facundo Batista353750c2007-09-13 18:13:15 +00003861 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003862 False
Facundo Batista353750c2007-09-13 18:13:15 +00003863 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003864 False
Facundo Batista353750c2007-09-13 18:13:15 +00003865 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003866 False
Facundo Batista353750c2007-09-13 18:13:15 +00003867 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003868 False
Facundo Batista353750c2007-09-13 18:13:15 +00003869 """
3870 return a.is_normal(context=self)
3871
3872 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003873 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003874
3875 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003876 False
Facundo Batista353750c2007-09-13 18:13:15 +00003877 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003878 True
Facundo Batista353750c2007-09-13 18:13:15 +00003879 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003880 False
Facundo Batista353750c2007-09-13 18:13:15 +00003881 """
3882 return a.is_qnan()
3883
3884 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003885 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003886
3887 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003888 False
Facundo Batista353750c2007-09-13 18:13:15 +00003889 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003890 True
Facundo Batista353750c2007-09-13 18:13:15 +00003891 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003892 True
Facundo Batista353750c2007-09-13 18:13:15 +00003893 """
3894 return a.is_signed()
3895
3896 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003897 """Return True if the operand is a signaling NaN;
3898 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003899
3900 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003901 False
Facundo Batista353750c2007-09-13 18:13:15 +00003902 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003903 False
Facundo Batista353750c2007-09-13 18:13:15 +00003904 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003905 True
Facundo Batista353750c2007-09-13 18:13:15 +00003906 """
3907 return a.is_snan()
3908
3909 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003910 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003911
3912 >>> c = ExtendedContext.copy()
3913 >>> c.Emin = -999
3914 >>> c.Emax = 999
3915 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003916 False
Facundo Batista353750c2007-09-13 18:13:15 +00003917 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003918 True
Facundo Batista353750c2007-09-13 18:13:15 +00003919 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003920 False
Facundo Batista353750c2007-09-13 18:13:15 +00003921 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003922 False
Facundo Batista353750c2007-09-13 18:13:15 +00003923 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003924 False
Facundo Batista353750c2007-09-13 18:13:15 +00003925 """
3926 return a.is_subnormal(context=self)
3927
3928 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003929 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003930
3931 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003932 True
Facundo Batista353750c2007-09-13 18:13:15 +00003933 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003934 False
Facundo Batista353750c2007-09-13 18:13:15 +00003935 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003936 True
Facundo Batista353750c2007-09-13 18:13:15 +00003937 """
3938 return a.is_zero()
3939
3940 def ln(self, a):
3941 """Returns the natural (base e) logarithm of the operand.
3942
3943 >>> c = ExtendedContext.copy()
3944 >>> c.Emin = -999
3945 >>> c.Emax = 999
3946 >>> c.ln(Decimal('0'))
3947 Decimal("-Infinity")
3948 >>> c.ln(Decimal('1.000'))
3949 Decimal("0")
3950 >>> c.ln(Decimal('2.71828183'))
3951 Decimal("1.00000000")
3952 >>> c.ln(Decimal('10'))
3953 Decimal("2.30258509")
3954 >>> c.ln(Decimal('+Infinity'))
3955 Decimal("Infinity")
3956 """
3957 return a.ln(context=self)
3958
3959 def log10(self, a):
3960 """Returns the base 10 logarithm of the operand.
3961
3962 >>> c = ExtendedContext.copy()
3963 >>> c.Emin = -999
3964 >>> c.Emax = 999
3965 >>> c.log10(Decimal('0'))
3966 Decimal("-Infinity")
3967 >>> c.log10(Decimal('0.001'))
3968 Decimal("-3")
3969 >>> c.log10(Decimal('1.000'))
3970 Decimal("0")
3971 >>> c.log10(Decimal('2'))
3972 Decimal("0.301029996")
3973 >>> c.log10(Decimal('10'))
3974 Decimal("1")
3975 >>> c.log10(Decimal('70'))
3976 Decimal("1.84509804")
3977 >>> c.log10(Decimal('+Infinity'))
3978 Decimal("Infinity")
3979 """
3980 return a.log10(context=self)
3981
3982 def logb(self, a):
3983 """ Returns the exponent of the magnitude of the operand's MSD.
3984
3985 The result is the integer which is the exponent of the magnitude
3986 of the most significant digit of the operand (as though the
3987 operand were truncated to a single digit while maintaining the
3988 value of that digit and without limiting the resulting exponent).
3989
3990 >>> ExtendedContext.logb(Decimal('250'))
3991 Decimal("2")
3992 >>> ExtendedContext.logb(Decimal('2.50'))
3993 Decimal("0")
3994 >>> ExtendedContext.logb(Decimal('0.03'))
3995 Decimal("-2")
3996 >>> ExtendedContext.logb(Decimal('0'))
3997 Decimal("-Infinity")
3998 """
3999 return a.logb(context=self)
4000
4001 def logical_and(self, a, b):
4002 """Applies the logical operation 'and' between each operand's digits.
4003
4004 The operands must be both logical numbers.
4005
4006 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4007 Decimal("0")
4008 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4009 Decimal("0")
4010 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4011 Decimal("0")
4012 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4013 Decimal("1")
4014 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4015 Decimal("1000")
4016 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4017 Decimal("10")
4018 """
4019 return a.logical_and(b, context=self)
4020
4021 def logical_invert(self, a):
4022 """Invert all the digits in the operand.
4023
4024 The operand must be a logical number.
4025
4026 >>> ExtendedContext.logical_invert(Decimal('0'))
4027 Decimal("111111111")
4028 >>> ExtendedContext.logical_invert(Decimal('1'))
4029 Decimal("111111110")
4030 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4031 Decimal("0")
4032 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4033 Decimal("10101010")
4034 """
4035 return a.logical_invert(context=self)
4036
4037 def logical_or(self, a, b):
4038 """Applies the logical operation 'or' between each operand's digits.
4039
4040 The operands must be both logical numbers.
4041
4042 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4043 Decimal("0")
4044 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4045 Decimal("1")
4046 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4047 Decimal("1")
4048 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4049 Decimal("1")
4050 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4051 Decimal("1110")
4052 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4053 Decimal("1110")
4054 """
4055 return a.logical_or(b, context=self)
4056
4057 def logical_xor(self, a, b):
4058 """Applies the logical operation 'xor' between each operand's digits.
4059
4060 The operands must be both logical numbers.
4061
4062 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4063 Decimal("0")
4064 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4065 Decimal("1")
4066 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4067 Decimal("1")
4068 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4069 Decimal("0")
4070 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4071 Decimal("110")
4072 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4073 Decimal("1101")
4074 """
4075 return a.logical_xor(b, context=self)
4076
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004077 def max(self, a,b):
4078 """max compares two values numerically and returns the maximum.
4079
4080 If either operand is a NaN then the general rules apply.
4081 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004082 operation. If they are numerically equal then the left-hand operand
4083 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004084 infinity) of the two operands is chosen as the result.
4085
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004086 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004087 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004088 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004089 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004090 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004091 Decimal("1")
4092 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4093 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004094 """
4095 return a.max(b, context=self)
4096
Facundo Batista353750c2007-09-13 18:13:15 +00004097 def max_mag(self, a, b):
4098 """Compares the values numerically with their sign ignored."""
4099 return a.max_mag(b, context=self)
4100
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004101 def min(self, a,b):
4102 """min compares two values numerically and returns the minimum.
4103
4104 If either operand is a NaN then the general rules apply.
4105 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004106 operation. If they are numerically equal then the left-hand operand
4107 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004108 infinity) of the two operands is chosen as the result.
4109
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004110 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004111 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004112 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004113 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004114 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004115 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004116 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4117 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004118 """
4119 return a.min(b, context=self)
4120
Facundo Batista353750c2007-09-13 18:13:15 +00004121 def min_mag(self, a, b):
4122 """Compares the values numerically with their sign ignored."""
4123 return a.min_mag(b, context=self)
4124
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004125 def minus(self, a):
4126 """Minus corresponds to unary prefix minus in Python.
4127
4128 The operation is evaluated using the same rules as subtract; the
4129 operation minus(a) is calculated as subtract('0', a) where the '0'
4130 has the same exponent as the operand.
4131
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004132 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004133 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004134 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004135 Decimal("1.3")
4136 """
4137 return a.__neg__(context=self)
4138
4139 def multiply(self, a, b):
4140 """multiply multiplies two operands.
4141
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004142 If either operand is a special value then the general rules apply.
4143 Otherwise, the operands are multiplied together ('long multiplication'),
4144 resulting in a number which may be as long as the sum of the lengths
4145 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004146
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004147 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004148 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004149 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004150 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004151 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004152 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004153 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004154 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004155 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004156 Decimal("4.28135971E+11")
4157 """
4158 return a.__mul__(b, context=self)
4159
Facundo Batista353750c2007-09-13 18:13:15 +00004160 def next_minus(self, a):
4161 """Returns the largest representable number smaller than a.
4162
4163 >>> c = ExtendedContext.copy()
4164 >>> c.Emin = -999
4165 >>> c.Emax = 999
4166 >>> ExtendedContext.next_minus(Decimal('1'))
4167 Decimal("0.999999999")
4168 >>> c.next_minus(Decimal('1E-1007'))
4169 Decimal("0E-1007")
4170 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4171 Decimal("-1.00000004")
4172 >>> c.next_minus(Decimal('Infinity'))
4173 Decimal("9.99999999E+999")
4174 """
4175 return a.next_minus(context=self)
4176
4177 def next_plus(self, a):
4178 """Returns the smallest representable number larger than a.
4179
4180 >>> c = ExtendedContext.copy()
4181 >>> c.Emin = -999
4182 >>> c.Emax = 999
4183 >>> ExtendedContext.next_plus(Decimal('1'))
4184 Decimal("1.00000001")
4185 >>> c.next_plus(Decimal('-1E-1007'))
4186 Decimal("-0E-1007")
4187 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4188 Decimal("-1.00000002")
4189 >>> c.next_plus(Decimal('-Infinity'))
4190 Decimal("-9.99999999E+999")
4191 """
4192 return a.next_plus(context=self)
4193
4194 def next_toward(self, a, b):
4195 """Returns the number closest to a, in direction towards b.
4196
4197 The result is the closest representable number from the first
4198 operand (but not the first operand) that is in the direction
4199 towards the second operand, unless the operands have the same
4200 value.
4201
4202 >>> c = ExtendedContext.copy()
4203 >>> c.Emin = -999
4204 >>> c.Emax = 999
4205 >>> c.next_toward(Decimal('1'), Decimal('2'))
4206 Decimal("1.00000001")
4207 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4208 Decimal("-0E-1007")
4209 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4210 Decimal("-1.00000002")
4211 >>> c.next_toward(Decimal('1'), Decimal('0'))
4212 Decimal("0.999999999")
4213 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4214 Decimal("0E-1007")
4215 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4216 Decimal("-1.00000004")
4217 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4218 Decimal("-0.00")
4219 """
4220 return a.next_toward(b, context=self)
4221
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004222 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004223 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004224
4225 Essentially a plus operation with all trailing zeros removed from the
4226 result.
4227
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004228 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004229 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004230 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004231 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004232 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004233 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004234 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004235 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004236 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004237 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004238 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004239 Decimal("0")
4240 """
4241 return a.normalize(context=self)
4242
Facundo Batista353750c2007-09-13 18:13:15 +00004243 def number_class(self, a):
4244 """Returns an indication of the class of the operand.
4245
4246 The class is one of the following strings:
4247 -sNaN
4248 -NaN
4249 -Infinity
4250 -Normal
4251 -Subnormal
4252 -Zero
4253 +Zero
4254 +Subnormal
4255 +Normal
4256 +Infinity
4257
4258 >>> c = Context(ExtendedContext)
4259 >>> c.Emin = -999
4260 >>> c.Emax = 999
4261 >>> c.number_class(Decimal('Infinity'))
4262 '+Infinity'
4263 >>> c.number_class(Decimal('1E-10'))
4264 '+Normal'
4265 >>> c.number_class(Decimal('2.50'))
4266 '+Normal'
4267 >>> c.number_class(Decimal('0.1E-999'))
4268 '+Subnormal'
4269 >>> c.number_class(Decimal('0'))
4270 '+Zero'
4271 >>> c.number_class(Decimal('-0'))
4272 '-Zero'
4273 >>> c.number_class(Decimal('-0.1E-999'))
4274 '-Subnormal'
4275 >>> c.number_class(Decimal('-1E-10'))
4276 '-Normal'
4277 >>> c.number_class(Decimal('-2.50'))
4278 '-Normal'
4279 >>> c.number_class(Decimal('-Infinity'))
4280 '-Infinity'
4281 >>> c.number_class(Decimal('NaN'))
4282 'NaN'
4283 >>> c.number_class(Decimal('-NaN'))
4284 'NaN'
4285 >>> c.number_class(Decimal('sNaN'))
4286 'sNaN'
4287 """
4288 return a.number_class(context=self)
4289
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004290 def plus(self, a):
4291 """Plus corresponds to unary prefix plus in Python.
4292
4293 The operation is evaluated using the same rules as add; the
4294 operation plus(a) is calculated as add('0', a) where the '0'
4295 has the same exponent as the operand.
4296
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004297 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004298 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004299 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004300 Decimal("-1.3")
4301 """
4302 return a.__pos__(context=self)
4303
4304 def power(self, a, b, modulo=None):
4305 """Raises a to the power of b, to modulo if given.
4306
Facundo Batista353750c2007-09-13 18:13:15 +00004307 With two arguments, compute a**b. If a is negative then b
4308 must be integral. The result will be inexact unless b is
4309 integral and the result is finite and can be expressed exactly
4310 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004311
Facundo Batista353750c2007-09-13 18:13:15 +00004312 With three arguments, compute (a**b) % modulo. For the
4313 three argument form, the following restrictions on the
4314 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004315
Facundo Batista353750c2007-09-13 18:13:15 +00004316 - all three arguments must be integral
4317 - b must be nonnegative
4318 - at least one of a or b must be nonzero
4319 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004320
Facundo Batista353750c2007-09-13 18:13:15 +00004321 The result of pow(a, b, modulo) is identical to the result
4322 that would be obtained by computing (a**b) % modulo with
4323 unbounded precision, but is computed more efficiently. It is
4324 always exact.
4325
4326 >>> c = ExtendedContext.copy()
4327 >>> c.Emin = -999
4328 >>> c.Emax = 999
4329 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004330 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004331 >>> c.power(Decimal('-2'), Decimal('3'))
4332 Decimal("-8")
4333 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004334 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004335 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004336 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004337 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4338 Decimal("2.00000000")
4339 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004340 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004341 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004342 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004343 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004344 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004345 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004346 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004347 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004348 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004349 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004350 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004351 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004352 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004353 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004354 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004355
4356 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4357 Decimal("11")
4358 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4359 Decimal("-11")
4360 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4361 Decimal("1")
4362 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4363 Decimal("11")
4364 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4365 Decimal("11729830")
4366 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4367 Decimal("-0")
4368 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4369 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004370 """
4371 return a.__pow__(b, modulo, context=self)
4372
4373 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004374 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004375
4376 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004377 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004378 exponent is being increased), multiplied by a positive power of ten (if
4379 the exponent is being decreased), or is unchanged (if the exponent is
4380 already equal to that of the right-hand operand).
4381
4382 Unlike other operations, if the length of the coefficient after the
4383 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004384 operation condition is raised. This guarantees that, unless there is
4385 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004386 equal to that of the right-hand operand.
4387
4388 Also unlike other operations, quantize will never raise Underflow, even
4389 if the result is subnormal and inexact.
4390
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004391 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004392 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004393 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004394 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004395 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004396 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004397 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004398 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004399 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004400 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004401 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004402 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004403 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004404 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004405 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004406 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004407 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004408 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004409 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004410 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004411 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004412 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004413 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004414 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004415 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004416 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004417 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004418 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004419 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004420 Decimal("2E+2")
4421 """
4422 return a.quantize(b, context=self)
4423
Facundo Batista353750c2007-09-13 18:13:15 +00004424 def radix(self):
4425 """Just returns 10, as this is Decimal, :)
4426
4427 >>> ExtendedContext.radix()
4428 Decimal("10")
4429 """
4430 return Decimal(10)
4431
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004432 def remainder(self, a, b):
4433 """Returns the remainder from integer division.
4434
4435 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004436 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004437 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004438 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004439
4440 This operation will fail under the same conditions as integer division
4441 (that is, if integer division on the same two operands would fail, the
4442 remainder cannot be calculated).
4443
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004444 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004445 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004446 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004447 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004448 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004449 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004450 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004451 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004452 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004453 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004454 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004455 Decimal("1.0")
4456 """
4457 return a.__mod__(b, context=self)
4458
4459 def remainder_near(self, a, b):
4460 """Returns to be "a - b * n", where n is the integer nearest the exact
4461 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004462 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004463 sign of a.
4464
4465 This operation will fail under the same conditions as integer division
4466 (that is, if integer division on the same two operands would fail, the
4467 remainder cannot be calculated).
4468
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004469 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004470 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004471 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004472 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004473 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004474 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004475 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004476 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004477 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004478 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004479 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004480 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004481 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004482 Decimal("-0.3")
4483 """
4484 return a.remainder_near(b, context=self)
4485
Facundo Batista353750c2007-09-13 18:13:15 +00004486 def rotate(self, a, b):
4487 """Returns a rotated copy of a, b times.
4488
4489 The coefficient of the result is a rotated copy of the digits in
4490 the coefficient of the first operand. The number of places of
4491 rotation is taken from the absolute value of the second operand,
4492 with the rotation being to the left if the second operand is
4493 positive or to the right otherwise.
4494
4495 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4496 Decimal("400000003")
4497 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4498 Decimal("12")
4499 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4500 Decimal("891234567")
4501 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4502 Decimal("123456789")
4503 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4504 Decimal("345678912")
4505 """
4506 return a.rotate(b, context=self)
4507
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004508 def same_quantum(self, a, b):
4509 """Returns True if the two operands have the same exponent.
4510
4511 The result is never affected by either the sign or the coefficient of
4512 either operand.
4513
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004514 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004515 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004516 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004517 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004518 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004519 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004520 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004521 True
4522 """
4523 return a.same_quantum(b)
4524
Facundo Batista353750c2007-09-13 18:13:15 +00004525 def scaleb (self, a, b):
4526 """Returns the first operand after adding the second value its exp.
4527
4528 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4529 Decimal("0.0750")
4530 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4531 Decimal("7.50")
4532 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4533 Decimal("7.50E+3")
4534 """
4535 return a.scaleb (b, context=self)
4536
4537 def shift(self, a, b):
4538 """Returns a shifted copy of a, b times.
4539
4540 The coefficient of the result is a shifted copy of the digits
4541 in the coefficient of the first operand. The number of places
4542 to shift is taken from the absolute value of the second operand,
4543 with the shift being to the left if the second operand is
4544 positive or to the right otherwise. Digits shifted into the
4545 coefficient are zeros.
4546
4547 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4548 Decimal("400000000")
4549 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4550 Decimal("0")
4551 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4552 Decimal("1234567")
4553 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4554 Decimal("123456789")
4555 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4556 Decimal("345678900")
4557 """
4558 return a.shift(b, context=self)
4559
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004560 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004561 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004562
4563 If the result must be inexact, it is rounded using the round-half-even
4564 algorithm.
4565
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004566 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004567 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004568 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004569 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004570 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004571 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004572 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004573 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004574 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004575 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004576 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004577 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004578 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004579 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004580 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004581 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004582 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004583 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004584 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004585 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004586 """
4587 return a.sqrt(context=self)
4588
4589 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004590 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004591
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004592 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004593 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004594 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004595 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004596 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004597 Decimal("-0.77")
4598 """
4599 return a.__sub__(b, context=self)
4600
4601 def to_eng_string(self, a):
4602 """Converts a number to a string, using scientific notation.
4603
4604 The operation is not affected by the context.
4605 """
4606 return a.to_eng_string(context=self)
4607
4608 def to_sci_string(self, a):
4609 """Converts a number to a string, using scientific notation.
4610
4611 The operation is not affected by the context.
4612 """
4613 return a.__str__(context=self)
4614
Facundo Batista353750c2007-09-13 18:13:15 +00004615 def to_integral_exact(self, a):
4616 """Rounds to an integer.
4617
4618 When the operand has a negative exponent, the result is the same
4619 as using the quantize() operation using the given operand as the
4620 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4621 of the operand as the precision setting; Inexact and Rounded flags
4622 are allowed in this operation. The rounding mode is taken from the
4623 context.
4624
4625 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4626 Decimal("2")
4627 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4628 Decimal("100")
4629 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4630 Decimal("100")
4631 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4632 Decimal("102")
4633 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4634 Decimal("-102")
4635 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4636 Decimal("1.0E+6")
4637 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4638 Decimal("7.89E+77")
4639 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4640 Decimal("-Infinity")
4641 """
4642 return a.to_integral_exact(context=self)
4643
4644 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004645 """Rounds to an integer.
4646
4647 When the operand has a negative exponent, the result is the same
4648 as using the quantize() operation using the given operand as the
4649 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4650 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004651 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004652
Facundo Batista353750c2007-09-13 18:13:15 +00004653 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004654 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004655 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004656 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004657 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004658 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004659 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004660 Decimal("102")
Facundo Batista353750c2007-09-13 18:13:15 +00004661 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004662 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004663 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004664 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004665 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004666 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004667 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004668 Decimal("-Infinity")
4669 """
Facundo Batista353750c2007-09-13 18:13:15 +00004670 return a.to_integral_value(context=self)
4671
4672 # the method name changed, but we provide also the old one, for compatibility
4673 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004674
4675class _WorkRep(object):
4676 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004677 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004678 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004679 # exp: None, int, or string
4680
4681 def __init__(self, value=None):
4682 if value is None:
4683 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004684 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004685 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004686 elif isinstance(value, Decimal):
4687 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004688 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004689 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004690 else:
4691 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004692 self.sign = value[0]
4693 self.int = value[1]
4694 self.exp = value[2]
4695
4696 def __repr__(self):
4697 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4698
4699 __str__ = __repr__
4700
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004701
4702
Facundo Batistae64acfa2007-12-17 14:18:42 +00004703def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004704 """Normalizes op1, op2 to have the same exp and length of coefficient.
4705
4706 Done during addition.
4707 """
Facundo Batista353750c2007-09-13 18:13:15 +00004708 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004709 tmp = op2
4710 other = op1
4711 else:
4712 tmp = op1
4713 other = op2
4714
Facundo Batista353750c2007-09-13 18:13:15 +00004715 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4716 # Then adding 10**exp to tmp has the same effect (after rounding)
4717 # as adding any positive quantity smaller than 10**exp; similarly
4718 # for subtraction. So if other is smaller than 10**exp we replace
4719 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00004720 tmp_len = len(str(tmp.int))
4721 other_len = len(str(other.int))
4722 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4723 if other_len + other.exp - 1 < exp:
4724 other.int = 1
4725 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004726
Facundo Batista353750c2007-09-13 18:13:15 +00004727 tmp.int *= 10 ** (tmp.exp - other.exp)
4728 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004729 return op1, op2
4730
Facundo Batista353750c2007-09-13 18:13:15 +00004731##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4732
4733# This function from Tim Peters was taken from here:
4734# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4735# The correction being in the function definition is for speed, and
4736# the whole function is not resolved with math.log because of avoiding
4737# the use of floats.
4738def _nbits(n, correction = {
4739 '0': 4, '1': 3, '2': 2, '3': 2,
4740 '4': 1, '5': 1, '6': 1, '7': 1,
4741 '8': 0, '9': 0, 'a': 0, 'b': 0,
4742 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4743 """Number of bits in binary representation of the positive integer n,
4744 or 0 if n == 0.
4745 """
4746 if n < 0:
4747 raise ValueError("The argument to _nbits should be nonnegative.")
4748 hex_n = "%x" % n
4749 return 4*len(hex_n) - correction[hex_n[0]]
4750
4751def _sqrt_nearest(n, a):
4752 """Closest integer to the square root of the positive integer n. a is
4753 an initial approximation to the square root. Any positive integer
4754 will do for a, but the closer a is to the square root of n the
4755 faster convergence will be.
4756
4757 """
4758 if n <= 0 or a <= 0:
4759 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4760
4761 b=0
4762 while a != b:
4763 b, a = a, a--n//a>>1
4764 return a
4765
4766def _rshift_nearest(x, shift):
4767 """Given an integer x and a nonnegative integer shift, return closest
4768 integer to x / 2**shift; use round-to-even in case of a tie.
4769
4770 """
4771 b, q = 1L << shift, x >> shift
4772 return q + (2*(x & (b-1)) + (q&1) > b)
4773
4774def _div_nearest(a, b):
4775 """Closest integer to a/b, a and b positive integers; rounds to even
4776 in the case of a tie.
4777
4778 """
4779 q, r = divmod(a, b)
4780 return q + (2*r + (q&1) > b)
4781
4782def _ilog(x, M, L = 8):
4783 """Integer approximation to M*log(x/M), with absolute error boundable
4784 in terms only of x/M.
4785
4786 Given positive integers x and M, return an integer approximation to
4787 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4788 between the approximation and the exact result is at most 22. For
4789 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4790 both cases these are upper bounds on the error; it will usually be
4791 much smaller."""
4792
4793 # The basic algorithm is the following: let log1p be the function
4794 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4795 # the reduction
4796 #
4797 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4798 #
4799 # repeatedly until the argument to log1p is small (< 2**-L in
4800 # absolute value). For small y we can use the Taylor series
4801 # expansion
4802 #
4803 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4804 #
4805 # truncating at T such that y**T is small enough. The whole
4806 # computation is carried out in a form of fixed-point arithmetic,
4807 # with a real number z being represented by an integer
4808 # approximation to z*M. To avoid loss of precision, the y below
4809 # is actually an integer approximation to 2**R*y*M, where R is the
4810 # number of reductions performed so far.
4811
4812 y = x-M
4813 # argument reduction; R = number of reductions performed
4814 R = 0
4815 while (R <= L and long(abs(y)) << L-R >= M or
4816 R > L and abs(y) >> R-L >= M):
4817 y = _div_nearest(long(M*y) << 1,
4818 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4819 R += 1
4820
4821 # Taylor series with T terms
4822 T = -int(-10*len(str(M))//(3*L))
4823 yshift = _rshift_nearest(y, R)
4824 w = _div_nearest(M, T)
4825 for k in xrange(T-1, 0, -1):
4826 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4827
4828 return _div_nearest(w*y, M)
4829
4830def _dlog10(c, e, p):
4831 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4832 approximation to 10**p * log10(c*10**e), with an absolute error of
4833 at most 1. Assumes that c*10**e is not exactly 1."""
4834
4835 # increase precision by 2; compensate for this by dividing
4836 # final result by 100
4837 p += 2
4838
4839 # write c*10**e as d*10**f with either:
4840 # f >= 0 and 1 <= d <= 10, or
4841 # f <= 0 and 0.1 <= d <= 1.
4842 # Thus for c*10**e close to 1, f = 0
4843 l = len(str(c))
4844 f = e+l - (e+l >= 1)
4845
4846 if p > 0:
4847 M = 10**p
4848 k = e+p-f
4849 if k >= 0:
4850 c *= 10**k
4851 else:
4852 c = _div_nearest(c, 10**-k)
4853
4854 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004855 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004856 log_d = _div_nearest(log_d*M, log_10)
4857 log_tenpower = f*M # exact
4858 else:
4859 log_d = 0 # error < 2.31
4860 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4861
4862 return _div_nearest(log_tenpower+log_d, 100)
4863
4864def _dlog(c, e, p):
4865 """Given integers c, e and p with c > 0, compute an integer
4866 approximation to 10**p * log(c*10**e), with an absolute error of
4867 at most 1. Assumes that c*10**e is not exactly 1."""
4868
4869 # Increase precision by 2. The precision increase is compensated
4870 # for at the end with a division by 100.
4871 p += 2
4872
4873 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4874 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4875 # as 10**p * log(d) + 10**p*f * log(10).
4876 l = len(str(c))
4877 f = e+l - (e+l >= 1)
4878
4879 # compute approximation to 10**p*log(d), with error < 27
4880 if p > 0:
4881 k = e+p-f
4882 if k >= 0:
4883 c *= 10**k
4884 else:
4885 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4886
4887 # _ilog magnifies existing error in c by a factor of at most 10
4888 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4889 else:
4890 # p <= 0: just approximate the whole thing by 0; error < 2.31
4891 log_d = 0
4892
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004893 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00004894 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004895 extra = len(str(abs(f)))-1
4896 if p + extra >= 0:
4897 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4898 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4899 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00004900 else:
4901 f_log_ten = 0
4902 else:
4903 f_log_ten = 0
4904
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004905 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004906 return _div_nearest(f_log_ten + log_d, 100)
4907
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004908class _Log10Memoize(object):
4909 """Class to compute, store, and allow retrieval of, digits of the
4910 constant log(10) = 2.302585.... This constant is needed by
4911 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4912 def __init__(self):
4913 self.digits = "23025850929940456840179914546843642076011014886"
4914
4915 def getdigits(self, p):
4916 """Given an integer p >= 0, return floor(10**p)*log(10).
4917
4918 For example, self.getdigits(3) returns 2302.
4919 """
4920 # digits are stored as a string, for quick conversion to
4921 # integer in the case that we've already computed enough
4922 # digits; the stored digits should always be correct
4923 # (truncated, not rounded to nearest).
4924 if p < 0:
4925 raise ValueError("p should be nonnegative")
4926
4927 if p >= len(self.digits):
4928 # compute p+3, p+6, p+9, ... digits; continue until at
4929 # least one of the extra digits is nonzero
4930 extra = 3
4931 while True:
4932 # compute p+extra digits, correct to within 1ulp
4933 M = 10**(p+extra+2)
4934 digits = str(_div_nearest(_ilog(10*M, M), 100))
4935 if digits[-extra:] != '0'*extra:
4936 break
4937 extra += 3
4938 # keep all reliable digits so far; remove trailing zeros
4939 # and next nonzero digit
4940 self.digits = digits.rstrip('0')[:-1]
4941 return int(self.digits[:p+1])
4942
4943_log10_digits = _Log10Memoize().getdigits
4944
Facundo Batista353750c2007-09-13 18:13:15 +00004945def _iexp(x, M, L=8):
4946 """Given integers x and M, M > 0, such that x/M is small in absolute
4947 value, compute an integer approximation to M*exp(x/M). For 0 <=
4948 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4949 is usually much smaller)."""
4950
4951 # Algorithm: to compute exp(z) for a real number z, first divide z
4952 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4953 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4954 # series
4955 #
4956 # expm1(x) = x + x**2/2! + x**3/3! + ...
4957 #
4958 # Now use the identity
4959 #
4960 # expm1(2x) = expm1(x)*(expm1(x)+2)
4961 #
4962 # R times to compute the sequence expm1(z/2**R),
4963 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
4964
4965 # Find R such that x/2**R/M <= 2**-L
4966 R = _nbits((long(x)<<L)//M)
4967
4968 # Taylor series. (2**L)**T > M
4969 T = -int(-10*len(str(M))//(3*L))
4970 y = _div_nearest(x, T)
4971 Mshift = long(M)<<R
4972 for i in xrange(T-1, 0, -1):
4973 y = _div_nearest(x*(Mshift + y), Mshift * i)
4974
4975 # Expansion
4976 for k in xrange(R-1, -1, -1):
4977 Mshift = long(M)<<(k+2)
4978 y = _div_nearest(y*(y+Mshift), Mshift)
4979
4980 return M+y
4981
4982def _dexp(c, e, p):
4983 """Compute an approximation to exp(c*10**e), with p decimal places of
4984 precision.
4985
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004986 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00004987
4988 10**(p-1) <= d <= 10**p, and
4989 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
4990
4991 In other words, d*10**f is an approximation to exp(c*10**e) with p
4992 digits of precision, and with an error in d of at most 1. This is
4993 almost, but not quite, the same as the error being < 1ulp: when d
4994 = 10**(p-1) the error could be up to 10 ulp."""
4995
4996 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
4997 p += 2
4998
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004999 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005000 extra = max(0, e + len(str(c)) - 1)
5001 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005002
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005003 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005004 # rounding down
5005 shift = e+q
5006 if shift >= 0:
5007 cshift = c*10**shift
5008 else:
5009 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005010 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005011
5012 # reduce remainder back to original precision
5013 rem = _div_nearest(rem, 10**extra)
5014
5015 # error in result of _iexp < 120; error after division < 0.62
5016 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5017
5018def _dpower(xc, xe, yc, ye, p):
5019 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5020 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5021
5022 10**(p-1) <= c <= 10**p, and
5023 (c-1)*10**e < x**y < (c+1)*10**e
5024
5025 in other words, c*10**e is an approximation to x**y with p digits
5026 of precision, and with an error in c of at most 1. (This is
5027 almost, but not quite, the same as the error being < 1ulp: when c
5028 == 10**(p-1) we can only guarantee error < 10ulp.)
5029
5030 We assume that: x is positive and not equal to 1, and y is nonzero.
5031 """
5032
5033 # Find b such that 10**(b-1) <= |y| <= 10**b
5034 b = len(str(abs(yc))) + ye
5035
5036 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5037 lxc = _dlog(xc, xe, p+b+1)
5038
5039 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5040 shift = ye-b
5041 if shift >= 0:
5042 pc = lxc*yc*10**shift
5043 else:
5044 pc = _div_nearest(lxc*yc, 10**-shift)
5045
5046 if pc == 0:
5047 # we prefer a result that isn't exactly 1; this makes it
5048 # easier to compute a correctly rounded result in __pow__
5049 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5050 coeff, exp = 10**(p-1)+1, 1-p
5051 else:
5052 coeff, exp = 10**p-1, -p
5053 else:
5054 coeff, exp = _dexp(pc, -(p+1), p+1)
5055 coeff = _div_nearest(coeff, 10)
5056 exp += 1
5057
5058 return coeff, exp
5059
5060def _log10_lb(c, correction = {
5061 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5062 '6': 23, '7': 16, '8': 10, '9': 5}):
5063 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5064 if c <= 0:
5065 raise ValueError("The argument to _log10_lb should be nonnegative.")
5066 str_c = str(c)
5067 return 100*len(str_c) - correction[str_c[0]]
5068
Facundo Batista59c58842007-04-10 12:58:45 +00005069##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005070
Facundo Batista353750c2007-09-13 18:13:15 +00005071def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005072 """Convert other to Decimal.
5073
5074 Verifies that it's ok to use in an implicit construction.
5075 """
5076 if isinstance(other, Decimal):
5077 return other
5078 if isinstance(other, (int, long)):
5079 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005080 if raiseit:
5081 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005082 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005083
Facundo Batista59c58842007-04-10 12:58:45 +00005084##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005085
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005086# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005087# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005088
5089DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005090 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005091 traps=[DivisionByZero, Overflow, InvalidOperation],
5092 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005093 Emax=999999999,
5094 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005095 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005096)
5097
5098# Pre-made alternate contexts offered by the specification
5099# Don't change these; the user should be able to select these
5100# contexts and be able to reproduce results from other implementations
5101# of the spec.
5102
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005103BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005104 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005105 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5106 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005107)
5108
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005109ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005110 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005111 traps=[],
5112 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005113)
5114
5115
Facundo Batista72bc54f2007-11-23 17:59:00 +00005116##### crud for parsing strings #############################################
5117import re
5118
5119# Regular expression used for parsing numeric strings. Additional
5120# comments:
5121#
5122# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5123# whitespace. But note that the specification disallows whitespace in
5124# a numeric string.
5125#
5126# 2. For finite numbers (not infinities and NaNs) the body of the
5127# number between the optional sign and the optional exponent must have
5128# at least one decimal digit, possibly after the decimal point. The
5129# lookahead expression '(?=\d|\.\d)' checks this.
5130#
5131# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5132# other meaning for \d than the numbers [0-9].
5133
5134import re
5135_parser = re.compile(r""" # A numeric string consists of:
5136# \s*
5137 (?P<sign>[-+])? # an optional sign, followed by either...
5138 (
5139 (?=\d|\.\d) # ...a number (with at least one digit)
5140 (?P<int>\d*) # consisting of a (possibly empty) integer part
5141 (\.(?P<frac>\d*))? # followed by an optional fractional part
5142 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5143 |
5144 Inf(inity)? # ...an infinity, or...
5145 |
5146 (?P<signal>s)? # ...an (optionally signaling)
5147 NaN # NaN
5148 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5149 )
5150# \s*
5151 $
5152""", re.VERBOSE | re.IGNORECASE).match
5153
Facundo Batista2ec74152007-12-03 17:55:00 +00005154_all_zeros = re.compile('0*$').match
5155_exact_half = re.compile('50*$').match
Facundo Batista72bc54f2007-11-23 17:59:00 +00005156del re
5157
5158
Facundo Batista59c58842007-04-10 12:58:45 +00005159##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005160
Facundo Batista59c58842007-04-10 12:58:45 +00005161# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005162Inf = Decimal('Inf')
5163negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005164NaN = Decimal('NaN')
5165Dec_0 = Decimal(0)
5166Dec_p1 = Decimal(1)
5167Dec_n1 = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005168
Facundo Batista59c58842007-04-10 12:58:45 +00005169# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005170Infsign = (Inf, negInf)
5171
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005172
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005173
5174if __name__ == '__main__':
5175 import doctest, sys
5176 doctest.testmod(sys.modules[__name__])