blob: 257ba0c118b152a5ba8cd2b7d3e101d8830d255c [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
Facundo Batista59c58842007-04-10 12:58:45 +0000139# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000140ROUND_DOWN = 'ROUND_DOWN'
141ROUND_HALF_UP = 'ROUND_HALF_UP'
142ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
143ROUND_CEILING = 'ROUND_CEILING'
144ROUND_FLOOR = 'ROUND_FLOOR'
145ROUND_UP = 'ROUND_UP'
146ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Facundo Batista353750c2007-09-13 18:13:15 +0000147ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000148
Facundo Batista59c58842007-04-10 12:58:45 +0000149# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000150
151class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000152 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000153
154 Used exceptions derive from this.
155 If an exception derives from another exception besides this (such as
156 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
157 called if the others are present. This isn't actually used for
158 anything, though.
159
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000160 handle -- Called when context._raise_error is called and the
161 trap_enabler is set. First argument is self, second is the
162 context. More arguments can be given, those being after
163 the explanation in _raise_error (For example,
164 context._raise_error(NewError, '(-x)!', self._sign) would
165 call NewError().handle(context, self._sign).)
166
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000167 To define a new exception, it should be sufficient to have it derive
168 from DecimalException.
169 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000170 def handle(self, context, *args):
171 pass
172
173
174class Clamped(DecimalException):
175 """Exponent of a 0 changed to fit bounds.
176
177 This occurs and signals clamped if the exponent of a result has been
178 altered in order to fit the constraints of a specific concrete
Facundo Batista59c58842007-04-10 12:58:45 +0000179 representation. This may occur when the exponent of a zero result would
180 be outside the bounds of a representation, or when a large normal
181 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000182 this latter case, the exponent is reduced to fit and the corresponding
183 number of zero digits are appended to the coefficient ("fold-down").
184 """
185
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000186class InvalidOperation(DecimalException):
187 """An invalid operation was performed.
188
189 Various bad things cause this:
190
191 Something creates a signaling NaN
192 -INF + INF
Facundo Batista59c58842007-04-10 12:58:45 +0000193 0 * (+-)INF
194 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000195 x % 0
196 (+-)INF % x
197 x._rescale( non-integer )
198 sqrt(-x) , x > 0
199 0 ** 0
200 x ** (non-integer)
201 x ** (+-)INF
202 An operand is invalid
Facundo Batista353750c2007-09-13 18:13:15 +0000203
204 The result of the operation after these is a quiet positive NaN,
205 except when the cause is a signaling NaN, in which case the result is
206 also a quiet NaN, but with the original sign, and an optional
207 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000208 """
209 def handle(self, context, *args):
210 if args:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000211 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
212 return ans._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000213 return NaN
214
215class ConversionSyntax(InvalidOperation):
216 """Trying to convert badly formed string.
217
218 This occurs and signals invalid-operation if an string is being
219 converted to a number and it does not conform to the numeric string
Facundo Batista59c58842007-04-10 12:58:45 +0000220 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000221 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000222 def handle(self, context, *args):
Facundo Batista353750c2007-09-13 18:13:15 +0000223 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000224
225class DivisionByZero(DecimalException, ZeroDivisionError):
226 """Division by 0.
227
228 This occurs and signals division-by-zero if division of a finite number
229 by zero was attempted (during a divide-integer or divide operation, or a
230 power operation with negative right-hand operand), and the dividend was
231 not zero.
232
233 The result of the operation is [sign,inf], where sign is the exclusive
234 or of the signs of the operands for divide, or is 1 for an odd power of
235 -0, for power.
236 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000237
Facundo Batistacce8df22007-09-18 16:53:18 +0000238 def handle(self, context, sign, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000239 return Infsign[sign]
240
241class DivisionImpossible(InvalidOperation):
242 """Cannot perform the division adequately.
243
244 This occurs and signals invalid-operation if the integer result of a
245 divide-integer or remainder operation had too many digits (would be
Facundo Batista59c58842007-04-10 12:58:45 +0000246 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000247 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000248
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000249 def handle(self, context, *args):
Facundo Batistacce8df22007-09-18 16:53:18 +0000250 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000251
252class DivisionUndefined(InvalidOperation, ZeroDivisionError):
253 """Undefined result of division.
254
255 This occurs and signals invalid-operation if division by zero was
256 attempted (during a divide-integer, divide, or remainder operation), and
Facundo Batista59c58842007-04-10 12:58:45 +0000257 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000258 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000259
Facundo Batistacce8df22007-09-18 16:53:18 +0000260 def handle(self, context, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000261 return NaN
262
263class Inexact(DecimalException):
264 """Had to round, losing information.
265
266 This occurs and signals inexact whenever the result of an operation is
267 not exact (that is, it needed to be rounded and any discarded digits
Facundo Batista59c58842007-04-10 12:58:45 +0000268 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000269 result in all cases is unchanged.
270
271 The inexact signal may be tested (or trapped) to determine if a given
272 operation (or sequence of operations) was inexact.
273 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000274
275class InvalidContext(InvalidOperation):
276 """Invalid context. Unknown rounding, for example.
277
278 This occurs and signals invalid-operation if an invalid context was
Facundo Batista59c58842007-04-10 12:58:45 +0000279 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000280 on creation and either the precision exceeds the capability of the
281 underlying concrete representation or an unknown or unsupported rounding
Facundo Batista59c58842007-04-10 12:58:45 +0000282 was specified. These aspects of the context need only be checked when
283 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000284 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000285
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000286 def handle(self, context, *args):
287 return NaN
288
289class Rounded(DecimalException):
290 """Number got rounded (not necessarily changed during rounding).
291
292 This occurs and signals rounded whenever the result of an operation is
293 rounded (that is, some zero or non-zero digits were discarded from the
Facundo Batista59c58842007-04-10 12:58:45 +0000294 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000295 result in all cases is unchanged.
296
297 The rounded signal may be tested (or trapped) to determine if a given
298 operation (or sequence of operations) caused a loss of precision.
299 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000300
301class Subnormal(DecimalException):
302 """Exponent < Emin before rounding.
303
304 This occurs and signals subnormal whenever the result of a conversion or
305 operation is subnormal (that is, its adjusted exponent is less than
Facundo Batista59c58842007-04-10 12:58:45 +0000306 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000307
308 The subnormal signal may be tested (or trapped) to determine if a given
309 or operation (or sequence of operations) yielded a subnormal result.
310 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000311
312class Overflow(Inexact, Rounded):
313 """Numerical overflow.
314
315 This occurs and signals overflow if the adjusted exponent of a result
316 (from a conversion or from an operation that is not an attempt to divide
317 by zero), after rounding, would be greater than the largest value that
318 can be handled by the implementation (the value Emax).
319
320 The result depends on the rounding mode:
321
322 For round-half-up and round-half-even (and for round-half-down and
323 round-up, if implemented), the result of the operation is [sign,inf],
Facundo Batista59c58842007-04-10 12:58:45 +0000324 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000325 result is the largest finite number that can be represented in the
Facundo Batista59c58842007-04-10 12:58:45 +0000326 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000327 round-ceiling, the result is the same as for round-down if the sign of
Facundo Batista59c58842007-04-10 12:58:45 +0000328 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000329 the result is the same as for round-down if the sign of the intermediate
Facundo Batista59c58842007-04-10 12:58:45 +0000330 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000331 will also be raised.
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000332 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000333
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000334 def handle(self, context, sign, *args):
335 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Facundo Batista353750c2007-09-13 18:13:15 +0000336 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 return Infsign[sign]
338 if sign == 0:
339 if context.rounding == ROUND_CEILING:
340 return Infsign[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000341 return _dec_from_triple(sign, '9'*context.prec,
342 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000343 if sign == 1:
344 if context.rounding == ROUND_FLOOR:
345 return Infsign[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000346 return _dec_from_triple(sign, '9'*context.prec,
347 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000348
349
350class Underflow(Inexact, Rounded, Subnormal):
351 """Numerical underflow with result rounded to 0.
352
353 This occurs and signals underflow if a result is inexact and the
354 adjusted exponent of the result would be smaller (more negative) than
355 the smallest value that can be handled by the implementation (the value
Facundo Batista59c58842007-04-10 12:58:45 +0000356 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000357
358 The result after an underflow will be a subnormal number rounded, if
Facundo Batista59c58842007-04-10 12:58:45 +0000359 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000360 in 0 with the sign of the intermediate result and an exponent of Etiny.
361
362 In all cases, Inexact, Rounded, and Subnormal will also be raised.
363 """
364
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000365# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000366_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000367 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000368
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000369# Map conditions (per the spec) to signals
370_condition_map = {ConversionSyntax:InvalidOperation,
371 DivisionImpossible:InvalidOperation,
372 DivisionUndefined:InvalidOperation,
373 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000374
Facundo Batista59c58842007-04-10 12:58:45 +0000375##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000376
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000377# The getcontext() and setcontext() function manage access to a thread-local
378# current context. Py2.4 offers direct support for thread locals. If that
379# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000380# work for older Pythons. If threads are not part of the build, create a
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000381# mock threading object with threading.local() returning the module namespace.
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000382
383try:
384 import threading
385except ImportError:
386 # Python was compiled without threads; create a mock object instead
387 import sys
Facundo Batista59c58842007-04-10 12:58:45 +0000388 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000389 def local(self, sys=sys):
390 return sys.modules[__name__]
391 threading = MockThreading()
392 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000393
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000394try:
395 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000396
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000397except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000398
Facundo Batista59c58842007-04-10 12:58:45 +0000399 # To fix reloading, force it to create a new context
400 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000401 if hasattr(threading.currentThread(), '__decimal_context__'):
402 del threading.currentThread().__decimal_context__
403
404 def setcontext(context):
405 """Set this thread's context to context."""
406 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000407 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000408 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000409 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000410
411 def getcontext():
412 """Returns this thread's context.
413
414 If this thread does not yet have a context, returns
415 a new context and sets this thread's context.
416 New contexts are copies of DefaultContext.
417 """
418 try:
419 return threading.currentThread().__decimal_context__
420 except AttributeError:
421 context = Context()
422 threading.currentThread().__decimal_context__ = context
423 return context
424
425else:
426
427 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000428 if hasattr(local, '__decimal_context__'):
429 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000430
431 def getcontext(_local=local):
432 """Returns this thread's context.
433
434 If this thread does not yet have a context, returns
435 a new context and sets this thread's context.
436 New contexts are copies of DefaultContext.
437 """
438 try:
439 return _local.__decimal_context__
440 except AttributeError:
441 context = Context()
442 _local.__decimal_context__ = context
443 return context
444
445 def setcontext(context, _local=local):
446 """Set this thread's context to context."""
447 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000448 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000449 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000450 _local.__decimal_context__ = context
451
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000452 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000453
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000454def localcontext(ctx=None):
455 """Return a context manager for a copy of the supplied context
456
457 Uses a copy of the current context if no context is specified
458 The returned context manager creates a local decimal context
459 in a with statement:
460 def sin(x):
461 with localcontext() as ctx:
462 ctx.prec += 2
463 # Rest of sin calculation algorithm
464 # uses a precision 2 greater than normal
Facundo Batista59c58842007-04-10 12:58:45 +0000465 return +s # Convert result to normal precision
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000466
467 def sin(x):
468 with localcontext(ExtendedContext):
469 # Rest of sin calculation algorithm
470 # uses the Extended Context from the
471 # General Decimal Arithmetic Specification
Facundo Batista59c58842007-04-10 12:58:45 +0000472 return +s # Convert result to normal context
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000473
474 """
Neal Norwitz681d8672006-09-02 18:51:34 +0000475 # The string below can't be included in the docstring until Python 2.6
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000476 # as the doctest module doesn't understand __future__ statements
477 """
478 >>> from __future__ import with_statement
479 >>> print getcontext().prec
480 28
481 >>> with localcontext():
482 ... ctx = getcontext()
Raymond Hettinger495df472007-02-08 01:42:35 +0000483 ... ctx.prec += 2
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000484 ... print ctx.prec
485 ...
486 30
487 >>> with localcontext(ExtendedContext):
488 ... print getcontext().prec
489 ...
490 9
491 >>> print getcontext().prec
492 28
493 """
Nick Coghlanced12182006-09-02 03:54:17 +0000494 if ctx is None: ctx = getcontext()
495 return _ContextManager(ctx)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000496
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000497
Facundo Batista59c58842007-04-10 12:58:45 +0000498##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000499
500class Decimal(object):
501 """Floating point class for decimal arithmetic."""
502
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000503 __slots__ = ('_exp','_int','_sign', '_is_special')
504 # Generally, the value of the Decimal instance is given by
505 # (-1)**_sign * _int * 10**_exp
506 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000507
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000508 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000509 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000510 """Create a decimal point instance.
511
512 >>> Decimal('3.14') # string input
513 Decimal("3.14")
Facundo Batista59c58842007-04-10 12:58:45 +0000514 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000515 Decimal("3.14")
516 >>> Decimal(314) # int or long
517 Decimal("314")
518 >>> Decimal(Decimal(314)) # another decimal instance
519 Decimal("314")
520 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000521
Facundo Batista72bc54f2007-11-23 17:59:00 +0000522 # Note that the coefficient, self._int, is actually stored as
523 # a string rather than as a tuple of digits. This speeds up
524 # the "digits to integer" and "integer to digits" conversions
525 # that are used in almost every arithmetic operation on
526 # Decimals. This is an internal detail: the as_tuple function
527 # and the Decimal constructor still deal with tuples of
528 # digits.
529
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000530 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000531
Facundo Batista0d157a02007-11-30 17:15:25 +0000532 # From a string
533 # REs insist on real strings, so we can too.
534 if isinstance(value, basestring):
535 m = _parser(value)
536 if m is None:
537 if context is None:
538 context = getcontext()
539 return context._raise_error(ConversionSyntax,
540 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000541
Facundo Batista0d157a02007-11-30 17:15:25 +0000542 if m.group('sign') == "-":
543 self._sign = 1
544 else:
545 self._sign = 0
546 intpart = m.group('int')
547 if intpart is not None:
548 # finite number
549 fracpart = m.group('frac')
550 exp = int(m.group('exp') or '0')
551 if fracpart is not None:
552 self._int = (intpart+fracpart).lstrip('0') or '0'
553 self._exp = exp - len(fracpart)
554 else:
555 self._int = intpart.lstrip('0') or '0'
556 self._exp = exp
557 self._is_special = False
558 else:
559 diag = m.group('diag')
560 if diag is not None:
561 # NaN
562 self._int = diag.lstrip('0')
563 if m.group('signal'):
564 self._exp = 'N'
565 else:
566 self._exp = 'n'
567 else:
568 # infinity
569 self._int = '0'
570 self._exp = 'F'
571 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000572 return self
573
574 # From an integer
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000575 if isinstance(value, (int,long)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000576 if value >= 0:
577 self._sign = 0
578 else:
579 self._sign = 1
580 self._exp = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +0000581 self._int = str(abs(value))
Facundo Batista0d157a02007-11-30 17:15:25 +0000582 self._is_special = False
583 return self
584
585 # From another decimal
586 if isinstance(value, Decimal):
587 self._exp = value._exp
588 self._sign = value._sign
589 self._int = value._int
590 self._is_special = value._is_special
591 return self
592
593 # From an internal working value
594 if isinstance(value, _WorkRep):
595 self._sign = value.sign
596 self._int = str(value.int)
597 self._exp = int(value.exp)
598 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000599 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000600
601 # tuple/list conversion (possibly from as_tuple())
602 if isinstance(value, (list,tuple)):
603 if len(value) != 3:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000604 raise ValueError('Invalid tuple size in creation of Decimal '
605 'from list or tuple. The list or tuple '
606 'should have exactly three elements.')
607 # process sign. The isinstance test rejects floats
608 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
609 raise ValueError("Invalid sign. The first value in the tuple "
610 "should be an integer; either 0 for a "
611 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000612 self._sign = value[0]
Facundo Batista9b5e2312007-10-19 19:25:57 +0000613 if value[2] == 'F':
614 # infinity: value[1] is ignored
Facundo Batista72bc54f2007-11-23 17:59:00 +0000615 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000616 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000617 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000618 else:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000619 # process and validate the digits in value[1]
620 digits = []
621 for digit in value[1]:
622 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
623 # skip leading zeros
624 if digits or digit != 0:
625 digits.append(digit)
626 else:
627 raise ValueError("The second value in the tuple must "
628 "be composed of integers in the range "
629 "0 through 9.")
630 if value[2] in ('n', 'N'):
631 # NaN: digits form the diagnostic
Facundo Batista72bc54f2007-11-23 17:59:00 +0000632 self._int = ''.join(map(str, digits))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000633 self._exp = value[2]
634 self._is_special = True
635 elif isinstance(value[2], (int, long)):
636 # finite number: digits give the coefficient
Facundo Batista72bc54f2007-11-23 17:59:00 +0000637 self._int = ''.join(map(str, digits or [0]))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000638 self._exp = value[2]
639 self._is_special = False
640 else:
641 raise ValueError("The third value in the tuple must "
642 "be an integer, or one of the "
643 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000644 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000645
Raymond Hettingerbf440692004-07-10 14:14:37 +0000646 if isinstance(value, float):
647 raise TypeError("Cannot convert float to Decimal. " +
648 "First convert the float to a string")
649
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000650 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000651
652 def _isnan(self):
653 """Returns whether the number is not actually one.
654
655 0 if a number
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000656 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000657 2 if sNaN
658 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000659 if self._is_special:
660 exp = self._exp
661 if exp == 'n':
662 return 1
663 elif exp == 'N':
664 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000665 return 0
666
667 def _isinfinity(self):
668 """Returns whether the number is infinite
669
670 0 if finite or not a number
671 1 if +INF
672 -1 if -INF
673 """
674 if self._exp == 'F':
675 if self._sign:
676 return -1
677 return 1
678 return 0
679
Facundo Batista353750c2007-09-13 18:13:15 +0000680 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000681 """Returns whether the number is not actually one.
682
683 if self, other are sNaN, signal
684 if self, other are NaN return nan
685 return 0
686
687 Done before operations.
688 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000689
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000690 self_is_nan = self._isnan()
691 if other is None:
692 other_is_nan = False
693 else:
694 other_is_nan = other._isnan()
695
696 if self_is_nan or other_is_nan:
697 if context is None:
698 context = getcontext()
699
700 if self_is_nan == 2:
701 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000702 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000703 if other_is_nan == 2:
704 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000705 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000706 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000707 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000708
Facundo Batista353750c2007-09-13 18:13:15 +0000709 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000710 return 0
711
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000712 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000713 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000714
Facundo Batista1a191df2007-10-02 17:01:24 +0000715 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000716 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000717 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000718
Facundo Batista353750c2007-09-13 18:13:15 +0000719 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000720 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000721 if other is NotImplemented:
Facundo Batista353750c2007-09-13 18:13:15 +0000722 # Never return NotImplemented
723 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000724
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000725 if self._is_special or other._is_special:
Facundo Batista353750c2007-09-13 18:13:15 +0000726 # check for nans, without raising on a signaling nan
727 if self._isnan() or other._isnan():
Facundo Batista59c58842007-04-10 12:58:45 +0000728 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000729
730 # INF = INF
731 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000732
Facundo Batista353750c2007-09-13 18:13:15 +0000733 # check for zeros; note that cmp(0, -0) should return 0
734 if not self:
735 if not other:
736 return 0
737 else:
738 return -((-1)**other._sign)
739 if not other:
740 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000741
Facundo Batista59c58842007-04-10 12:58:45 +0000742 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000743 if other._sign < self._sign:
744 return -1
745 if self._sign < other._sign:
746 return 1
747
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000748 self_adjusted = self.adjusted()
749 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000750 if self_adjusted == other_adjusted:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000751 self_padded = self._int + '0'*(self._exp - other._exp)
752 other_padded = other._int + '0'*(other._exp - self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +0000753 return cmp(self_padded, other_padded) * (-1)**self._sign
754 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000755 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000756 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000757 return -((-1)**self._sign)
758
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000759 def __eq__(self, other):
760 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000761 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000762 return self.__cmp__(other) == 0
763
764 def __ne__(self, other):
765 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000766 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000767 return self.__cmp__(other) != 0
768
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000769 def compare(self, other, context=None):
770 """Compares one to another.
771
772 -1 => a < b
773 0 => a = b
774 1 => a > b
775 NaN => one is NaN
776 Like __cmp__, but returns Decimal instances.
777 """
Facundo Batista353750c2007-09-13 18:13:15 +0000778 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000779
Facundo Batista59c58842007-04-10 12:58:45 +0000780 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000781 if (self._is_special or other and other._is_special):
782 ans = self._check_nans(other, context)
783 if ans:
784 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000785
Facundo Batista353750c2007-09-13 18:13:15 +0000786 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000787
788 def __hash__(self):
789 """x.__hash__() <==> hash(x)"""
790 # Decimal integers must hash the same as the ints
791 # Non-integer decimals are normalized and hashed as strings
Georg Brandl1fb9f522006-05-11 19:57:09 +0000792 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000793 if self._is_special:
794 if self._isnan():
795 raise TypeError('Cannot hash a NaN value.')
796 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000797 if not self:
798 return 0
799 if self._isinteger():
800 op = _WorkRep(self.to_integral_value())
801 # to make computation feasible for Decimals with large
802 # exponent, we use the fact that hash(n) == hash(m) for
803 # any two nonzero integers n and m such that (i) n and m
804 # have the same sign, and (ii) n is congruent to m modulo
805 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
806 # hash((-1)**s*c*pow(10, e, 2**64-1).
807 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000808 return hash(str(self.normalize()))
809
810 def as_tuple(self):
811 """Represents the number as a triple tuple.
812
813 To show the internals exactly as they are.
814 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000815 return (self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000816
817 def __repr__(self):
818 """Represents the number as an instance of Decimal."""
819 # Invariant: eval(repr(d)) == d
820 return 'Decimal("%s")' % str(self)
821
Facundo Batista353750c2007-09-13 18:13:15 +0000822 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000823 """Return string representation of the number in scientific notation.
824
825 Captures all of the information in the underlying representation.
826 """
827
Facundo Batista62edb712007-12-03 16:29:52 +0000828 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000829 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +0000830 if self._exp == 'F':
831 return sign + 'Infinity'
832 elif self._exp == 'n':
833 return sign + 'NaN' + self._int
834 else: # self._exp == 'N'
835 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000836
Facundo Batista62edb712007-12-03 16:29:52 +0000837 # number of digits of self._int to left of decimal point
838 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000839
Facundo Batista62edb712007-12-03 16:29:52 +0000840 # dotplace is number of digits of self._int to the left of the
841 # decimal point in the mantissa of the output string (that is,
842 # after adjusting the exponent)
843 if self._exp <= 0 and leftdigits > -6:
844 # no exponent required
845 dotplace = leftdigits
846 elif not eng:
847 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000848 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +0000849 elif self._int == '0':
850 # engineering notation, zero
851 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000852 else:
Facundo Batista62edb712007-12-03 16:29:52 +0000853 # engineering notation, nonzero
854 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000855
Facundo Batista62edb712007-12-03 16:29:52 +0000856 if dotplace <= 0:
857 intpart = '0'
858 fracpart = '.' + '0'*(-dotplace) + self._int
859 elif dotplace >= len(self._int):
860 intpart = self._int+'0'*(dotplace-len(self._int))
861 fracpart = ''
862 else:
863 intpart = self._int[:dotplace]
864 fracpart = '.' + self._int[dotplace:]
865 if leftdigits == dotplace:
866 exp = ''
867 else:
868 if context is None:
869 context = getcontext()
870 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
871
872 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000873
874 def to_eng_string(self, context=None):
875 """Convert to engineering-type string.
876
877 Engineering notation has an exponent which is a multiple of 3, so there
878 are up to 3 digits left of the decimal place.
879
880 Same rules for when in exponential and when as a value as in __str__.
881 """
Facundo Batista353750c2007-09-13 18:13:15 +0000882 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000883
884 def __neg__(self, context=None):
885 """Returns a copy with the sign switched.
886
887 Rounds, if it has reason.
888 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000889 if self._is_special:
890 ans = self._check_nans(context=context)
891 if ans:
892 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000893
894 if not self:
895 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000896 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000897 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000898 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000899
900 if context is None:
901 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +0000902 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000903
904 def __pos__(self, context=None):
905 """Returns a copy, unless it is a sNaN.
906
907 Rounds the number (if more then precision digits)
908 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000909 if self._is_special:
910 ans = self._check_nans(context=context)
911 if ans:
912 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000913
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000914 if not self:
915 # + (-0) = 0
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000916 ans = self.copy_abs()
Facundo Batista353750c2007-09-13 18:13:15 +0000917 else:
918 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000919
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000920 if context is None:
921 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +0000922 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000923
Facundo Batistae64acfa2007-12-17 14:18:42 +0000924 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000925 """Returns the absolute value of self.
926
Facundo Batistae64acfa2007-12-17 14:18:42 +0000927 If the keyword argument 'round' is false, do not round. The
928 expression self.__abs__(round=False) is equivalent to
929 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000930 """
Facundo Batistae64acfa2007-12-17 14:18:42 +0000931 if not round:
932 return self.copy_abs()
933
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000934 if self._is_special:
935 ans = self._check_nans(context=context)
936 if ans:
937 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000938
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000939 if self._sign:
940 ans = self.__neg__(context=context)
941 else:
942 ans = self.__pos__(context=context)
943
944 return ans
945
946 def __add__(self, other, context=None):
947 """Returns self + other.
948
949 -INF + INF (or the reverse) cause InvalidOperation errors.
950 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000951 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000952 if other is NotImplemented:
953 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000954
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000955 if context is None:
956 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000957
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000958 if self._is_special or other._is_special:
959 ans = self._check_nans(other, context)
960 if ans:
961 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000962
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000963 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000964 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000965 if self._sign != other._sign and other._isinfinity():
966 return context._raise_error(InvalidOperation, '-INF + INF')
967 return Decimal(self)
968 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000969 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000970
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971 exp = min(self._exp, other._exp)
972 negativezero = 0
973 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +0000974 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000975 negativezero = 1
976
977 if not self and not other:
978 sign = min(self._sign, other._sign)
979 if negativezero:
980 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +0000981 ans = _dec_from_triple(sign, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +0000982 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +0000983 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000984 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +0000985 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +0000986 ans = other._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +0000987 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000988 return ans
989 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +0000990 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +0000991 ans = self._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +0000992 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000993 return ans
994
995 op1 = _WorkRep(self)
996 op2 = _WorkRep(other)
Facundo Batistae64acfa2007-12-17 14:18:42 +0000997 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000998
999 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001001 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001002 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001003 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001004 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001005 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001006 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001007 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001008 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001009 if op1.sign == 1:
1010 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001011 op1.sign, op2.sign = op2.sign, op1.sign
1012 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001013 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001014 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001015 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001016 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001017 op1.sign, op2.sign = (0, 0)
1018 else:
1019 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001020 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001021
Raymond Hettinger17931de2004-10-27 06:21:46 +00001022 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001023 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001024 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001025 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001026
1027 result.exp = op1.exp
1028 ans = Decimal(result)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001029 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001030 return ans
1031
1032 __radd__ = __add__
1033
1034 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001035 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001036 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001037 if other is NotImplemented:
1038 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001039
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001040 if self._is_special or other._is_special:
1041 ans = self._check_nans(other, context=context)
1042 if ans:
1043 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001044
Facundo Batista353750c2007-09-13 18:13:15 +00001045 # self - other is computed as self + other.copy_negate()
1046 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001047
1048 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001049 """Return other - self"""
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
Facundo Batista353750c2007-09-13 18:13:15 +00001054 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001056 def __mul__(self, other, context=None):
1057 """Return self * other.
1058
1059 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1060 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001061 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001062 if other is NotImplemented:
1063 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001064
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001065 if context is None:
1066 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001067
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001068 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001069
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001070 if self._is_special or other._is_special:
1071 ans = self._check_nans(other, context)
1072 if ans:
1073 return ans
1074
1075 if self._isinfinity():
1076 if not other:
1077 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1078 return Infsign[resultsign]
1079
1080 if other._isinfinity():
1081 if not self:
1082 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1083 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001084
1085 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001086
1087 # Special case for multiplying by zero
1088 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001089 ans = _dec_from_triple(resultsign, '0', resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001090 # Fixing in case the exponent is out of bounds
1091 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001092 return ans
1093
1094 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001095 if self._int == '1':
1096 ans = _dec_from_triple(resultsign, other._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001097 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001098 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001099 if other._int == '1':
1100 ans = _dec_from_triple(resultsign, self._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001101 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001102 return ans
1103
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001104 op1 = _WorkRep(self)
1105 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001106
Facundo Batista72bc54f2007-11-23 17:59:00 +00001107 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001108 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001109
1110 return ans
1111 __rmul__ = __mul__
1112
1113 def __div__(self, other, context=None):
1114 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001115 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001116 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001117 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001118
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001119 if context is None:
1120 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001121
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001122 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001123
1124 if self._is_special or other._is_special:
1125 ans = self._check_nans(other, context)
1126 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001127 return ans
1128
1129 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001130 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001131
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001132 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001133 return Infsign[sign]
1134
1135 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001136 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001137 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001138
1139 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001140 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001141 if not self:
1142 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001143 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001144
Facundo Batistacce8df22007-09-18 16:53:18 +00001145 if not self:
1146 exp = self._exp - other._exp
1147 coeff = 0
1148 else:
1149 # OK, so neither = 0, INF or NaN
1150 shift = len(other._int) - len(self._int) + context.prec + 1
1151 exp = self._exp - other._exp - shift
1152 op1 = _WorkRep(self)
1153 op2 = _WorkRep(other)
1154 if shift >= 0:
1155 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1156 else:
1157 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1158 if remainder:
1159 # result is not exact; adjust to ensure correct rounding
1160 if coeff % 5 == 0:
1161 coeff += 1
1162 else:
1163 # result is exact; get as close to ideal exponent as possible
1164 ideal_exp = self._exp - other._exp
1165 while exp < ideal_exp and coeff % 10 == 0:
1166 coeff //= 10
1167 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001168
Facundo Batista72bc54f2007-11-23 17:59:00 +00001169 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001170 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001171
Facundo Batistacce8df22007-09-18 16:53:18 +00001172 __truediv__ = __div__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001173
Facundo Batistacce8df22007-09-18 16:53:18 +00001174 def _divide(self, other, context):
1175 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001176
Facundo Batistacce8df22007-09-18 16:53:18 +00001177 Assumes that neither self nor other is a NaN, that self is not
1178 infinite and that other is nonzero.
1179 """
1180 sign = self._sign ^ other._sign
1181 if other._isinfinity():
1182 ideal_exp = self._exp
1183 else:
1184 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001185
Facundo Batistacce8df22007-09-18 16:53:18 +00001186 expdiff = self.adjusted() - other.adjusted()
1187 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001188 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001189 self._rescale(ideal_exp, context.rounding))
1190 if expdiff <= context.prec:
1191 op1 = _WorkRep(self)
1192 op2 = _WorkRep(other)
1193 if op1.exp >= op2.exp:
1194 op1.int *= 10**(op1.exp - op2.exp)
1195 else:
1196 op2.int *= 10**(op2.exp - op1.exp)
1197 q, r = divmod(op1.int, op2.int)
1198 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001199 return (_dec_from_triple(sign, str(q), 0),
1200 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001201
Facundo Batistacce8df22007-09-18 16:53:18 +00001202 # Here the quotient is too large to be representable
1203 ans = context._raise_error(DivisionImpossible,
1204 'quotient too large in //, % or divmod')
1205 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001206
1207 def __rdiv__(self, other, context=None):
1208 """Swaps self/other and returns __div__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001209 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001210 if other is NotImplemented:
1211 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001212 return other.__div__(self, context=context)
1213 __rtruediv__ = __rdiv__
1214
1215 def __divmod__(self, other, context=None):
1216 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001217 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001218 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001219 other = _convert_other(other)
1220 if other is NotImplemented:
1221 return other
1222
1223 if context is None:
1224 context = getcontext()
1225
1226 ans = self._check_nans(other, context)
1227 if ans:
1228 return (ans, ans)
1229
1230 sign = self._sign ^ other._sign
1231 if self._isinfinity():
1232 if other._isinfinity():
1233 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1234 return ans, ans
1235 else:
1236 return (Infsign[sign],
1237 context._raise_error(InvalidOperation, 'INF % x'))
1238
1239 if not other:
1240 if not self:
1241 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1242 return ans, ans
1243 else:
1244 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1245 context._raise_error(InvalidOperation, 'x % 0'))
1246
1247 quotient, remainder = self._divide(other, context)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001248 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001249 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001250
1251 def __rdivmod__(self, other, context=None):
1252 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001253 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001254 if other is NotImplemented:
1255 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001256 return other.__divmod__(self, context=context)
1257
1258 def __mod__(self, other, context=None):
1259 """
1260 self % other
1261 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001262 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001263 if other is NotImplemented:
1264 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001265
Facundo Batistacce8df22007-09-18 16:53:18 +00001266 if context is None:
1267 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001268
Facundo Batistacce8df22007-09-18 16:53:18 +00001269 ans = self._check_nans(other, context)
1270 if ans:
1271 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001272
Facundo Batistacce8df22007-09-18 16:53:18 +00001273 if self._isinfinity():
1274 return context._raise_error(InvalidOperation, 'INF % x')
1275 elif not other:
1276 if self:
1277 return context._raise_error(InvalidOperation, 'x % 0')
1278 else:
1279 return context._raise_error(DivisionUndefined, '0 % 0')
1280
1281 remainder = self._divide(other, context)[1]
Facundo Batistae64acfa2007-12-17 14:18:42 +00001282 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001283 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001284
1285 def __rmod__(self, other, context=None):
1286 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001287 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001288 if other is NotImplemented:
1289 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001290 return other.__mod__(self, context=context)
1291
1292 def remainder_near(self, other, context=None):
1293 """
1294 Remainder nearest to 0- abs(remainder-near) <= other/2
1295 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001296 if context is None:
1297 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001298
Facundo Batista353750c2007-09-13 18:13:15 +00001299 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001300
Facundo Batista353750c2007-09-13 18:13:15 +00001301 ans = self._check_nans(other, context)
1302 if ans:
1303 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001304
Facundo Batista353750c2007-09-13 18:13:15 +00001305 # self == +/-infinity -> InvalidOperation
1306 if self._isinfinity():
1307 return context._raise_error(InvalidOperation,
1308 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001309
Facundo Batista353750c2007-09-13 18:13:15 +00001310 # other == 0 -> either InvalidOperation or DivisionUndefined
1311 if not other:
1312 if self:
1313 return context._raise_error(InvalidOperation,
1314 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001315 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001316 return context._raise_error(DivisionUndefined,
1317 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001318
Facundo Batista353750c2007-09-13 18:13:15 +00001319 # other = +/-infinity -> remainder = self
1320 if other._isinfinity():
1321 ans = Decimal(self)
1322 return ans._fix(context)
1323
1324 # self = 0 -> remainder = self, with ideal exponent
1325 ideal_exponent = min(self._exp, other._exp)
1326 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001327 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001328 return ans._fix(context)
1329
1330 # catch most cases of large or small quotient
1331 expdiff = self.adjusted() - other.adjusted()
1332 if expdiff >= context.prec + 1:
1333 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001334 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001335 if expdiff <= -2:
1336 # expdiff <= -2 => abs(self/other) < 0.1
1337 ans = self._rescale(ideal_exponent, context.rounding)
1338 return ans._fix(context)
1339
1340 # adjust both arguments to have the same exponent, then divide
1341 op1 = _WorkRep(self)
1342 op2 = _WorkRep(other)
1343 if op1.exp >= op2.exp:
1344 op1.int *= 10**(op1.exp - op2.exp)
1345 else:
1346 op2.int *= 10**(op2.exp - op1.exp)
1347 q, r = divmod(op1.int, op2.int)
1348 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1349 # 10**ideal_exponent. Apply correction to ensure that
1350 # abs(remainder) <= abs(other)/2
1351 if 2*r + (q&1) > op2.int:
1352 r -= op2.int
1353 q += 1
1354
1355 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001356 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001357
1358 # result has same sign as self unless r is negative
1359 sign = self._sign
1360 if r < 0:
1361 sign = 1-sign
1362 r = -r
1363
Facundo Batista72bc54f2007-11-23 17:59:00 +00001364 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001365 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001366
1367 def __floordiv__(self, other, context=None):
1368 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001369 other = _convert_other(other)
1370 if other is NotImplemented:
1371 return other
1372
1373 if context is None:
1374 context = getcontext()
1375
1376 ans = self._check_nans(other, context)
1377 if ans:
1378 return ans
1379
1380 if self._isinfinity():
1381 if other._isinfinity():
1382 return context._raise_error(InvalidOperation, 'INF // INF')
1383 else:
1384 return Infsign[self._sign ^ other._sign]
1385
1386 if not other:
1387 if self:
1388 return context._raise_error(DivisionByZero, 'x // 0',
1389 self._sign ^ other._sign)
1390 else:
1391 return context._raise_error(DivisionUndefined, '0 // 0')
1392
1393 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001394
1395 def __rfloordiv__(self, other, context=None):
1396 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001397 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001398 if other is NotImplemented:
1399 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001400 return other.__floordiv__(self, context=context)
1401
1402 def __float__(self):
1403 """Float representation."""
1404 return float(str(self))
1405
1406 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001407 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001408 if self._is_special:
1409 if self._isnan():
1410 context = getcontext()
1411 return context._raise_error(InvalidContext)
1412 elif self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001413 raise OverflowError("Cannot convert infinity to long")
Facundo Batista353750c2007-09-13 18:13:15 +00001414 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001415 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001416 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001417 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001418 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001419
1420 def __long__(self):
1421 """Converts to a long.
1422
1423 Equivalent to long(int(self))
1424 """
1425 return long(self.__int__())
1426
Facundo Batista353750c2007-09-13 18:13:15 +00001427 def _fix_nan(self, context):
1428 """Decapitate the payload of a NaN to fit the context"""
1429 payload = self._int
1430
1431 # maximum length of payload is precision if _clamp=0,
1432 # precision-1 if _clamp=1.
1433 max_payload_len = context.prec - context._clamp
1434 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001435 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1436 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001437 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001438
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001439 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001440 """Round if it is necessary to keep self within prec precision.
1441
1442 Rounds and fixes the exponent. Does not raise on a sNaN.
1443
1444 Arguments:
1445 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001446 context - context used.
1447 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001448
Facundo Batista353750c2007-09-13 18:13:15 +00001449 if self._is_special:
1450 if self._isnan():
1451 # decapitate payload if necessary
1452 return self._fix_nan(context)
1453 else:
1454 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001455 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001456
Facundo Batista353750c2007-09-13 18:13:15 +00001457 # if self is zero then exponent should be between Etiny and
1458 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1459 Etiny = context.Etiny()
1460 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001461 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001462 exp_max = [context.Emax, Etop][context._clamp]
1463 new_exp = min(max(self._exp, Etiny), exp_max)
1464 if new_exp != self._exp:
1465 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001466 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001467 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001468 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001469
1470 # exp_min is the smallest allowable exponent of the result,
1471 # equal to max(self.adjusted()-context.prec+1, Etiny)
1472 exp_min = len(self._int) + self._exp - context.prec
1473 if exp_min > Etop:
1474 # overflow: exp_min > Etop iff self.adjusted() > Emax
1475 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001476 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001477 return context._raise_error(Overflow, 'above Emax', self._sign)
1478 self_is_subnormal = exp_min < Etiny
1479 if self_is_subnormal:
1480 context._raise_error(Subnormal)
1481 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001482
Facundo Batista353750c2007-09-13 18:13:15 +00001483 # round if self has too many digits
1484 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001485 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001486 digits = len(self._int) + self._exp - exp_min
1487 if digits < 0:
1488 self = _dec_from_triple(self._sign, '1', exp_min-1)
1489 digits = 0
1490 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1491 changed = this_function(digits)
1492 coeff = self._int[:digits] or '0'
1493 if changed == 1:
1494 coeff = str(int(coeff)+1)
1495 ans = _dec_from_triple(self._sign, coeff, exp_min)
1496
1497 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001498 context._raise_error(Inexact)
1499 if self_is_subnormal:
1500 context._raise_error(Underflow)
1501 if not ans:
1502 # raise Clamped on underflow to 0
1503 context._raise_error(Clamped)
1504 elif len(ans._int) == context.prec+1:
1505 # we get here only if rescaling rounds the
1506 # cofficient up to exactly 10**context.prec
1507 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001508 ans = _dec_from_triple(ans._sign,
1509 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001510 else:
1511 # Inexact and Rounded have already been raised
1512 ans = context._raise_error(Overflow, 'above Emax',
1513 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001514 return ans
1515
Facundo Batista353750c2007-09-13 18:13:15 +00001516 # fold down if _clamp == 1 and self has too few digits
1517 if context._clamp == 1 and self._exp > Etop:
1518 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001519 self_padded = self._int + '0'*(self._exp - Etop)
1520 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001521
Facundo Batista353750c2007-09-13 18:13:15 +00001522 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001523 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001524
1525 _pick_rounding_function = {}
1526
Facundo Batista353750c2007-09-13 18:13:15 +00001527 # for each of the rounding functions below:
1528 # self is a finite, nonzero Decimal
1529 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001530 #
1531 # each function returns either -1, 0, or 1, as follows:
1532 # 1 indicates that self should be rounded up (away from zero)
1533 # 0 indicates that self should be truncated, and that all the
1534 # digits to be truncated are zeros (so the value is unchanged)
1535 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001536
1537 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001538 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001539 if _all_zeros(self._int, prec):
1540 return 0
1541 else:
1542 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001543
Facundo Batista353750c2007-09-13 18:13:15 +00001544 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001545 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001546 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001547
Facundo Batista353750c2007-09-13 18:13:15 +00001548 def _round_half_up(self, prec):
1549 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001550 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001551 return 1
1552 elif _all_zeros(self._int, prec):
1553 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001554 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001555 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001556
1557 def _round_half_down(self, prec):
1558 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001559 if _exact_half(self._int, prec):
1560 return -1
1561 else:
1562 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001563
1564 def _round_half_even(self, prec):
1565 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001566 if _exact_half(self._int, prec) and \
1567 (prec == 0 or self._int[prec-1] in '02468'):
1568 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001569 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001570 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001571
1572 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001573 """Rounds up (not away from 0 if negative.)"""
1574 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001575 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001576 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001577 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001578
Facundo Batista353750c2007-09-13 18:13:15 +00001579 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001580 """Rounds down (not towards 0 if negative)"""
1581 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001582 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001583 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001584 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001585
Facundo Batista353750c2007-09-13 18:13:15 +00001586 def _round_05up(self, prec):
1587 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001588 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001589 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001590 else:
1591 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001592
Facundo Batista353750c2007-09-13 18:13:15 +00001593 def fma(self, other, third, context=None):
1594 """Fused multiply-add.
1595
1596 Returns self*other+third with no rounding of the intermediate
1597 product self*other.
1598
1599 self and other are multiplied together, with no rounding of
1600 the result. The third operand is then added to the result,
1601 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001602 """
Facundo Batista353750c2007-09-13 18:13:15 +00001603
1604 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001605
1606 # compute product; raise InvalidOperation if either operand is
1607 # a signaling NaN or if the product is zero times infinity.
1608 if self._is_special or other._is_special:
1609 if context is None:
1610 context = getcontext()
1611 if self._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001612 return context._raise_error(InvalidOperation, 'sNaN', self)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001613 if other._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001614 return context._raise_error(InvalidOperation, 'sNaN', other)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001615 if self._exp == 'n':
1616 product = self
1617 elif other._exp == 'n':
1618 product = other
1619 elif self._exp == 'F':
1620 if not other:
1621 return context._raise_error(InvalidOperation,
1622 'INF * 0 in fma')
1623 product = Infsign[self._sign ^ other._sign]
1624 elif other._exp == 'F':
1625 if not self:
1626 return context._raise_error(InvalidOperation,
1627 '0 * INF in fma')
1628 product = Infsign[self._sign ^ other._sign]
1629 else:
1630 product = _dec_from_triple(self._sign ^ other._sign,
1631 str(int(self._int) * int(other._int)),
1632 self._exp + other._exp)
1633
Facundo Batista353750c2007-09-13 18:13:15 +00001634 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001635 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001636
Facundo Batista353750c2007-09-13 18:13:15 +00001637 def _power_modulo(self, other, modulo, context=None):
1638 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001639
Facundo Batista353750c2007-09-13 18:13:15 +00001640 # if can't convert other and modulo to Decimal, raise
1641 # TypeError; there's no point returning NotImplemented (no
1642 # equivalent of __rpow__ for three argument pow)
1643 other = _convert_other(other, raiseit=True)
1644 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001645
Facundo Batista353750c2007-09-13 18:13:15 +00001646 if context is None:
1647 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001648
Facundo Batista353750c2007-09-13 18:13:15 +00001649 # deal with NaNs: if there are any sNaNs then first one wins,
1650 # (i.e. behaviour for NaNs is identical to that of fma)
1651 self_is_nan = self._isnan()
1652 other_is_nan = other._isnan()
1653 modulo_is_nan = modulo._isnan()
1654 if self_is_nan or other_is_nan or modulo_is_nan:
1655 if self_is_nan == 2:
1656 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001657 self)
Facundo Batista353750c2007-09-13 18:13:15 +00001658 if other_is_nan == 2:
1659 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001660 other)
Facundo Batista353750c2007-09-13 18:13:15 +00001661 if modulo_is_nan == 2:
1662 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001663 modulo)
Facundo Batista353750c2007-09-13 18:13:15 +00001664 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001665 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001666 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001667 return other._fix_nan(context)
1668 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001669
Facundo Batista353750c2007-09-13 18:13:15 +00001670 # check inputs: we apply same restrictions as Python's pow()
1671 if not (self._isinteger() and
1672 other._isinteger() and
1673 modulo._isinteger()):
1674 return context._raise_error(InvalidOperation,
1675 'pow() 3rd argument not allowed '
1676 'unless all arguments are integers')
1677 if other < 0:
1678 return context._raise_error(InvalidOperation,
1679 'pow() 2nd argument cannot be '
1680 'negative when 3rd argument specified')
1681 if not modulo:
1682 return context._raise_error(InvalidOperation,
1683 'pow() 3rd argument cannot be 0')
1684
1685 # additional restriction for decimal: the modulus must be less
1686 # than 10**prec in absolute value
1687 if modulo.adjusted() >= context.prec:
1688 return context._raise_error(InvalidOperation,
1689 'insufficient precision: pow() 3rd '
1690 'argument must not have more than '
1691 'precision digits')
1692
1693 # define 0**0 == NaN, for consistency with two-argument pow
1694 # (even though it hurts!)
1695 if not other and not self:
1696 return context._raise_error(InvalidOperation,
1697 'at least one of pow() 1st argument '
1698 'and 2nd argument must be nonzero ;'
1699 '0**0 is not defined')
1700
1701 # compute sign of result
1702 if other._iseven():
1703 sign = 0
1704 else:
1705 sign = self._sign
1706
1707 # convert modulo to a Python integer, and self and other to
1708 # Decimal integers (i.e. force their exponents to be >= 0)
1709 modulo = abs(int(modulo))
1710 base = _WorkRep(self.to_integral_value())
1711 exponent = _WorkRep(other.to_integral_value())
1712
1713 # compute result using integer pow()
1714 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1715 for i in xrange(exponent.exp):
1716 base = pow(base, 10, modulo)
1717 base = pow(base, exponent.int, modulo)
1718
Facundo Batista72bc54f2007-11-23 17:59:00 +00001719 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001720
1721 def _power_exact(self, other, p):
1722 """Attempt to compute self**other exactly.
1723
1724 Given Decimals self and other and an integer p, attempt to
1725 compute an exact result for the power self**other, with p
1726 digits of precision. Return None if self**other is not
1727 exactly representable in p digits.
1728
1729 Assumes that elimination of special cases has already been
1730 performed: self and other must both be nonspecial; self must
1731 be positive and not numerically equal to 1; other must be
1732 nonzero. For efficiency, other._exp should not be too large,
1733 so that 10**abs(other._exp) is a feasible calculation."""
1734
1735 # In the comments below, we write x for the value of self and
1736 # y for the value of other. Write x = xc*10**xe and y =
1737 # yc*10**ye.
1738
1739 # The main purpose of this method is to identify the *failure*
1740 # of x**y to be exactly representable with as little effort as
1741 # possible. So we look for cheap and easy tests that
1742 # eliminate the possibility of x**y being exact. Only if all
1743 # these tests are passed do we go on to actually compute x**y.
1744
1745 # Here's the main idea. First normalize both x and y. We
1746 # express y as a rational m/n, with m and n relatively prime
1747 # and n>0. Then for x**y to be exactly representable (at
1748 # *any* precision), xc must be the nth power of a positive
1749 # integer and xe must be divisible by n. If m is negative
1750 # then additionally xc must be a power of either 2 or 5, hence
1751 # a power of 2**n or 5**n.
1752 #
1753 # There's a limit to how small |y| can be: if y=m/n as above
1754 # then:
1755 #
1756 # (1) if xc != 1 then for the result to be representable we
1757 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1758 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1759 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1760 # representable.
1761 #
1762 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1763 # |y| < 1/|xe| then the result is not representable.
1764 #
1765 # Note that since x is not equal to 1, at least one of (1) and
1766 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1767 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1768 #
1769 # There's also a limit to how large y can be, at least if it's
1770 # positive: the normalized result will have coefficient xc**y,
1771 # so if it's representable then xc**y < 10**p, and y <
1772 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1773 # not exactly representable.
1774
1775 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1776 # so |y| < 1/xe and the result is not representable.
1777 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1778 # < 1/nbits(xc).
1779
1780 x = _WorkRep(self)
1781 xc, xe = x.int, x.exp
1782 while xc % 10 == 0:
1783 xc //= 10
1784 xe += 1
1785
1786 y = _WorkRep(other)
1787 yc, ye = y.int, y.exp
1788 while yc % 10 == 0:
1789 yc //= 10
1790 ye += 1
1791
1792 # case where xc == 1: result is 10**(xe*y), with xe*y
1793 # required to be an integer
1794 if xc == 1:
1795 if ye >= 0:
1796 exponent = xe*yc*10**ye
1797 else:
1798 exponent, remainder = divmod(xe*yc, 10**-ye)
1799 if remainder:
1800 return None
1801 if y.sign == 1:
1802 exponent = -exponent
1803 # if other is a nonnegative integer, use ideal exponent
1804 if other._isinteger() and other._sign == 0:
1805 ideal_exponent = self._exp*int(other)
1806 zeros = min(exponent-ideal_exponent, p-1)
1807 else:
1808 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001809 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001810
1811 # case where y is negative: xc must be either a power
1812 # of 2 or a power of 5.
1813 if y.sign == 1:
1814 last_digit = xc % 10
1815 if last_digit in (2,4,6,8):
1816 # quick test for power of 2
1817 if xc & -xc != xc:
1818 return None
1819 # now xc is a power of 2; e is its exponent
1820 e = _nbits(xc)-1
1821 # find e*y and xe*y; both must be integers
1822 if ye >= 0:
1823 y_as_int = yc*10**ye
1824 e = e*y_as_int
1825 xe = xe*y_as_int
1826 else:
1827 ten_pow = 10**-ye
1828 e, remainder = divmod(e*yc, ten_pow)
1829 if remainder:
1830 return None
1831 xe, remainder = divmod(xe*yc, ten_pow)
1832 if remainder:
1833 return None
1834
1835 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1836 return None
1837 xc = 5**e
1838
1839 elif last_digit == 5:
1840 # e >= log_5(xc) if xc is a power of 5; we have
1841 # equality all the way up to xc=5**2658
1842 e = _nbits(xc)*28//65
1843 xc, remainder = divmod(5**e, xc)
1844 if remainder:
1845 return None
1846 while xc % 5 == 0:
1847 xc //= 5
1848 e -= 1
1849 if ye >= 0:
1850 y_as_integer = yc*10**ye
1851 e = e*y_as_integer
1852 xe = xe*y_as_integer
1853 else:
1854 ten_pow = 10**-ye
1855 e, remainder = divmod(e*yc, ten_pow)
1856 if remainder:
1857 return None
1858 xe, remainder = divmod(xe*yc, ten_pow)
1859 if remainder:
1860 return None
1861 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1862 return None
1863 xc = 2**e
1864 else:
1865 return None
1866
1867 if xc >= 10**p:
1868 return None
1869 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00001870 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00001871
1872 # now y is positive; find m and n such that y = m/n
1873 if ye >= 0:
1874 m, n = yc*10**ye, 1
1875 else:
1876 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1877 return None
1878 xc_bits = _nbits(xc)
1879 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1880 return None
1881 m, n = yc, 10**(-ye)
1882 while m % 2 == n % 2 == 0:
1883 m //= 2
1884 n //= 2
1885 while m % 5 == n % 5 == 0:
1886 m //= 5
1887 n //= 5
1888
1889 # compute nth root of xc*10**xe
1890 if n > 1:
1891 # if 1 < xc < 2**n then xc isn't an nth power
1892 if xc != 1 and xc_bits <= n:
1893 return None
1894
1895 xe, rem = divmod(xe, n)
1896 if rem != 0:
1897 return None
1898
1899 # compute nth root of xc using Newton's method
1900 a = 1L << -(-_nbits(xc)//n) # initial estimate
1901 while True:
1902 q, r = divmod(xc, a**(n-1))
1903 if a <= q:
1904 break
1905 else:
1906 a = (a*(n-1) + q)//n
1907 if not (a == q and r == 0):
1908 return None
1909 xc = a
1910
1911 # now xc*10**xe is the nth root of the original xc*10**xe
1912 # compute mth power of xc*10**xe
1913
1914 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1915 # 10**p and the result is not representable.
1916 if xc > 1 and m > p*100//_log10_lb(xc):
1917 return None
1918 xc = xc**m
1919 xe *= m
1920 if xc > 10**p:
1921 return None
1922
1923 # by this point the result *is* exactly representable
1924 # adjust the exponent to get as close as possible to the ideal
1925 # exponent, if necessary
1926 str_xc = str(xc)
1927 if other._isinteger() and other._sign == 0:
1928 ideal_exponent = self._exp*int(other)
1929 zeros = min(xe-ideal_exponent, p-len(str_xc))
1930 else:
1931 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001932 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001933
1934 def __pow__(self, other, modulo=None, context=None):
1935 """Return self ** other [ % modulo].
1936
1937 With two arguments, compute self**other.
1938
1939 With three arguments, compute (self**other) % modulo. For the
1940 three argument form, the following restrictions on the
1941 arguments hold:
1942
1943 - all three arguments must be integral
1944 - other must be nonnegative
1945 - either self or other (or both) must be nonzero
1946 - modulo must be nonzero and must have at most p digits,
1947 where p is the context precision.
1948
1949 If any of these restrictions is violated the InvalidOperation
1950 flag is raised.
1951
1952 The result of pow(self, other, modulo) is identical to the
1953 result that would be obtained by computing (self**other) %
1954 modulo with unbounded precision, but is computed more
1955 efficiently. It is always exact.
1956 """
1957
1958 if modulo is not None:
1959 return self._power_modulo(other, modulo, context)
1960
1961 other = _convert_other(other)
1962 if other is NotImplemented:
1963 return other
1964
1965 if context is None:
1966 context = getcontext()
1967
1968 # either argument is a NaN => result is NaN
1969 ans = self._check_nans(other, context)
1970 if ans:
1971 return ans
1972
1973 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1974 if not other:
1975 if not self:
1976 return context._raise_error(InvalidOperation, '0 ** 0')
1977 else:
1978 return Dec_p1
1979
1980 # result has sign 1 iff self._sign is 1 and other is an odd integer
1981 result_sign = 0
1982 if self._sign == 1:
1983 if other._isinteger():
1984 if not other._iseven():
1985 result_sign = 1
1986 else:
1987 # -ve**noninteger = NaN
1988 # (-0)**noninteger = 0**noninteger
1989 if self:
1990 return context._raise_error(InvalidOperation,
1991 'x ** y with x negative and y not an integer')
1992 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00001993 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00001994
1995 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
1996 if not self:
1997 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001998 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001999 else:
2000 return Infsign[result_sign]
2001
2002 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002003 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002004 if other._sign == 0:
2005 return Infsign[result_sign]
2006 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002007 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002008
Facundo Batista353750c2007-09-13 18:13:15 +00002009 # 1**other = 1, but the choice of exponent and the flags
2010 # depend on the exponent of self, and on whether other is a
2011 # positive integer, a negative integer, or neither
2012 if self == Dec_p1:
2013 if other._isinteger():
2014 # exp = max(self._exp*max(int(other), 0),
2015 # 1-context.prec) but evaluating int(other) directly
2016 # is dangerous until we know other is small (other
2017 # could be 1e999999999)
2018 if other._sign == 1:
2019 multiplier = 0
2020 elif other > context.prec:
2021 multiplier = context.prec
2022 else:
2023 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002024
Facundo Batista353750c2007-09-13 18:13:15 +00002025 exp = self._exp * multiplier
2026 if exp < 1-context.prec:
2027 exp = 1-context.prec
2028 context._raise_error(Rounded)
2029 else:
2030 context._raise_error(Inexact)
2031 context._raise_error(Rounded)
2032 exp = 1-context.prec
2033
Facundo Batista72bc54f2007-11-23 17:59:00 +00002034 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002035
2036 # compute adjusted exponent of self
2037 self_adj = self.adjusted()
2038
2039 # self ** infinity is infinity if self > 1, 0 if self < 1
2040 # self ** -infinity is infinity if self < 1, 0 if self > 1
2041 if other._isinfinity():
2042 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002043 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002044 else:
2045 return Infsign[result_sign]
2046
2047 # from here on, the result always goes through the call
2048 # to _fix at the end of this function.
2049 ans = None
2050
2051 # crude test to catch cases of extreme overflow/underflow. If
2052 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2053 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2054 # self**other >= 10**(Emax+1), so overflow occurs. The test
2055 # for underflow is similar.
2056 bound = self._log10_exp_bound() + other.adjusted()
2057 if (self_adj >= 0) == (other._sign == 0):
2058 # self > 1 and other +ve, or self < 1 and other -ve
2059 # possibility of overflow
2060 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002061 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002062 else:
2063 # self > 1 and other -ve, or self < 1 and other +ve
2064 # possibility of underflow to 0
2065 Etiny = context.Etiny()
2066 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002067 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002068
2069 # try for an exact result with precision +1
2070 if ans is None:
2071 ans = self._power_exact(other, context.prec + 1)
2072 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002073 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002074
2075 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2076 if ans is None:
2077 p = context.prec
2078 x = _WorkRep(self)
2079 xc, xe = x.int, x.exp
2080 y = _WorkRep(other)
2081 yc, ye = y.int, y.exp
2082 if y.sign == 1:
2083 yc = -yc
2084
2085 # compute correctly rounded result: start with precision +3,
2086 # then increase precision until result is unambiguously roundable
2087 extra = 3
2088 while True:
2089 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2090 if coeff % (5*10**(len(str(coeff))-p-1)):
2091 break
2092 extra += 3
2093
Facundo Batista72bc54f2007-11-23 17:59:00 +00002094 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002095
2096 # the specification says that for non-integer other we need to
2097 # raise Inexact, even when the result is actually exact. In
2098 # the same way, we need to raise Underflow here if the result
2099 # is subnormal. (The call to _fix will take care of raising
2100 # Rounded and Subnormal, as usual.)
2101 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002102 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002103 # pad with zeros up to length context.prec+1 if necessary
2104 if len(ans._int) <= context.prec:
2105 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002106 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2107 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002108 if ans.adjusted() < context.Emin:
2109 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002110
Facundo Batista353750c2007-09-13 18:13:15 +00002111 # unlike exp, ln and log10, the power function respects the
2112 # rounding mode; no need to use ROUND_HALF_EVEN here
2113 ans = ans._fix(context)
2114 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002115
2116 def __rpow__(self, other, context=None):
2117 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002118 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002119 if other is NotImplemented:
2120 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002121 return other.__pow__(self, context=context)
2122
2123 def normalize(self, context=None):
2124 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002125
Facundo Batista353750c2007-09-13 18:13:15 +00002126 if context is None:
2127 context = getcontext()
2128
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002129 if self._is_special:
2130 ans = self._check_nans(context=context)
2131 if ans:
2132 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002133
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002134 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002135 if dup._isinfinity():
2136 return dup
2137
2138 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002139 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002140 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002141 end = len(dup._int)
2142 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002143 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002144 exp += 1
2145 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002146 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002147
Facundo Batistabd2fe832007-09-13 18:42:09 +00002148 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002149 """Quantize self so its exponent is the same as that of exp.
2150
2151 Similar to self._rescale(exp._exp) but with error checking.
2152 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002153 exp = _convert_other(exp, raiseit=True)
2154
Facundo Batista353750c2007-09-13 18:13:15 +00002155 if context is None:
2156 context = getcontext()
2157 if rounding is None:
2158 rounding = context.rounding
2159
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002160 if self._is_special or exp._is_special:
2161 ans = self._check_nans(exp, context)
2162 if ans:
2163 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002164
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002165 if exp._isinfinity() or self._isinfinity():
2166 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002167 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002168 return context._raise_error(InvalidOperation,
2169 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002170
Facundo Batistabd2fe832007-09-13 18:42:09 +00002171 # if we're not watching exponents, do a simple rescale
2172 if not watchexp:
2173 ans = self._rescale(exp._exp, rounding)
2174 # raise Inexact and Rounded where appropriate
2175 if ans._exp > self._exp:
2176 context._raise_error(Rounded)
2177 if ans != self:
2178 context._raise_error(Inexact)
2179 return ans
2180
Facundo Batista353750c2007-09-13 18:13:15 +00002181 # exp._exp should be between Etiny and Emax
2182 if not (context.Etiny() <= exp._exp <= context.Emax):
2183 return context._raise_error(InvalidOperation,
2184 'target exponent out of bounds in quantize')
2185
2186 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002187 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002188 return ans._fix(context)
2189
2190 self_adjusted = self.adjusted()
2191 if self_adjusted > context.Emax:
2192 return context._raise_error(InvalidOperation,
2193 'exponent of quantize result too large for current context')
2194 if self_adjusted - exp._exp + 1 > context.prec:
2195 return context._raise_error(InvalidOperation,
2196 'quantize result has too many digits for current context')
2197
2198 ans = self._rescale(exp._exp, rounding)
2199 if ans.adjusted() > context.Emax:
2200 return context._raise_error(InvalidOperation,
2201 'exponent of quantize result too large for current context')
2202 if len(ans._int) > context.prec:
2203 return context._raise_error(InvalidOperation,
2204 'quantize result has too many digits for current context')
2205
2206 # raise appropriate flags
2207 if ans._exp > self._exp:
2208 context._raise_error(Rounded)
2209 if ans != self:
2210 context._raise_error(Inexact)
2211 if ans and ans.adjusted() < context.Emin:
2212 context._raise_error(Subnormal)
2213
2214 # call to fix takes care of any necessary folddown
2215 ans = ans._fix(context)
2216 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002217
2218 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002219 """Return True if self and other have the same exponent; otherwise
2220 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002221
Facundo Batista1a191df2007-10-02 17:01:24 +00002222 If either operand is a special value, the following rules are used:
2223 * return True if both operands are infinities
2224 * return True if both operands are NaNs
2225 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002226 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002227 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002228 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002229 return (self.is_nan() and other.is_nan() or
2230 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002231 return self._exp == other._exp
2232
Facundo Batista353750c2007-09-13 18:13:15 +00002233 def _rescale(self, exp, rounding):
2234 """Rescale self so that the exponent is exp, either by padding with zeros
2235 or by truncating digits, using the given rounding mode.
2236
2237 Specials are returned without change. This operation is
2238 quiet: it raises no flags, and uses no information from the
2239 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002240
2241 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002242 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002243 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002244 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002245 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002246 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002247 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002248
Facundo Batista353750c2007-09-13 18:13:15 +00002249 if self._exp >= exp:
2250 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002251 return _dec_from_triple(self._sign,
2252 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002253
Facundo Batista353750c2007-09-13 18:13:15 +00002254 # too many digits; round and lose data. If self.adjusted() <
2255 # exp-1, replace self by 10**(exp-1) before rounding
2256 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002257 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002258 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002259 digits = 0
2260 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002261 changed = this_function(digits)
2262 coeff = self._int[:digits] or '0'
2263 if changed == 1:
2264 coeff = str(int(coeff)+1)
2265 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002266
Facundo Batista353750c2007-09-13 18:13:15 +00002267 def to_integral_exact(self, rounding=None, context=None):
2268 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002269
Facundo Batista353750c2007-09-13 18:13:15 +00002270 If no rounding mode is specified, take the rounding mode from
2271 the context. This method raises the Rounded and Inexact flags
2272 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002273
Facundo Batista353750c2007-09-13 18:13:15 +00002274 See also: to_integral_value, which does exactly the same as
2275 this method except that it doesn't raise Inexact or Rounded.
2276 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002277 if self._is_special:
2278 ans = self._check_nans(context=context)
2279 if ans:
2280 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002281 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002282 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002283 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002284 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002285 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002286 if context is None:
2287 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002288 if rounding is None:
2289 rounding = context.rounding
2290 context._raise_error(Rounded)
2291 ans = self._rescale(0, rounding)
2292 if ans != self:
2293 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002294 return ans
2295
Facundo Batista353750c2007-09-13 18:13:15 +00002296 def to_integral_value(self, rounding=None, context=None):
2297 """Rounds to the nearest integer, without raising inexact, rounded."""
2298 if context is None:
2299 context = getcontext()
2300 if rounding is None:
2301 rounding = context.rounding
2302 if self._is_special:
2303 ans = self._check_nans(context=context)
2304 if ans:
2305 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002306 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002307 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002308 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002309 else:
2310 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002311
Facundo Batista353750c2007-09-13 18:13:15 +00002312 # the method name changed, but we provide also the old one, for compatibility
2313 to_integral = to_integral_value
2314
2315 def sqrt(self, context=None):
2316 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002317 if self._is_special:
2318 ans = self._check_nans(context=context)
2319 if ans:
2320 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002321
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002322 if self._isinfinity() and self._sign == 0:
2323 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002324
2325 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002326 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002327 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002328 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002329
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002330 if context is None:
2331 context = getcontext()
2332
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002333 if self._sign == 1:
2334 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2335
Facundo Batista353750c2007-09-13 18:13:15 +00002336 # At this point self represents a positive number. Let p be
2337 # the desired precision and express self in the form c*100**e
2338 # with c a positive real number and e an integer, c and e
2339 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2340 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2341 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2342 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2343 # the closest integer to sqrt(c) with the even integer chosen
2344 # in the case of a tie.
2345 #
2346 # To ensure correct rounding in all cases, we use the
2347 # following trick: we compute the square root to an extra
2348 # place (precision p+1 instead of precision p), rounding down.
2349 # Then, if the result is inexact and its last digit is 0 or 5,
2350 # we increase the last digit to 1 or 6 respectively; if it's
2351 # exact we leave the last digit alone. Now the final round to
2352 # p places (or fewer in the case of underflow) will round
2353 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002354
Facundo Batista353750c2007-09-13 18:13:15 +00002355 # use an extra digit of precision
2356 prec = context.prec+1
2357
2358 # write argument in the form c*100**e where e = self._exp//2
2359 # is the 'ideal' exponent, to be used if the square root is
2360 # exactly representable. l is the number of 'digits' of c in
2361 # base 100, so that 100**(l-1) <= c < 100**l.
2362 op = _WorkRep(self)
2363 e = op.exp >> 1
2364 if op.exp & 1:
2365 c = op.int * 10
2366 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002367 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002368 c = op.int
2369 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002370
Facundo Batista353750c2007-09-13 18:13:15 +00002371 # rescale so that c has exactly prec base 100 'digits'
2372 shift = prec-l
2373 if shift >= 0:
2374 c *= 100**shift
2375 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002376 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002377 c, remainder = divmod(c, 100**-shift)
2378 exact = not remainder
2379 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002380
Facundo Batista353750c2007-09-13 18:13:15 +00002381 # find n = floor(sqrt(c)) using Newton's method
2382 n = 10**prec
2383 while True:
2384 q = c//n
2385 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002386 break
Facundo Batista353750c2007-09-13 18:13:15 +00002387 else:
2388 n = n + q >> 1
2389 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002390
Facundo Batista353750c2007-09-13 18:13:15 +00002391 if exact:
2392 # result is exact; rescale to use ideal exponent e
2393 if shift >= 0:
2394 # assert n % 10**shift == 0
2395 n //= 10**shift
2396 else:
2397 n *= 10**-shift
2398 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002399 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002400 # result is not exact; fix last digit as described above
2401 if n % 5 == 0:
2402 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002403
Facundo Batista72bc54f2007-11-23 17:59:00 +00002404 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002405
Facundo Batista353750c2007-09-13 18:13:15 +00002406 # round, and fit to current context
2407 context = context._shallow_copy()
2408 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002409 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002410 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002411
Facundo Batista353750c2007-09-13 18:13:15 +00002412 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002413
2414 def max(self, other, context=None):
2415 """Returns the larger value.
2416
Facundo Batista353750c2007-09-13 18:13:15 +00002417 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002418 NaN (and signals if one is sNaN). Also rounds.
2419 """
Facundo Batista353750c2007-09-13 18:13:15 +00002420 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002421
Facundo Batista6c398da2007-09-17 17:30:13 +00002422 if context is None:
2423 context = getcontext()
2424
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002425 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002426 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002427 # number is always returned
2428 sn = self._isnan()
2429 on = other._isnan()
2430 if sn or on:
2431 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002432 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002433 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002434 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002435 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002436
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002437 c = self.__cmp__(other)
2438 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002439 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002440 # then an ordering is applied:
2441 #
Facundo Batista59c58842007-04-10 12:58:45 +00002442 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002443 # positive sign and min returns the operand with the negative sign
2444 #
Facundo Batista59c58842007-04-10 12:58:45 +00002445 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002446 # the result. This is exactly the ordering used in compare_total.
2447 c = self.compare_total(other)
2448
2449 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002450 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002451 else:
2452 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002453
Facundo Batistae64acfa2007-12-17 14:18:42 +00002454 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002455
2456 def min(self, other, context=None):
2457 """Returns the smaller value.
2458
Facundo Batista59c58842007-04-10 12:58:45 +00002459 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002460 NaN (and signals if one is sNaN). Also rounds.
2461 """
Facundo Batista353750c2007-09-13 18:13:15 +00002462 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002463
Facundo Batista6c398da2007-09-17 17:30:13 +00002464 if context is None:
2465 context = getcontext()
2466
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002467 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002468 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002469 # number is always returned
2470 sn = self._isnan()
2471 on = other._isnan()
2472 if sn or on:
2473 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002474 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002475 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002476 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002477 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002478
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002479 c = self.__cmp__(other)
2480 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002481 c = self.compare_total(other)
2482
2483 if c == -1:
2484 ans = self
2485 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002486 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002487
Facundo Batistae64acfa2007-12-17 14:18:42 +00002488 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002489
2490 def _isinteger(self):
2491 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002492 if self._is_special:
2493 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002494 if self._exp >= 0:
2495 return True
2496 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002497 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002498
2499 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002500 """Returns True if self is even. Assumes self is an integer."""
2501 if not self or self._exp > 0:
2502 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002503 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002504
2505 def adjusted(self):
2506 """Return the adjusted exponent of self"""
2507 try:
2508 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002509 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002510 except TypeError:
2511 return 0
2512
Facundo Batista353750c2007-09-13 18:13:15 +00002513 def canonical(self, context=None):
2514 """Returns the same Decimal object.
2515
2516 As we do not have different encodings for the same number, the
2517 received object already is in its canonical form.
2518 """
2519 return self
2520
2521 def compare_signal(self, other, context=None):
2522 """Compares self to the other operand numerically.
2523
2524 It's pretty much like compare(), but all NaNs signal, with signaling
2525 NaNs taking precedence over quiet NaNs.
2526 """
2527 if context is None:
2528 context = getcontext()
2529
2530 self_is_nan = self._isnan()
2531 other_is_nan = other._isnan()
2532 if self_is_nan == 2:
2533 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002534 self)
Facundo Batista353750c2007-09-13 18:13:15 +00002535 if other_is_nan == 2:
2536 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002537 other)
Facundo Batista353750c2007-09-13 18:13:15 +00002538 if self_is_nan:
2539 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002540 self)
Facundo Batista353750c2007-09-13 18:13:15 +00002541 if other_is_nan:
2542 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002543 other)
Facundo Batista353750c2007-09-13 18:13:15 +00002544 return self.compare(other, context=context)
2545
2546 def compare_total(self, other):
2547 """Compares self to other using the abstract representations.
2548
2549 This is not like the standard compare, which use their numerical
2550 value. Note that a total ordering is defined for all possible abstract
2551 representations.
2552 """
2553 # if one is negative and the other is positive, it's easy
2554 if self._sign and not other._sign:
2555 return Dec_n1
2556 if not self._sign and other._sign:
2557 return Dec_p1
2558 sign = self._sign
2559
2560 # let's handle both NaN types
2561 self_nan = self._isnan()
2562 other_nan = other._isnan()
2563 if self_nan or other_nan:
2564 if self_nan == other_nan:
2565 if self._int < other._int:
2566 if sign:
2567 return Dec_p1
2568 else:
2569 return Dec_n1
2570 if self._int > other._int:
2571 if sign:
2572 return Dec_n1
2573 else:
2574 return Dec_p1
2575 return Dec_0
2576
2577 if sign:
2578 if self_nan == 1:
2579 return Dec_n1
2580 if other_nan == 1:
2581 return Dec_p1
2582 if self_nan == 2:
2583 return Dec_n1
2584 if other_nan == 2:
2585 return Dec_p1
2586 else:
2587 if self_nan == 1:
2588 return Dec_p1
2589 if other_nan == 1:
2590 return Dec_n1
2591 if self_nan == 2:
2592 return Dec_p1
2593 if other_nan == 2:
2594 return Dec_n1
2595
2596 if self < other:
2597 return Dec_n1
2598 if self > other:
2599 return Dec_p1
2600
2601 if self._exp < other._exp:
2602 if sign:
2603 return Dec_p1
2604 else:
2605 return Dec_n1
2606 if self._exp > other._exp:
2607 if sign:
2608 return Dec_n1
2609 else:
2610 return Dec_p1
2611 return Dec_0
2612
2613
2614 def compare_total_mag(self, other):
2615 """Compares self to other using abstract repr., ignoring sign.
2616
2617 Like compare_total, but with operand's sign ignored and assumed to be 0.
2618 """
2619 s = self.copy_abs()
2620 o = other.copy_abs()
2621 return s.compare_total(o)
2622
2623 def copy_abs(self):
2624 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002625 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002626
2627 def copy_negate(self):
2628 """Returns a copy with the sign inverted."""
2629 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002630 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002631 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002632 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002633
2634 def copy_sign(self, other):
2635 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002636 return _dec_from_triple(other._sign, self._int,
2637 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002638
2639 def exp(self, context=None):
2640 """Returns e ** self."""
2641
2642 if context is None:
2643 context = getcontext()
2644
2645 # exp(NaN) = NaN
2646 ans = self._check_nans(context=context)
2647 if ans:
2648 return ans
2649
2650 # exp(-Infinity) = 0
2651 if self._isinfinity() == -1:
2652 return Dec_0
2653
2654 # exp(0) = 1
2655 if not self:
2656 return Dec_p1
2657
2658 # exp(Infinity) = Infinity
2659 if self._isinfinity() == 1:
2660 return Decimal(self)
2661
2662 # the result is now guaranteed to be inexact (the true
2663 # mathematical result is transcendental). There's no need to
2664 # raise Rounded and Inexact here---they'll always be raised as
2665 # a result of the call to _fix.
2666 p = context.prec
2667 adj = self.adjusted()
2668
2669 # we only need to do any computation for quite a small range
2670 # of adjusted exponents---for example, -29 <= adj <= 10 for
2671 # the default context. For smaller exponent the result is
2672 # indistinguishable from 1 at the given precision, while for
2673 # larger exponent the result either overflows or underflows.
2674 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2675 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002676 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002677 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2678 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002679 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002680 elif self._sign == 0 and adj < -p:
2681 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002682 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002683 elif self._sign == 1 and adj < -p-1:
2684 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002685 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002686 # general case
2687 else:
2688 op = _WorkRep(self)
2689 c, e = op.int, op.exp
2690 if op.sign == 1:
2691 c = -c
2692
2693 # compute correctly rounded result: increase precision by
2694 # 3 digits at a time until we get an unambiguously
2695 # roundable result
2696 extra = 3
2697 while True:
2698 coeff, exp = _dexp(c, e, p+extra)
2699 if coeff % (5*10**(len(str(coeff))-p-1)):
2700 break
2701 extra += 3
2702
Facundo Batista72bc54f2007-11-23 17:59:00 +00002703 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002704
2705 # at this stage, ans should round correctly with *any*
2706 # rounding mode, not just with ROUND_HALF_EVEN
2707 context = context._shallow_copy()
2708 rounding = context._set_rounding(ROUND_HALF_EVEN)
2709 ans = ans._fix(context)
2710 context.rounding = rounding
2711
2712 return ans
2713
2714 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002715 """Return True if self is canonical; otherwise return False.
2716
2717 Currently, the encoding of a Decimal instance is always
2718 canonical, so this method returns True for any Decimal.
2719 """
2720 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002721
2722 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002723 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002724
Facundo Batista1a191df2007-10-02 17:01:24 +00002725 A Decimal instance is considered finite if it is neither
2726 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002727 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002728 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002729
2730 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002731 """Return True if self is infinite; otherwise return False."""
2732 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002733
2734 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002735 """Return True if self is a qNaN or sNaN; otherwise return False."""
2736 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002737
2738 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002739 """Return True if self is a normal number; otherwise return False."""
2740 if self._is_special or not self:
2741 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002742 if context is None:
2743 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002744 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002745
2746 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002747 """Return True if self is a quiet NaN; otherwise return False."""
2748 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002749
2750 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002751 """Return True if self is negative; otherwise return False."""
2752 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002753
2754 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002755 """Return True if self is a signaling NaN; otherwise return False."""
2756 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002757
2758 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002759 """Return True if self is subnormal; otherwise return False."""
2760 if self._is_special or not self:
2761 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002762 if context is None:
2763 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002764 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002765
2766 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002767 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002768 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002769
2770 def _ln_exp_bound(self):
2771 """Compute a lower bound for the adjusted exponent of self.ln().
2772 In other words, compute r such that self.ln() >= 10**r. Assumes
2773 that self is finite and positive and that self != 1.
2774 """
2775
2776 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2777 adj = self._exp + len(self._int) - 1
2778 if adj >= 1:
2779 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2780 return len(str(adj*23//10)) - 1
2781 if adj <= -2:
2782 # argument <= 0.1
2783 return len(str((-1-adj)*23//10)) - 1
2784 op = _WorkRep(self)
2785 c, e = op.int, op.exp
2786 if adj == 0:
2787 # 1 < self < 10
2788 num = str(c-10**-e)
2789 den = str(c)
2790 return len(num) - len(den) - (num < den)
2791 # adj == -1, 0.1 <= self < 1
2792 return e + len(str(10**-e - c)) - 1
2793
2794
2795 def ln(self, context=None):
2796 """Returns the natural (base e) logarithm of self."""
2797
2798 if context is None:
2799 context = getcontext()
2800
2801 # ln(NaN) = NaN
2802 ans = self._check_nans(context=context)
2803 if ans:
2804 return ans
2805
2806 # ln(0.0) == -Infinity
2807 if not self:
2808 return negInf
2809
2810 # ln(Infinity) = Infinity
2811 if self._isinfinity() == 1:
2812 return Inf
2813
2814 # ln(1.0) == 0.0
2815 if self == Dec_p1:
2816 return Dec_0
2817
2818 # ln(negative) raises InvalidOperation
2819 if self._sign == 1:
2820 return context._raise_error(InvalidOperation,
2821 'ln of a negative value')
2822
2823 # result is irrational, so necessarily inexact
2824 op = _WorkRep(self)
2825 c, e = op.int, op.exp
2826 p = context.prec
2827
2828 # correctly rounded result: repeatedly increase precision by 3
2829 # until we get an unambiguously roundable result
2830 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2831 while True:
2832 coeff = _dlog(c, e, places)
2833 # assert len(str(abs(coeff)))-p >= 1
2834 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2835 break
2836 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002837 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002838
2839 context = context._shallow_copy()
2840 rounding = context._set_rounding(ROUND_HALF_EVEN)
2841 ans = ans._fix(context)
2842 context.rounding = rounding
2843 return ans
2844
2845 def _log10_exp_bound(self):
2846 """Compute a lower bound for the adjusted exponent of self.log10().
2847 In other words, find r such that self.log10() >= 10**r.
2848 Assumes that self is finite and positive and that self != 1.
2849 """
2850
2851 # For x >= 10 or x < 0.1 we only need a bound on the integer
2852 # part of log10(self), and this comes directly from the
2853 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2854 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2855 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2856
2857 adj = self._exp + len(self._int) - 1
2858 if adj >= 1:
2859 # self >= 10
2860 return len(str(adj))-1
2861 if adj <= -2:
2862 # self < 0.1
2863 return len(str(-1-adj))-1
2864 op = _WorkRep(self)
2865 c, e = op.int, op.exp
2866 if adj == 0:
2867 # 1 < self < 10
2868 num = str(c-10**-e)
2869 den = str(231*c)
2870 return len(num) - len(den) - (num < den) + 2
2871 # adj == -1, 0.1 <= self < 1
2872 num = str(10**-e-c)
2873 return len(num) + e - (num < "231") - 1
2874
2875 def log10(self, context=None):
2876 """Returns the base 10 logarithm of self."""
2877
2878 if context is None:
2879 context = getcontext()
2880
2881 # log10(NaN) = NaN
2882 ans = self._check_nans(context=context)
2883 if ans:
2884 return ans
2885
2886 # log10(0.0) == -Infinity
2887 if not self:
2888 return negInf
2889
2890 # log10(Infinity) = Infinity
2891 if self._isinfinity() == 1:
2892 return Inf
2893
2894 # log10(negative or -Infinity) raises InvalidOperation
2895 if self._sign == 1:
2896 return context._raise_error(InvalidOperation,
2897 'log10 of a negative value')
2898
2899 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00002900 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00002901 # answer may need rounding
2902 ans = Decimal(self._exp + len(self._int) - 1)
2903 else:
2904 # result is irrational, so necessarily inexact
2905 op = _WorkRep(self)
2906 c, e = op.int, op.exp
2907 p = context.prec
2908
2909 # correctly rounded result: repeatedly increase precision
2910 # until result is unambiguously roundable
2911 places = p-self._log10_exp_bound()+2
2912 while True:
2913 coeff = _dlog10(c, e, places)
2914 # assert len(str(abs(coeff)))-p >= 1
2915 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2916 break
2917 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002918 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002919
2920 context = context._shallow_copy()
2921 rounding = context._set_rounding(ROUND_HALF_EVEN)
2922 ans = ans._fix(context)
2923 context.rounding = rounding
2924 return ans
2925
2926 def logb(self, context=None):
2927 """ Returns the exponent of the magnitude of self's MSD.
2928
2929 The result is the integer which is the exponent of the magnitude
2930 of the most significant digit of self (as though it were truncated
2931 to a single digit while maintaining the value of that digit and
2932 without limiting the resulting exponent).
2933 """
2934 # logb(NaN) = NaN
2935 ans = self._check_nans(context=context)
2936 if ans:
2937 return ans
2938
2939 if context is None:
2940 context = getcontext()
2941
2942 # logb(+/-Inf) = +Inf
2943 if self._isinfinity():
2944 return Inf
2945
2946 # logb(0) = -Inf, DivisionByZero
2947 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00002948 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00002949
2950 # otherwise, simply return the adjusted exponent of self, as a
2951 # Decimal. Note that no attempt is made to fit the result
2952 # into the current context.
2953 return Decimal(self.adjusted())
2954
2955 def _islogical(self):
2956 """Return True if self is a logical operand.
2957
2958 For being logical, it must be a finite numbers with a sign of 0,
2959 an exponent of 0, and a coefficient whose digits must all be
2960 either 0 or 1.
2961 """
2962 if self._sign != 0 or self._exp != 0:
2963 return False
2964 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002965 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00002966 return False
2967 return True
2968
2969 def _fill_logical(self, context, opa, opb):
2970 dif = context.prec - len(opa)
2971 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002972 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00002973 elif dif < 0:
2974 opa = opa[-context.prec:]
2975 dif = context.prec - len(opb)
2976 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002977 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00002978 elif dif < 0:
2979 opb = opb[-context.prec:]
2980 return opa, opb
2981
2982 def logical_and(self, other, context=None):
2983 """Applies an 'and' operation between self and other's digits."""
2984 if context is None:
2985 context = getcontext()
2986 if not self._islogical() or not other._islogical():
2987 return context._raise_error(InvalidOperation)
2988
2989 # fill to context.prec
2990 (opa, opb) = self._fill_logical(context, self._int, other._int)
2991
2992 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00002993 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
2994 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002995
2996 def logical_invert(self, context=None):
2997 """Invert all its digits."""
2998 if context is None:
2999 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003000 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3001 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003002
3003 def logical_or(self, other, context=None):
3004 """Applies an 'or' operation between self and other's digits."""
3005 if context is None:
3006 context = getcontext()
3007 if not self._islogical() or not other._islogical():
3008 return context._raise_error(InvalidOperation)
3009
3010 # fill to context.prec
3011 (opa, opb) = self._fill_logical(context, self._int, other._int)
3012
3013 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003014 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3015 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003016
3017 def logical_xor(self, other, context=None):
3018 """Applies an 'xor' 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 max_mag(self, other, context=None):
3032 """Compares the values numerically with their sign ignored."""
3033 other = _convert_other(other, raiseit=True)
3034
Facundo Batista6c398da2007-09-17 17:30:13 +00003035 if context is None:
3036 context = getcontext()
3037
Facundo Batista353750c2007-09-13 18:13:15 +00003038 if self._is_special or other._is_special:
3039 # If one operand is a quiet NaN and the other is number, then the
3040 # number is always returned
3041 sn = self._isnan()
3042 on = other._isnan()
3043 if sn or on:
3044 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003045 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003046 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003047 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003048 return self._check_nans(other, context)
3049
3050 c = self.copy_abs().__cmp__(other.copy_abs())
3051 if c == 0:
3052 c = self.compare_total(other)
3053
3054 if c == -1:
3055 ans = other
3056 else:
3057 ans = self
3058
Facundo Batistae64acfa2007-12-17 14:18:42 +00003059 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003060
3061 def min_mag(self, other, context=None):
3062 """Compares the values numerically with their sign ignored."""
3063 other = _convert_other(other, raiseit=True)
3064
Facundo Batista6c398da2007-09-17 17:30:13 +00003065 if context is None:
3066 context = getcontext()
3067
Facundo Batista353750c2007-09-13 18:13:15 +00003068 if self._is_special or other._is_special:
3069 # If one operand is a quiet NaN and the other is number, then the
3070 # number is always returned
3071 sn = self._isnan()
3072 on = other._isnan()
3073 if sn or on:
3074 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003075 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003076 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003077 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003078 return self._check_nans(other, context)
3079
3080 c = self.copy_abs().__cmp__(other.copy_abs())
3081 if c == 0:
3082 c = self.compare_total(other)
3083
3084 if c == -1:
3085 ans = self
3086 else:
3087 ans = other
3088
Facundo Batistae64acfa2007-12-17 14:18:42 +00003089 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003090
3091 def next_minus(self, context=None):
3092 """Returns the largest representable number smaller than itself."""
3093 if context is None:
3094 context = getcontext()
3095
3096 ans = self._check_nans(context=context)
3097 if ans:
3098 return ans
3099
3100 if self._isinfinity() == -1:
3101 return negInf
3102 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003103 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003104
3105 context = context.copy()
3106 context._set_rounding(ROUND_FLOOR)
3107 context._ignore_all_flags()
3108 new_self = self._fix(context)
3109 if new_self != self:
3110 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003111 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3112 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003113
3114 def next_plus(self, context=None):
3115 """Returns the smallest representable number larger than itself."""
3116 if context is None:
3117 context = getcontext()
3118
3119 ans = self._check_nans(context=context)
3120 if ans:
3121 return ans
3122
3123 if self._isinfinity() == 1:
3124 return Inf
3125 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003126 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003127
3128 context = context.copy()
3129 context._set_rounding(ROUND_CEILING)
3130 context._ignore_all_flags()
3131 new_self = self._fix(context)
3132 if new_self != self:
3133 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003134 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3135 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003136
3137 def next_toward(self, other, context=None):
3138 """Returns the number closest to self, in the direction towards other.
3139
3140 The result is the closest representable number to self
3141 (excluding self) that is in the direction towards other,
3142 unless both have the same value. If the two operands are
3143 numerically equal, then the result is a copy of self with the
3144 sign set to be the same as the sign of other.
3145 """
3146 other = _convert_other(other, raiseit=True)
3147
3148 if context is None:
3149 context = getcontext()
3150
3151 ans = self._check_nans(other, context)
3152 if ans:
3153 return ans
3154
3155 comparison = self.__cmp__(other)
3156 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003157 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003158
3159 if comparison == -1:
3160 ans = self.next_plus(context)
3161 else: # comparison == 1
3162 ans = self.next_minus(context)
3163
3164 # decide which flags to raise using value of ans
3165 if ans._isinfinity():
3166 context._raise_error(Overflow,
3167 'Infinite result from next_toward',
3168 ans._sign)
3169 context._raise_error(Rounded)
3170 context._raise_error(Inexact)
3171 elif ans.adjusted() < context.Emin:
3172 context._raise_error(Underflow)
3173 context._raise_error(Subnormal)
3174 context._raise_error(Rounded)
3175 context._raise_error(Inexact)
3176 # if precision == 1 then we don't raise Clamped for a
3177 # result 0E-Etiny.
3178 if not ans:
3179 context._raise_error(Clamped)
3180
3181 return ans
3182
3183 def number_class(self, context=None):
3184 """Returns an indication of the class of self.
3185
3186 The class is one of the following strings:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00003187 sNaN
3188 NaN
Facundo Batista353750c2007-09-13 18:13:15 +00003189 -Infinity
3190 -Normal
3191 -Subnormal
3192 -Zero
3193 +Zero
3194 +Subnormal
3195 +Normal
3196 +Infinity
3197 """
3198 if self.is_snan():
3199 return "sNaN"
3200 if self.is_qnan():
3201 return "NaN"
3202 inf = self._isinfinity()
3203 if inf == 1:
3204 return "+Infinity"
3205 if inf == -1:
3206 return "-Infinity"
3207 if self.is_zero():
3208 if self._sign:
3209 return "-Zero"
3210 else:
3211 return "+Zero"
3212 if context is None:
3213 context = getcontext()
3214 if self.is_subnormal(context=context):
3215 if self._sign:
3216 return "-Subnormal"
3217 else:
3218 return "+Subnormal"
3219 # just a normal, regular, boring number, :)
3220 if self._sign:
3221 return "-Normal"
3222 else:
3223 return "+Normal"
3224
3225 def radix(self):
3226 """Just returns 10, as this is Decimal, :)"""
3227 return Decimal(10)
3228
3229 def rotate(self, other, context=None):
3230 """Returns a rotated copy of self, value-of-other times."""
3231 if context is None:
3232 context = getcontext()
3233
3234 ans = self._check_nans(other, context)
3235 if ans:
3236 return ans
3237
3238 if other._exp != 0:
3239 return context._raise_error(InvalidOperation)
3240 if not (-context.prec <= int(other) <= context.prec):
3241 return context._raise_error(InvalidOperation)
3242
3243 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003244 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003245
3246 # get values, pad if necessary
3247 torot = int(other)
3248 rotdig = self._int
3249 topad = context.prec - len(rotdig)
3250 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003251 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003252
3253 # let's rotate!
3254 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003255 return _dec_from_triple(self._sign,
3256 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003257
3258 def scaleb (self, other, context=None):
3259 """Returns self operand after adding the second value to its exp."""
3260 if context is None:
3261 context = getcontext()
3262
3263 ans = self._check_nans(other, context)
3264 if ans:
3265 return ans
3266
3267 if other._exp != 0:
3268 return context._raise_error(InvalidOperation)
3269 liminf = -2 * (context.Emax + context.prec)
3270 limsup = 2 * (context.Emax + context.prec)
3271 if not (liminf <= int(other) <= limsup):
3272 return context._raise_error(InvalidOperation)
3273
3274 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003275 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003276
Facundo Batista72bc54f2007-11-23 17:59:00 +00003277 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003278 d = d._fix(context)
3279 return d
3280
3281 def shift(self, other, context=None):
3282 """Returns a shifted copy of self, value-of-other times."""
3283 if context is None:
3284 context = getcontext()
3285
3286 ans = self._check_nans(other, context)
3287 if ans:
3288 return ans
3289
3290 if other._exp != 0:
3291 return context._raise_error(InvalidOperation)
3292 if not (-context.prec <= int(other) <= context.prec):
3293 return context._raise_error(InvalidOperation)
3294
3295 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003296 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003297
3298 # get values, pad if necessary
3299 torot = int(other)
3300 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003301 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003302 rotdig = self._int
3303 topad = context.prec - len(rotdig)
3304 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003305 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003306
3307 # let's shift!
3308 if torot < 0:
3309 rotated = rotdig[:torot]
3310 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003311 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003312 rotated = rotated[-context.prec:]
3313
Facundo Batista72bc54f2007-11-23 17:59:00 +00003314 return _dec_from_triple(self._sign,
3315 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003316
Facundo Batista59c58842007-04-10 12:58:45 +00003317 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003318 def __reduce__(self):
3319 return (self.__class__, (str(self),))
3320
3321 def __copy__(self):
3322 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003323 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003324 return self.__class__(str(self))
3325
3326 def __deepcopy__(self, memo):
3327 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003328 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003329 return self.__class__(str(self))
3330
Facundo Batista72bc54f2007-11-23 17:59:00 +00003331def _dec_from_triple(sign, coefficient, exponent, special=False):
3332 """Create a decimal instance directly, without any validation,
3333 normalization (e.g. removal of leading zeros) or argument
3334 conversion.
3335
3336 This function is for *internal use only*.
3337 """
3338
3339 self = object.__new__(Decimal)
3340 self._sign = sign
3341 self._int = coefficient
3342 self._exp = exponent
3343 self._is_special = special
3344
3345 return self
3346
Facundo Batista59c58842007-04-10 12:58:45 +00003347##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003348
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003349
3350# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003351rounding_functions = [name for name in Decimal.__dict__.keys()
3352 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003353for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003354 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003355 globalname = name[1:].upper()
3356 val = globals()[globalname]
3357 Decimal._pick_rounding_function[val] = name
3358
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003359del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003360
Nick Coghlanced12182006-09-02 03:54:17 +00003361class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003362 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003363
Nick Coghlanced12182006-09-02 03:54:17 +00003364 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003365 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003366 """
3367 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003368 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003369 def __enter__(self):
3370 self.saved_context = getcontext()
3371 setcontext(self.new_context)
3372 return self.new_context
3373 def __exit__(self, t, v, tb):
3374 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003375
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003376class Context(object):
3377 """Contains the context for a Decimal instance.
3378
3379 Contains:
3380 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003381 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003382 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003383 raised when it is caused. Otherwise, a value is
3384 substituted in.
3385 flags - When an exception is caused, flags[exception] is incremented.
3386 (Whether or not the trap_enabler is set)
3387 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003388 Emin - Minimum exponent
3389 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003390 capitals - If 1, 1*10^1 is printed as 1E+1.
3391 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003392 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003393 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003394
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003395 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003396 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003397 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003398 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003399 _ignored_flags=None):
3400 if flags is None:
3401 flags = []
3402 if _ignored_flags is None:
3403 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003404 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003405 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003406 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003407 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003408 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003409 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003410 for name, val in locals().items():
3411 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003412 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003413 else:
3414 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003415 del self.self
3416
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003417 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003418 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003419 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003420 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3421 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3422 % vars(self))
3423 names = [f.__name__ for f, v in self.flags.items() if v]
3424 s.append('flags=[' + ', '.join(names) + ']')
3425 names = [t.__name__ for t, v in self.traps.items() if v]
3426 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003427 return ', '.join(s) + ')'
3428
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003429 def clear_flags(self):
3430 """Reset all flags to zero"""
3431 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003432 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003433
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003434 def _shallow_copy(self):
3435 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003436 nc = Context(self.prec, self.rounding, self.traps,
3437 self.flags, self.Emin, self.Emax,
3438 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003439 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003440
3441 def copy(self):
3442 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003443 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003444 self.flags.copy(), self.Emin, self.Emax,
3445 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003446 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003447 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003448
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003449 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003450 """Handles an error
3451
3452 If the flag is in _ignored_flags, returns the default response.
3453 Otherwise, it increments the flag, then, if the corresponding
3454 trap_enabler is set, it reaises the exception. Otherwise, it returns
3455 the default value after incrementing the flag.
3456 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003457 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003458 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003459 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003460 return error().handle(self, *args)
3461
3462 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003463 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003464 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003465 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003466
3467 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003468 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003469 raise error, explanation
3470
3471 def _ignore_all_flags(self):
3472 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003473 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003474
3475 def _ignore_flags(self, *flags):
3476 """Ignore the flags, if they are raised"""
3477 # Do not mutate-- This way, copies of a context leave the original
3478 # alone.
3479 self._ignored_flags = (self._ignored_flags + list(flags))
3480 return list(flags)
3481
3482 def _regard_flags(self, *flags):
3483 """Stop ignoring the flags, if they are raised"""
3484 if flags and isinstance(flags[0], (tuple,list)):
3485 flags = flags[0]
3486 for flag in flags:
3487 self._ignored_flags.remove(flag)
3488
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003489 def __hash__(self):
3490 """A Context cannot be hashed."""
3491 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003492 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003493
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003494 def Etiny(self):
3495 """Returns Etiny (= Emin - prec + 1)"""
3496 return int(self.Emin - self.prec + 1)
3497
3498 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003499 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003500 return int(self.Emax - self.prec + 1)
3501
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003502 def _set_rounding(self, type):
3503 """Sets the rounding type.
3504
3505 Sets the rounding type, and returns the current (previous)
3506 rounding type. Often used like:
3507
3508 context = context.copy()
3509 # so you don't change the calling context
3510 # if an error occurs in the middle.
3511 rounding = context._set_rounding(ROUND_UP)
3512 val = self.__sub__(other, context=context)
3513 context._set_rounding(rounding)
3514
3515 This will make it round up for that operation.
3516 """
3517 rounding = self.rounding
3518 self.rounding= type
3519 return rounding
3520
Raymond Hettingerfed52962004-07-14 15:41:57 +00003521 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003522 """Creates a new Decimal instance but using self as context."""
3523 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003524 if d._isnan() and len(d._int) > self.prec - self._clamp:
3525 return self._raise_error(ConversionSyntax,
3526 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003527 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003528
Facundo Batista59c58842007-04-10 12:58:45 +00003529 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003530 def abs(self, a):
3531 """Returns the absolute value of the operand.
3532
3533 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003534 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003535 the plus operation on the operand.
3536
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003537 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003538 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003539 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003540 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003541 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003542 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003543 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003544 Decimal("101.5")
3545 """
3546 return a.__abs__(context=self)
3547
3548 def add(self, a, b):
3549 """Return the sum of the two operands.
3550
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003551 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003552 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003553 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003554 Decimal("1.02E+4")
3555 """
3556 return a.__add__(b, context=self)
3557
3558 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003559 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003560
Facundo Batista353750c2007-09-13 18:13:15 +00003561 def canonical(self, a):
3562 """Returns the same Decimal object.
3563
3564 As we do not have different encodings for the same number, the
3565 received object already is in its canonical form.
3566
3567 >>> ExtendedContext.canonical(Decimal('2.50'))
3568 Decimal("2.50")
3569 """
3570 return a.canonical(context=self)
3571
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003572 def compare(self, a, b):
3573 """Compares values numerically.
3574
3575 If the signs of the operands differ, a value representing each operand
3576 ('-1' if the operand is less than zero, '0' if the operand is zero or
3577 negative zero, or '1' if the operand is greater than zero) is used in
3578 place of that operand for the comparison instead of the actual
3579 operand.
3580
3581 The comparison is then effected by subtracting the second operand from
3582 the first and then returning a value according to the result of the
3583 subtraction: '-1' if the result is less than zero, '0' if the result is
3584 zero or negative zero, or '1' if the result is greater than zero.
3585
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003586 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003587 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003588 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003589 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003590 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003591 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003592 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003593 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003594 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003595 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003596 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003597 Decimal("-1")
3598 """
3599 return a.compare(b, context=self)
3600
Facundo Batista353750c2007-09-13 18:13:15 +00003601 def compare_signal(self, a, b):
3602 """Compares the values of the two operands numerically.
3603
3604 It's pretty much like compare(), but all NaNs signal, with signaling
3605 NaNs taking precedence over quiet NaNs.
3606
3607 >>> c = ExtendedContext
3608 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3609 Decimal("-1")
3610 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3611 Decimal("0")
3612 >>> c.flags[InvalidOperation] = 0
3613 >>> print c.flags[InvalidOperation]
3614 0
3615 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3616 Decimal("NaN")
3617 >>> print c.flags[InvalidOperation]
3618 1
3619 >>> c.flags[InvalidOperation] = 0
3620 >>> print c.flags[InvalidOperation]
3621 0
3622 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3623 Decimal("NaN")
3624 >>> print c.flags[InvalidOperation]
3625 1
3626 """
3627 return a.compare_signal(b, context=self)
3628
3629 def compare_total(self, a, b):
3630 """Compares two operands using their abstract representation.
3631
3632 This is not like the standard compare, which use their numerical
3633 value. Note that a total ordering is defined for all possible abstract
3634 representations.
3635
3636 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3637 Decimal("-1")
3638 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3639 Decimal("-1")
3640 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3641 Decimal("-1")
3642 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3643 Decimal("0")
3644 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3645 Decimal("1")
3646 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3647 Decimal("-1")
3648 """
3649 return a.compare_total(b)
3650
3651 def compare_total_mag(self, a, b):
3652 """Compares two operands using their abstract representation ignoring sign.
3653
3654 Like compare_total, but with operand's sign ignored and assumed to be 0.
3655 """
3656 return a.compare_total_mag(b)
3657
3658 def copy_abs(self, a):
3659 """Returns a copy of the operand with the sign set to 0.
3660
3661 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3662 Decimal("2.1")
3663 >>> ExtendedContext.copy_abs(Decimal('-100'))
3664 Decimal("100")
3665 """
3666 return a.copy_abs()
3667
3668 def copy_decimal(self, a):
3669 """Returns a copy of the decimal objet.
3670
3671 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3672 Decimal("2.1")
3673 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3674 Decimal("-1.00")
3675 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003676 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003677
3678 def copy_negate(self, a):
3679 """Returns a copy of the operand with the sign inverted.
3680
3681 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3682 Decimal("-101.5")
3683 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3684 Decimal("101.5")
3685 """
3686 return a.copy_negate()
3687
3688 def copy_sign(self, a, b):
3689 """Copies the second operand's sign to the first one.
3690
3691 In detail, it returns a copy of the first operand with the sign
3692 equal to the sign of the second operand.
3693
3694 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3695 Decimal("1.50")
3696 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3697 Decimal("1.50")
3698 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3699 Decimal("-1.50")
3700 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3701 Decimal("-1.50")
3702 """
3703 return a.copy_sign(b)
3704
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003705 def divide(self, a, b):
3706 """Decimal division in a specified context.
3707
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003708 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003709 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003710 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003711 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003712 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003713 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003714 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003715 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003716 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003717 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003718 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003719 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003720 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003721 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003722 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003723 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003724 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003725 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003726 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003727 Decimal("1.20E+6")
3728 """
3729 return a.__div__(b, context=self)
3730
3731 def divide_int(self, a, b):
3732 """Divides two numbers and returns the integer part of the result.
3733
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003734 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003735 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003736 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003737 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003738 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003739 Decimal("3")
3740 """
3741 return a.__floordiv__(b, context=self)
3742
3743 def divmod(self, a, b):
3744 return a.__divmod__(b, context=self)
3745
Facundo Batista353750c2007-09-13 18:13:15 +00003746 def exp(self, a):
3747 """Returns e ** a.
3748
3749 >>> c = ExtendedContext.copy()
3750 >>> c.Emin = -999
3751 >>> c.Emax = 999
3752 >>> c.exp(Decimal('-Infinity'))
3753 Decimal("0")
3754 >>> c.exp(Decimal('-1'))
3755 Decimal("0.367879441")
3756 >>> c.exp(Decimal('0'))
3757 Decimal("1")
3758 >>> c.exp(Decimal('1'))
3759 Decimal("2.71828183")
3760 >>> c.exp(Decimal('0.693147181'))
3761 Decimal("2.00000000")
3762 >>> c.exp(Decimal('+Infinity'))
3763 Decimal("Infinity")
3764 """
3765 return a.exp(context=self)
3766
3767 def fma(self, a, b, c):
3768 """Returns a multiplied by b, plus c.
3769
3770 The first two operands are multiplied together, using multiply,
3771 the third operand is then added to the result of that
3772 multiplication, using add, all with only one final rounding.
3773
3774 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3775 Decimal("22")
3776 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3777 Decimal("-8")
3778 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3779 Decimal("1.38435736E+12")
3780 """
3781 return a.fma(b, c, context=self)
3782
3783 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003784 """Return True if the operand is canonical; otherwise return False.
3785
3786 Currently, the encoding of a Decimal instance is always
3787 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00003788
3789 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003790 True
Facundo Batista353750c2007-09-13 18:13:15 +00003791 """
Facundo Batista1a191df2007-10-02 17:01:24 +00003792 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00003793
3794 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003795 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003796
Facundo Batista1a191df2007-10-02 17:01:24 +00003797 A Decimal instance is considered finite if it is neither
3798 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00003799
3800 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003801 True
Facundo Batista353750c2007-09-13 18:13:15 +00003802 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003803 True
Facundo Batista353750c2007-09-13 18:13:15 +00003804 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003805 True
Facundo Batista353750c2007-09-13 18:13:15 +00003806 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003807 False
Facundo Batista353750c2007-09-13 18:13:15 +00003808 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003809 False
Facundo Batista353750c2007-09-13 18:13:15 +00003810 """
3811 return a.is_finite()
3812
3813 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003814 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003815
3816 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003817 False
Facundo Batista353750c2007-09-13 18:13:15 +00003818 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003819 True
Facundo Batista353750c2007-09-13 18:13:15 +00003820 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003821 False
Facundo Batista353750c2007-09-13 18:13:15 +00003822 """
3823 return a.is_infinite()
3824
3825 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003826 """Return True if the operand is a qNaN or sNaN;
3827 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003828
3829 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003830 False
Facundo Batista353750c2007-09-13 18:13:15 +00003831 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003832 True
Facundo Batista353750c2007-09-13 18:13:15 +00003833 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003834 True
Facundo Batista353750c2007-09-13 18:13:15 +00003835 """
3836 return a.is_nan()
3837
3838 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003839 """Return True if the operand is a normal number;
3840 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003841
3842 >>> c = ExtendedContext.copy()
3843 >>> c.Emin = -999
3844 >>> c.Emax = 999
3845 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003846 True
Facundo Batista353750c2007-09-13 18:13:15 +00003847 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003848 False
Facundo Batista353750c2007-09-13 18:13:15 +00003849 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003850 False
Facundo Batista353750c2007-09-13 18:13:15 +00003851 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003852 False
Facundo Batista353750c2007-09-13 18:13:15 +00003853 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003854 False
Facundo Batista353750c2007-09-13 18:13:15 +00003855 """
3856 return a.is_normal(context=self)
3857
3858 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003859 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003860
3861 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003862 False
Facundo Batista353750c2007-09-13 18:13:15 +00003863 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003864 True
Facundo Batista353750c2007-09-13 18:13:15 +00003865 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003866 False
Facundo Batista353750c2007-09-13 18:13:15 +00003867 """
3868 return a.is_qnan()
3869
3870 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003871 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003872
3873 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003874 False
Facundo Batista353750c2007-09-13 18:13:15 +00003875 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003876 True
Facundo Batista353750c2007-09-13 18:13:15 +00003877 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003878 True
Facundo Batista353750c2007-09-13 18:13:15 +00003879 """
3880 return a.is_signed()
3881
3882 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003883 """Return True if the operand is a signaling NaN;
3884 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003885
3886 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003887 False
Facundo Batista353750c2007-09-13 18:13:15 +00003888 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003889 False
Facundo Batista353750c2007-09-13 18:13:15 +00003890 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003891 True
Facundo Batista353750c2007-09-13 18:13:15 +00003892 """
3893 return a.is_snan()
3894
3895 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003896 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003897
3898 >>> c = ExtendedContext.copy()
3899 >>> c.Emin = -999
3900 >>> c.Emax = 999
3901 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003902 False
Facundo Batista353750c2007-09-13 18:13:15 +00003903 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003904 True
Facundo Batista353750c2007-09-13 18:13:15 +00003905 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003906 False
Facundo Batista353750c2007-09-13 18:13:15 +00003907 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003908 False
Facundo Batista353750c2007-09-13 18:13:15 +00003909 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003910 False
Facundo Batista353750c2007-09-13 18:13:15 +00003911 """
3912 return a.is_subnormal(context=self)
3913
3914 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003915 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003916
3917 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003918 True
Facundo Batista353750c2007-09-13 18:13:15 +00003919 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003920 False
Facundo Batista353750c2007-09-13 18:13:15 +00003921 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003922 True
Facundo Batista353750c2007-09-13 18:13:15 +00003923 """
3924 return a.is_zero()
3925
3926 def ln(self, a):
3927 """Returns the natural (base e) logarithm of the operand.
3928
3929 >>> c = ExtendedContext.copy()
3930 >>> c.Emin = -999
3931 >>> c.Emax = 999
3932 >>> c.ln(Decimal('0'))
3933 Decimal("-Infinity")
3934 >>> c.ln(Decimal('1.000'))
3935 Decimal("0")
3936 >>> c.ln(Decimal('2.71828183'))
3937 Decimal("1.00000000")
3938 >>> c.ln(Decimal('10'))
3939 Decimal("2.30258509")
3940 >>> c.ln(Decimal('+Infinity'))
3941 Decimal("Infinity")
3942 """
3943 return a.ln(context=self)
3944
3945 def log10(self, a):
3946 """Returns the base 10 logarithm of the operand.
3947
3948 >>> c = ExtendedContext.copy()
3949 >>> c.Emin = -999
3950 >>> c.Emax = 999
3951 >>> c.log10(Decimal('0'))
3952 Decimal("-Infinity")
3953 >>> c.log10(Decimal('0.001'))
3954 Decimal("-3")
3955 >>> c.log10(Decimal('1.000'))
3956 Decimal("0")
3957 >>> c.log10(Decimal('2'))
3958 Decimal("0.301029996")
3959 >>> c.log10(Decimal('10'))
3960 Decimal("1")
3961 >>> c.log10(Decimal('70'))
3962 Decimal("1.84509804")
3963 >>> c.log10(Decimal('+Infinity'))
3964 Decimal("Infinity")
3965 """
3966 return a.log10(context=self)
3967
3968 def logb(self, a):
3969 """ Returns the exponent of the magnitude of the operand's MSD.
3970
3971 The result is the integer which is the exponent of the magnitude
3972 of the most significant digit of the operand (as though the
3973 operand were truncated to a single digit while maintaining the
3974 value of that digit and without limiting the resulting exponent).
3975
3976 >>> ExtendedContext.logb(Decimal('250'))
3977 Decimal("2")
3978 >>> ExtendedContext.logb(Decimal('2.50'))
3979 Decimal("0")
3980 >>> ExtendedContext.logb(Decimal('0.03'))
3981 Decimal("-2")
3982 >>> ExtendedContext.logb(Decimal('0'))
3983 Decimal("-Infinity")
3984 """
3985 return a.logb(context=self)
3986
3987 def logical_and(self, a, b):
3988 """Applies the logical operation 'and' between each operand's digits.
3989
3990 The operands must be both logical numbers.
3991
3992 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
3993 Decimal("0")
3994 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
3995 Decimal("0")
3996 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
3997 Decimal("0")
3998 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
3999 Decimal("1")
4000 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4001 Decimal("1000")
4002 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4003 Decimal("10")
4004 """
4005 return a.logical_and(b, context=self)
4006
4007 def logical_invert(self, a):
4008 """Invert all the digits in the operand.
4009
4010 The operand must be a logical number.
4011
4012 >>> ExtendedContext.logical_invert(Decimal('0'))
4013 Decimal("111111111")
4014 >>> ExtendedContext.logical_invert(Decimal('1'))
4015 Decimal("111111110")
4016 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4017 Decimal("0")
4018 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4019 Decimal("10101010")
4020 """
4021 return a.logical_invert(context=self)
4022
4023 def logical_or(self, a, b):
4024 """Applies the logical operation 'or' between each operand's digits.
4025
4026 The operands must be both logical numbers.
4027
4028 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4029 Decimal("0")
4030 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4031 Decimal("1")
4032 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4033 Decimal("1")
4034 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4035 Decimal("1")
4036 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4037 Decimal("1110")
4038 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4039 Decimal("1110")
4040 """
4041 return a.logical_or(b, context=self)
4042
4043 def logical_xor(self, a, b):
4044 """Applies the logical operation 'xor' between each operand's digits.
4045
4046 The operands must be both logical numbers.
4047
4048 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4049 Decimal("0")
4050 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4051 Decimal("1")
4052 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4053 Decimal("1")
4054 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4055 Decimal("0")
4056 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4057 Decimal("110")
4058 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4059 Decimal("1101")
4060 """
4061 return a.logical_xor(b, context=self)
4062
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004063 def max(self, a,b):
4064 """max compares two values numerically and returns the maximum.
4065
4066 If either operand is a NaN then the general rules apply.
4067 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004068 operation. If they are numerically equal then the left-hand operand
4069 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004070 infinity) of the two operands is chosen as the result.
4071
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004072 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004073 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004074 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004075 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004076 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004077 Decimal("1")
4078 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4079 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004080 """
4081 return a.max(b, context=self)
4082
Facundo Batista353750c2007-09-13 18:13:15 +00004083 def max_mag(self, a, b):
4084 """Compares the values numerically with their sign ignored."""
4085 return a.max_mag(b, context=self)
4086
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004087 def min(self, a,b):
4088 """min compares two values numerically and returns the minimum.
4089
4090 If either operand is a NaN then the general rules apply.
4091 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004092 operation. If they are numerically equal then the left-hand operand
4093 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004094 infinity) of the two operands is chosen as the result.
4095
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004096 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004097 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004098 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004099 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004100 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004101 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004102 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4103 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004104 """
4105 return a.min(b, context=self)
4106
Facundo Batista353750c2007-09-13 18:13:15 +00004107 def min_mag(self, a, b):
4108 """Compares the values numerically with their sign ignored."""
4109 return a.min_mag(b, context=self)
4110
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004111 def minus(self, a):
4112 """Minus corresponds to unary prefix minus in Python.
4113
4114 The operation is evaluated using the same rules as subtract; the
4115 operation minus(a) is calculated as subtract('0', a) where the '0'
4116 has the same exponent as the operand.
4117
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004118 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004119 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004120 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004121 Decimal("1.3")
4122 """
4123 return a.__neg__(context=self)
4124
4125 def multiply(self, a, b):
4126 """multiply multiplies two operands.
4127
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004128 If either operand is a special value then the general rules apply.
4129 Otherwise, the operands are multiplied together ('long multiplication'),
4130 resulting in a number which may be as long as the sum of the lengths
4131 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004132
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004133 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004134 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004135 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004136 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004137 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004138 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004139 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004140 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004141 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004142 Decimal("4.28135971E+11")
4143 """
4144 return a.__mul__(b, context=self)
4145
Facundo Batista353750c2007-09-13 18:13:15 +00004146 def next_minus(self, a):
4147 """Returns the largest representable number smaller than a.
4148
4149 >>> c = ExtendedContext.copy()
4150 >>> c.Emin = -999
4151 >>> c.Emax = 999
4152 >>> ExtendedContext.next_minus(Decimal('1'))
4153 Decimal("0.999999999")
4154 >>> c.next_minus(Decimal('1E-1007'))
4155 Decimal("0E-1007")
4156 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4157 Decimal("-1.00000004")
4158 >>> c.next_minus(Decimal('Infinity'))
4159 Decimal("9.99999999E+999")
4160 """
4161 return a.next_minus(context=self)
4162
4163 def next_plus(self, a):
4164 """Returns the smallest representable number larger than a.
4165
4166 >>> c = ExtendedContext.copy()
4167 >>> c.Emin = -999
4168 >>> c.Emax = 999
4169 >>> ExtendedContext.next_plus(Decimal('1'))
4170 Decimal("1.00000001")
4171 >>> c.next_plus(Decimal('-1E-1007'))
4172 Decimal("-0E-1007")
4173 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4174 Decimal("-1.00000002")
4175 >>> c.next_plus(Decimal('-Infinity'))
4176 Decimal("-9.99999999E+999")
4177 """
4178 return a.next_plus(context=self)
4179
4180 def next_toward(self, a, b):
4181 """Returns the number closest to a, in direction towards b.
4182
4183 The result is the closest representable number from the first
4184 operand (but not the first operand) that is in the direction
4185 towards the second operand, unless the operands have the same
4186 value.
4187
4188 >>> c = ExtendedContext.copy()
4189 >>> c.Emin = -999
4190 >>> c.Emax = 999
4191 >>> c.next_toward(Decimal('1'), Decimal('2'))
4192 Decimal("1.00000001")
4193 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4194 Decimal("-0E-1007")
4195 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4196 Decimal("-1.00000002")
4197 >>> c.next_toward(Decimal('1'), Decimal('0'))
4198 Decimal("0.999999999")
4199 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4200 Decimal("0E-1007")
4201 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4202 Decimal("-1.00000004")
4203 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4204 Decimal("-0.00")
4205 """
4206 return a.next_toward(b, context=self)
4207
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004208 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004209 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004210
4211 Essentially a plus operation with all trailing zeros removed from the
4212 result.
4213
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004214 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004215 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004216 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004217 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004218 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004219 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004220 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004221 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004222 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004223 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004224 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004225 Decimal("0")
4226 """
4227 return a.normalize(context=self)
4228
Facundo Batista353750c2007-09-13 18:13:15 +00004229 def number_class(self, a):
4230 """Returns an indication of the class of the operand.
4231
4232 The class is one of the following strings:
4233 -sNaN
4234 -NaN
4235 -Infinity
4236 -Normal
4237 -Subnormal
4238 -Zero
4239 +Zero
4240 +Subnormal
4241 +Normal
4242 +Infinity
4243
4244 >>> c = Context(ExtendedContext)
4245 >>> c.Emin = -999
4246 >>> c.Emax = 999
4247 >>> c.number_class(Decimal('Infinity'))
4248 '+Infinity'
4249 >>> c.number_class(Decimal('1E-10'))
4250 '+Normal'
4251 >>> c.number_class(Decimal('2.50'))
4252 '+Normal'
4253 >>> c.number_class(Decimal('0.1E-999'))
4254 '+Subnormal'
4255 >>> c.number_class(Decimal('0'))
4256 '+Zero'
4257 >>> c.number_class(Decimal('-0'))
4258 '-Zero'
4259 >>> c.number_class(Decimal('-0.1E-999'))
4260 '-Subnormal'
4261 >>> c.number_class(Decimal('-1E-10'))
4262 '-Normal'
4263 >>> c.number_class(Decimal('-2.50'))
4264 '-Normal'
4265 >>> c.number_class(Decimal('-Infinity'))
4266 '-Infinity'
4267 >>> c.number_class(Decimal('NaN'))
4268 'NaN'
4269 >>> c.number_class(Decimal('-NaN'))
4270 'NaN'
4271 >>> c.number_class(Decimal('sNaN'))
4272 'sNaN'
4273 """
4274 return a.number_class(context=self)
4275
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004276 def plus(self, a):
4277 """Plus corresponds to unary prefix plus in Python.
4278
4279 The operation is evaluated using the same rules as add; the
4280 operation plus(a) is calculated as add('0', a) where the '0'
4281 has the same exponent as the operand.
4282
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004283 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004284 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004285 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004286 Decimal("-1.3")
4287 """
4288 return a.__pos__(context=self)
4289
4290 def power(self, a, b, modulo=None):
4291 """Raises a to the power of b, to modulo if given.
4292
Facundo Batista353750c2007-09-13 18:13:15 +00004293 With two arguments, compute a**b. If a is negative then b
4294 must be integral. The result will be inexact unless b is
4295 integral and the result is finite and can be expressed exactly
4296 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004297
Facundo Batista353750c2007-09-13 18:13:15 +00004298 With three arguments, compute (a**b) % modulo. For the
4299 three argument form, the following restrictions on the
4300 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004301
Facundo Batista353750c2007-09-13 18:13:15 +00004302 - all three arguments must be integral
4303 - b must be nonnegative
4304 - at least one of a or b must be nonzero
4305 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004306
Facundo Batista353750c2007-09-13 18:13:15 +00004307 The result of pow(a, b, modulo) is identical to the result
4308 that would be obtained by computing (a**b) % modulo with
4309 unbounded precision, but is computed more efficiently. It is
4310 always exact.
4311
4312 >>> c = ExtendedContext.copy()
4313 >>> c.Emin = -999
4314 >>> c.Emax = 999
4315 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004316 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004317 >>> c.power(Decimal('-2'), Decimal('3'))
4318 Decimal("-8")
4319 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004320 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004321 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004322 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004323 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4324 Decimal("2.00000000")
4325 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004326 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004327 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004328 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004329 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004330 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004331 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004332 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004333 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004334 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004335 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004336 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004337 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004338 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004339 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004340 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004341
4342 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4343 Decimal("11")
4344 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4345 Decimal("-11")
4346 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4347 Decimal("1")
4348 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4349 Decimal("11")
4350 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4351 Decimal("11729830")
4352 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4353 Decimal("-0")
4354 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4355 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004356 """
4357 return a.__pow__(b, modulo, context=self)
4358
4359 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004360 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004361
4362 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004363 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004364 exponent is being increased), multiplied by a positive power of ten (if
4365 the exponent is being decreased), or is unchanged (if the exponent is
4366 already equal to that of the right-hand operand).
4367
4368 Unlike other operations, if the length of the coefficient after the
4369 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004370 operation condition is raised. This guarantees that, unless there is
4371 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004372 equal to that of the right-hand operand.
4373
4374 Also unlike other operations, quantize will never raise Underflow, even
4375 if the result is subnormal and inexact.
4376
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004377 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004378 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004379 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004380 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004381 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004382 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004383 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004384 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004385 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004386 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004387 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004388 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004389 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004390 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004391 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004392 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004393 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004394 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004395 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004396 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004397 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004398 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004399 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004400 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004401 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004402 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004403 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004404 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004405 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004406 Decimal("2E+2")
4407 """
4408 return a.quantize(b, context=self)
4409
Facundo Batista353750c2007-09-13 18:13:15 +00004410 def radix(self):
4411 """Just returns 10, as this is Decimal, :)
4412
4413 >>> ExtendedContext.radix()
4414 Decimal("10")
4415 """
4416 return Decimal(10)
4417
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004418 def remainder(self, a, b):
4419 """Returns the remainder from integer division.
4420
4421 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004422 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004423 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004424 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004425
4426 This operation will fail under the same conditions as integer division
4427 (that is, if integer division on the same two operands would fail, the
4428 remainder cannot be calculated).
4429
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004430 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004431 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004432 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004433 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004434 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004435 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004436 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004437 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004438 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004439 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004440 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004441 Decimal("1.0")
4442 """
4443 return a.__mod__(b, context=self)
4444
4445 def remainder_near(self, a, b):
4446 """Returns to be "a - b * n", where n is the integer nearest the exact
4447 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004448 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004449 sign of a.
4450
4451 This operation will fail under the same conditions as integer division
4452 (that is, if integer division on the same two operands would fail, the
4453 remainder cannot be calculated).
4454
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004455 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004456 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004457 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004458 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004459 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004460 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004461 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004462 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004463 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004464 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004465 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004466 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004467 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004468 Decimal("-0.3")
4469 """
4470 return a.remainder_near(b, context=self)
4471
Facundo Batista353750c2007-09-13 18:13:15 +00004472 def rotate(self, a, b):
4473 """Returns a rotated copy of a, b times.
4474
4475 The coefficient of the result is a rotated copy of the digits in
4476 the coefficient of the first operand. The number of places of
4477 rotation is taken from the absolute value of the second operand,
4478 with the rotation being to the left if the second operand is
4479 positive or to the right otherwise.
4480
4481 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4482 Decimal("400000003")
4483 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4484 Decimal("12")
4485 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4486 Decimal("891234567")
4487 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4488 Decimal("123456789")
4489 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4490 Decimal("345678912")
4491 """
4492 return a.rotate(b, context=self)
4493
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004494 def same_quantum(self, a, b):
4495 """Returns True if the two operands have the same exponent.
4496
4497 The result is never affected by either the sign or the coefficient of
4498 either operand.
4499
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004500 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004501 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004502 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004503 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004504 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004505 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004506 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004507 True
4508 """
4509 return a.same_quantum(b)
4510
Facundo Batista353750c2007-09-13 18:13:15 +00004511 def scaleb (self, a, b):
4512 """Returns the first operand after adding the second value its exp.
4513
4514 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4515 Decimal("0.0750")
4516 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4517 Decimal("7.50")
4518 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4519 Decimal("7.50E+3")
4520 """
4521 return a.scaleb (b, context=self)
4522
4523 def shift(self, a, b):
4524 """Returns a shifted copy of a, b times.
4525
4526 The coefficient of the result is a shifted copy of the digits
4527 in the coefficient of the first operand. The number of places
4528 to shift is taken from the absolute value of the second operand,
4529 with the shift being to the left if the second operand is
4530 positive or to the right otherwise. Digits shifted into the
4531 coefficient are zeros.
4532
4533 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4534 Decimal("400000000")
4535 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4536 Decimal("0")
4537 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4538 Decimal("1234567")
4539 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4540 Decimal("123456789")
4541 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4542 Decimal("345678900")
4543 """
4544 return a.shift(b, context=self)
4545
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004546 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004547 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004548
4549 If the result must be inexact, it is rounded using the round-half-even
4550 algorithm.
4551
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004552 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004553 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004554 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004555 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004556 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004557 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004558 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004559 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004560 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004561 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004562 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004563 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004564 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004565 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004566 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004567 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004568 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004569 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004570 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004571 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004572 """
4573 return a.sqrt(context=self)
4574
4575 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004576 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004577
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004578 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004579 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004580 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004581 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004582 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004583 Decimal("-0.77")
4584 """
4585 return a.__sub__(b, context=self)
4586
4587 def to_eng_string(self, a):
4588 """Converts a number to a string, using scientific notation.
4589
4590 The operation is not affected by the context.
4591 """
4592 return a.to_eng_string(context=self)
4593
4594 def to_sci_string(self, a):
4595 """Converts a number to a string, using scientific notation.
4596
4597 The operation is not affected by the context.
4598 """
4599 return a.__str__(context=self)
4600
Facundo Batista353750c2007-09-13 18:13:15 +00004601 def to_integral_exact(self, a):
4602 """Rounds to an integer.
4603
4604 When the operand has a negative exponent, the result is the same
4605 as using the quantize() operation using the given operand as the
4606 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4607 of the operand as the precision setting; Inexact and Rounded flags
4608 are allowed in this operation. The rounding mode is taken from the
4609 context.
4610
4611 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4612 Decimal("2")
4613 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4614 Decimal("100")
4615 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4616 Decimal("100")
4617 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4618 Decimal("102")
4619 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4620 Decimal("-102")
4621 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4622 Decimal("1.0E+6")
4623 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4624 Decimal("7.89E+77")
4625 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4626 Decimal("-Infinity")
4627 """
4628 return a.to_integral_exact(context=self)
4629
4630 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004631 """Rounds to an integer.
4632
4633 When the operand has a negative exponent, the result is the same
4634 as using the quantize() operation using the given operand as the
4635 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4636 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004637 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004638
Facundo Batista353750c2007-09-13 18:13:15 +00004639 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004640 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004641 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004642 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004643 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004644 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004645 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004646 Decimal("102")
Facundo Batista353750c2007-09-13 18:13:15 +00004647 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004648 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004649 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004650 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004651 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004652 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004653 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004654 Decimal("-Infinity")
4655 """
Facundo Batista353750c2007-09-13 18:13:15 +00004656 return a.to_integral_value(context=self)
4657
4658 # the method name changed, but we provide also the old one, for compatibility
4659 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004660
4661class _WorkRep(object):
4662 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004663 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004664 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004665 # exp: None, int, or string
4666
4667 def __init__(self, value=None):
4668 if value is None:
4669 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004670 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004671 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004672 elif isinstance(value, Decimal):
4673 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004674 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004675 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004676 else:
4677 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004678 self.sign = value[0]
4679 self.int = value[1]
4680 self.exp = value[2]
4681
4682 def __repr__(self):
4683 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4684
4685 __str__ = __repr__
4686
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004687
4688
Facundo Batistae64acfa2007-12-17 14:18:42 +00004689def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004690 """Normalizes op1, op2 to have the same exp and length of coefficient.
4691
4692 Done during addition.
4693 """
Facundo Batista353750c2007-09-13 18:13:15 +00004694 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004695 tmp = op2
4696 other = op1
4697 else:
4698 tmp = op1
4699 other = op2
4700
Facundo Batista353750c2007-09-13 18:13:15 +00004701 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4702 # Then adding 10**exp to tmp has the same effect (after rounding)
4703 # as adding any positive quantity smaller than 10**exp; similarly
4704 # for subtraction. So if other is smaller than 10**exp we replace
4705 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00004706 tmp_len = len(str(tmp.int))
4707 other_len = len(str(other.int))
4708 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4709 if other_len + other.exp - 1 < exp:
4710 other.int = 1
4711 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004712
Facundo Batista353750c2007-09-13 18:13:15 +00004713 tmp.int *= 10 ** (tmp.exp - other.exp)
4714 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004715 return op1, op2
4716
Facundo Batista353750c2007-09-13 18:13:15 +00004717##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4718
4719# This function from Tim Peters was taken from here:
4720# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4721# The correction being in the function definition is for speed, and
4722# the whole function is not resolved with math.log because of avoiding
4723# the use of floats.
4724def _nbits(n, correction = {
4725 '0': 4, '1': 3, '2': 2, '3': 2,
4726 '4': 1, '5': 1, '6': 1, '7': 1,
4727 '8': 0, '9': 0, 'a': 0, 'b': 0,
4728 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4729 """Number of bits in binary representation of the positive integer n,
4730 or 0 if n == 0.
4731 """
4732 if n < 0:
4733 raise ValueError("The argument to _nbits should be nonnegative.")
4734 hex_n = "%x" % n
4735 return 4*len(hex_n) - correction[hex_n[0]]
4736
4737def _sqrt_nearest(n, a):
4738 """Closest integer to the square root of the positive integer n. a is
4739 an initial approximation to the square root. Any positive integer
4740 will do for a, but the closer a is to the square root of n the
4741 faster convergence will be.
4742
4743 """
4744 if n <= 0 or a <= 0:
4745 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4746
4747 b=0
4748 while a != b:
4749 b, a = a, a--n//a>>1
4750 return a
4751
4752def _rshift_nearest(x, shift):
4753 """Given an integer x and a nonnegative integer shift, return closest
4754 integer to x / 2**shift; use round-to-even in case of a tie.
4755
4756 """
4757 b, q = 1L << shift, x >> shift
4758 return q + (2*(x & (b-1)) + (q&1) > b)
4759
4760def _div_nearest(a, b):
4761 """Closest integer to a/b, a and b positive integers; rounds to even
4762 in the case of a tie.
4763
4764 """
4765 q, r = divmod(a, b)
4766 return q + (2*r + (q&1) > b)
4767
4768def _ilog(x, M, L = 8):
4769 """Integer approximation to M*log(x/M), with absolute error boundable
4770 in terms only of x/M.
4771
4772 Given positive integers x and M, return an integer approximation to
4773 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4774 between the approximation and the exact result is at most 22. For
4775 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4776 both cases these are upper bounds on the error; it will usually be
4777 much smaller."""
4778
4779 # The basic algorithm is the following: let log1p be the function
4780 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4781 # the reduction
4782 #
4783 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4784 #
4785 # repeatedly until the argument to log1p is small (< 2**-L in
4786 # absolute value). For small y we can use the Taylor series
4787 # expansion
4788 #
4789 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4790 #
4791 # truncating at T such that y**T is small enough. The whole
4792 # computation is carried out in a form of fixed-point arithmetic,
4793 # with a real number z being represented by an integer
4794 # approximation to z*M. To avoid loss of precision, the y below
4795 # is actually an integer approximation to 2**R*y*M, where R is the
4796 # number of reductions performed so far.
4797
4798 y = x-M
4799 # argument reduction; R = number of reductions performed
4800 R = 0
4801 while (R <= L and long(abs(y)) << L-R >= M or
4802 R > L and abs(y) >> R-L >= M):
4803 y = _div_nearest(long(M*y) << 1,
4804 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4805 R += 1
4806
4807 # Taylor series with T terms
4808 T = -int(-10*len(str(M))//(3*L))
4809 yshift = _rshift_nearest(y, R)
4810 w = _div_nearest(M, T)
4811 for k in xrange(T-1, 0, -1):
4812 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4813
4814 return _div_nearest(w*y, M)
4815
4816def _dlog10(c, e, p):
4817 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4818 approximation to 10**p * log10(c*10**e), with an absolute error of
4819 at most 1. Assumes that c*10**e is not exactly 1."""
4820
4821 # increase precision by 2; compensate for this by dividing
4822 # final result by 100
4823 p += 2
4824
4825 # write c*10**e as d*10**f with either:
4826 # f >= 0 and 1 <= d <= 10, or
4827 # f <= 0 and 0.1 <= d <= 1.
4828 # Thus for c*10**e close to 1, f = 0
4829 l = len(str(c))
4830 f = e+l - (e+l >= 1)
4831
4832 if p > 0:
4833 M = 10**p
4834 k = e+p-f
4835 if k >= 0:
4836 c *= 10**k
4837 else:
4838 c = _div_nearest(c, 10**-k)
4839
4840 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004841 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004842 log_d = _div_nearest(log_d*M, log_10)
4843 log_tenpower = f*M # exact
4844 else:
4845 log_d = 0 # error < 2.31
4846 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4847
4848 return _div_nearest(log_tenpower+log_d, 100)
4849
4850def _dlog(c, e, p):
4851 """Given integers c, e and p with c > 0, compute an integer
4852 approximation to 10**p * log(c*10**e), with an absolute error of
4853 at most 1. Assumes that c*10**e is not exactly 1."""
4854
4855 # Increase precision by 2. The precision increase is compensated
4856 # for at the end with a division by 100.
4857 p += 2
4858
4859 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4860 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4861 # as 10**p * log(d) + 10**p*f * log(10).
4862 l = len(str(c))
4863 f = e+l - (e+l >= 1)
4864
4865 # compute approximation to 10**p*log(d), with error < 27
4866 if p > 0:
4867 k = e+p-f
4868 if k >= 0:
4869 c *= 10**k
4870 else:
4871 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4872
4873 # _ilog magnifies existing error in c by a factor of at most 10
4874 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4875 else:
4876 # p <= 0: just approximate the whole thing by 0; error < 2.31
4877 log_d = 0
4878
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004879 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00004880 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004881 extra = len(str(abs(f)))-1
4882 if p + extra >= 0:
4883 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4884 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4885 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00004886 else:
4887 f_log_ten = 0
4888 else:
4889 f_log_ten = 0
4890
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004891 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004892 return _div_nearest(f_log_ten + log_d, 100)
4893
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004894class _Log10Memoize(object):
4895 """Class to compute, store, and allow retrieval of, digits of the
4896 constant log(10) = 2.302585.... This constant is needed by
4897 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4898 def __init__(self):
4899 self.digits = "23025850929940456840179914546843642076011014886"
4900
4901 def getdigits(self, p):
4902 """Given an integer p >= 0, return floor(10**p)*log(10).
4903
4904 For example, self.getdigits(3) returns 2302.
4905 """
4906 # digits are stored as a string, for quick conversion to
4907 # integer in the case that we've already computed enough
4908 # digits; the stored digits should always be correct
4909 # (truncated, not rounded to nearest).
4910 if p < 0:
4911 raise ValueError("p should be nonnegative")
4912
4913 if p >= len(self.digits):
4914 # compute p+3, p+6, p+9, ... digits; continue until at
4915 # least one of the extra digits is nonzero
4916 extra = 3
4917 while True:
4918 # compute p+extra digits, correct to within 1ulp
4919 M = 10**(p+extra+2)
4920 digits = str(_div_nearest(_ilog(10*M, M), 100))
4921 if digits[-extra:] != '0'*extra:
4922 break
4923 extra += 3
4924 # keep all reliable digits so far; remove trailing zeros
4925 # and next nonzero digit
4926 self.digits = digits.rstrip('0')[:-1]
4927 return int(self.digits[:p+1])
4928
4929_log10_digits = _Log10Memoize().getdigits
4930
Facundo Batista353750c2007-09-13 18:13:15 +00004931def _iexp(x, M, L=8):
4932 """Given integers x and M, M > 0, such that x/M is small in absolute
4933 value, compute an integer approximation to M*exp(x/M). For 0 <=
4934 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4935 is usually much smaller)."""
4936
4937 # Algorithm: to compute exp(z) for a real number z, first divide z
4938 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4939 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4940 # series
4941 #
4942 # expm1(x) = x + x**2/2! + x**3/3! + ...
4943 #
4944 # Now use the identity
4945 #
4946 # expm1(2x) = expm1(x)*(expm1(x)+2)
4947 #
4948 # R times to compute the sequence expm1(z/2**R),
4949 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
4950
4951 # Find R such that x/2**R/M <= 2**-L
4952 R = _nbits((long(x)<<L)//M)
4953
4954 # Taylor series. (2**L)**T > M
4955 T = -int(-10*len(str(M))//(3*L))
4956 y = _div_nearest(x, T)
4957 Mshift = long(M)<<R
4958 for i in xrange(T-1, 0, -1):
4959 y = _div_nearest(x*(Mshift + y), Mshift * i)
4960
4961 # Expansion
4962 for k in xrange(R-1, -1, -1):
4963 Mshift = long(M)<<(k+2)
4964 y = _div_nearest(y*(y+Mshift), Mshift)
4965
4966 return M+y
4967
4968def _dexp(c, e, p):
4969 """Compute an approximation to exp(c*10**e), with p decimal places of
4970 precision.
4971
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004972 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00004973
4974 10**(p-1) <= d <= 10**p, and
4975 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
4976
4977 In other words, d*10**f is an approximation to exp(c*10**e) with p
4978 digits of precision, and with an error in d of at most 1. This is
4979 almost, but not quite, the same as the error being < 1ulp: when d
4980 = 10**(p-1) the error could be up to 10 ulp."""
4981
4982 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
4983 p += 2
4984
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004985 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00004986 extra = max(0, e + len(str(c)) - 1)
4987 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00004988
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004989 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00004990 # rounding down
4991 shift = e+q
4992 if shift >= 0:
4993 cshift = c*10**shift
4994 else:
4995 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004996 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00004997
4998 # reduce remainder back to original precision
4999 rem = _div_nearest(rem, 10**extra)
5000
5001 # error in result of _iexp < 120; error after division < 0.62
5002 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5003
5004def _dpower(xc, xe, yc, ye, p):
5005 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5006 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5007
5008 10**(p-1) <= c <= 10**p, and
5009 (c-1)*10**e < x**y < (c+1)*10**e
5010
5011 in other words, c*10**e is an approximation to x**y with p digits
5012 of precision, and with an error in c of at most 1. (This is
5013 almost, but not quite, the same as the error being < 1ulp: when c
5014 == 10**(p-1) we can only guarantee error < 10ulp.)
5015
5016 We assume that: x is positive and not equal to 1, and y is nonzero.
5017 """
5018
5019 # Find b such that 10**(b-1) <= |y| <= 10**b
5020 b = len(str(abs(yc))) + ye
5021
5022 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5023 lxc = _dlog(xc, xe, p+b+1)
5024
5025 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5026 shift = ye-b
5027 if shift >= 0:
5028 pc = lxc*yc*10**shift
5029 else:
5030 pc = _div_nearest(lxc*yc, 10**-shift)
5031
5032 if pc == 0:
5033 # we prefer a result that isn't exactly 1; this makes it
5034 # easier to compute a correctly rounded result in __pow__
5035 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5036 coeff, exp = 10**(p-1)+1, 1-p
5037 else:
5038 coeff, exp = 10**p-1, -p
5039 else:
5040 coeff, exp = _dexp(pc, -(p+1), p+1)
5041 coeff = _div_nearest(coeff, 10)
5042 exp += 1
5043
5044 return coeff, exp
5045
5046def _log10_lb(c, correction = {
5047 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5048 '6': 23, '7': 16, '8': 10, '9': 5}):
5049 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5050 if c <= 0:
5051 raise ValueError("The argument to _log10_lb should be nonnegative.")
5052 str_c = str(c)
5053 return 100*len(str_c) - correction[str_c[0]]
5054
Facundo Batista59c58842007-04-10 12:58:45 +00005055##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005056
Facundo Batista353750c2007-09-13 18:13:15 +00005057def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005058 """Convert other to Decimal.
5059
5060 Verifies that it's ok to use in an implicit construction.
5061 """
5062 if isinstance(other, Decimal):
5063 return other
5064 if isinstance(other, (int, long)):
5065 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005066 if raiseit:
5067 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005068 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005069
Facundo Batista59c58842007-04-10 12:58:45 +00005070##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005071
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005072# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005073# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005074
5075DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005076 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005077 traps=[DivisionByZero, Overflow, InvalidOperation],
5078 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005079 Emax=999999999,
5080 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005081 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005082)
5083
5084# Pre-made alternate contexts offered by the specification
5085# Don't change these; the user should be able to select these
5086# contexts and be able to reproduce results from other implementations
5087# of the spec.
5088
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005089BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005090 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005091 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5092 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005093)
5094
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005095ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005096 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005097 traps=[],
5098 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005099)
5100
5101
Facundo Batista72bc54f2007-11-23 17:59:00 +00005102##### crud for parsing strings #############################################
5103import re
5104
5105# Regular expression used for parsing numeric strings. Additional
5106# comments:
5107#
5108# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5109# whitespace. But note that the specification disallows whitespace in
5110# a numeric string.
5111#
5112# 2. For finite numbers (not infinities and NaNs) the body of the
5113# number between the optional sign and the optional exponent must have
5114# at least one decimal digit, possibly after the decimal point. The
5115# lookahead expression '(?=\d|\.\d)' checks this.
5116#
5117# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5118# other meaning for \d than the numbers [0-9].
5119
5120import re
5121_parser = re.compile(r""" # A numeric string consists of:
5122# \s*
5123 (?P<sign>[-+])? # an optional sign, followed by either...
5124 (
5125 (?=\d|\.\d) # ...a number (with at least one digit)
5126 (?P<int>\d*) # consisting of a (possibly empty) integer part
5127 (\.(?P<frac>\d*))? # followed by an optional fractional part
5128 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5129 |
5130 Inf(inity)? # ...an infinity, or...
5131 |
5132 (?P<signal>s)? # ...an (optionally signaling)
5133 NaN # NaN
5134 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5135 )
5136# \s*
5137 $
5138""", re.VERBOSE | re.IGNORECASE).match
5139
Facundo Batista2ec74152007-12-03 17:55:00 +00005140_all_zeros = re.compile('0*$').match
5141_exact_half = re.compile('50*$').match
Facundo Batista72bc54f2007-11-23 17:59:00 +00005142del re
5143
5144
Facundo Batista59c58842007-04-10 12:58:45 +00005145##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005146
Facundo Batista59c58842007-04-10 12:58:45 +00005147# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005148Inf = Decimal('Inf')
5149negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005150NaN = Decimal('NaN')
5151Dec_0 = Decimal(0)
5152Dec_p1 = Decimal(1)
5153Dec_n1 = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005154
Facundo Batista59c58842007-04-10 12:58:45 +00005155# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005156Infsign = (Inf, negInf)
5157
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005158
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005159
5160if __name__ == '__main__':
5161 import doctest, sys
5162 doctest.testmod(sys.modules[__name__])