blob: 3ee078f570daf1303521f28fe776a42a380df86a [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
Facundo Batista52b25792008-01-08 12:25:20 +0000791 #
792 # The hash of a nonspecial noninteger Decimal must depend only
793 # on the value of that Decimal, and not on its representation.
794 # For example: hash(Decimal("100E-1")) == hash(Decimal("10")).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000795 if self._is_special:
796 if self._isnan():
797 raise TypeError('Cannot hash a NaN value.')
798 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000799 if not self:
800 return 0
801 if self._isinteger():
802 op = _WorkRep(self.to_integral_value())
803 # to make computation feasible for Decimals with large
804 # exponent, we use the fact that hash(n) == hash(m) for
805 # any two nonzero integers n and m such that (i) n and m
806 # have the same sign, and (ii) n is congruent to m modulo
807 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
808 # hash((-1)**s*c*pow(10, e, 2**64-1).
809 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Facundo Batista52b25792008-01-08 12:25:20 +0000810 # The value of a nonzero nonspecial Decimal instance is
811 # faithfully represented by the triple consisting of its sign,
812 # its adjusted exponent, and its coefficient with trailing
813 # zeros removed.
814 return hash((self._sign,
815 self._exp+len(self._int),
816 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000817
818 def as_tuple(self):
819 """Represents the number as a triple tuple.
820
821 To show the internals exactly as they are.
822 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000823 return (self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000824
825 def __repr__(self):
826 """Represents the number as an instance of Decimal."""
827 # Invariant: eval(repr(d)) == d
828 return 'Decimal("%s")' % str(self)
829
Facundo Batista353750c2007-09-13 18:13:15 +0000830 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000831 """Return string representation of the number in scientific notation.
832
833 Captures all of the information in the underlying representation.
834 """
835
Facundo Batista62edb712007-12-03 16:29:52 +0000836 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000837 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +0000838 if self._exp == 'F':
839 return sign + 'Infinity'
840 elif self._exp == 'n':
841 return sign + 'NaN' + self._int
842 else: # self._exp == 'N'
843 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000844
Facundo Batista62edb712007-12-03 16:29:52 +0000845 # number of digits of self._int to left of decimal point
846 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000847
Facundo Batista62edb712007-12-03 16:29:52 +0000848 # dotplace is number of digits of self._int to the left of the
849 # decimal point in the mantissa of the output string (that is,
850 # after adjusting the exponent)
851 if self._exp <= 0 and leftdigits > -6:
852 # no exponent required
853 dotplace = leftdigits
854 elif not eng:
855 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000856 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +0000857 elif self._int == '0':
858 # engineering notation, zero
859 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000860 else:
Facundo Batista62edb712007-12-03 16:29:52 +0000861 # engineering notation, nonzero
862 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000863
Facundo Batista62edb712007-12-03 16:29:52 +0000864 if dotplace <= 0:
865 intpart = '0'
866 fracpart = '.' + '0'*(-dotplace) + self._int
867 elif dotplace >= len(self._int):
868 intpart = self._int+'0'*(dotplace-len(self._int))
869 fracpart = ''
870 else:
871 intpart = self._int[:dotplace]
872 fracpart = '.' + self._int[dotplace:]
873 if leftdigits == dotplace:
874 exp = ''
875 else:
876 if context is None:
877 context = getcontext()
878 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
879
880 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000881
882 def to_eng_string(self, context=None):
883 """Convert to engineering-type string.
884
885 Engineering notation has an exponent which is a multiple of 3, so there
886 are up to 3 digits left of the decimal place.
887
888 Same rules for when in exponential and when as a value as in __str__.
889 """
Facundo Batista353750c2007-09-13 18:13:15 +0000890 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000891
892 def __neg__(self, context=None):
893 """Returns a copy with the sign switched.
894
895 Rounds, if it has reason.
896 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000897 if self._is_special:
898 ans = self._check_nans(context=context)
899 if ans:
900 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000901
902 if not self:
903 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000904 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000905 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000906 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000907
908 if context is None:
909 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +0000910 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000911
912 def __pos__(self, context=None):
913 """Returns a copy, unless it is a sNaN.
914
915 Rounds the number (if more then precision digits)
916 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000917 if self._is_special:
918 ans = self._check_nans(context=context)
919 if ans:
920 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000921
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000922 if not self:
923 # + (-0) = 0
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000924 ans = self.copy_abs()
Facundo Batista353750c2007-09-13 18:13:15 +0000925 else:
926 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000927
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000928 if context is None:
929 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +0000930 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000931
Facundo Batistae64acfa2007-12-17 14:18:42 +0000932 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000933 """Returns the absolute value of self.
934
Facundo Batistae64acfa2007-12-17 14:18:42 +0000935 If the keyword argument 'round' is false, do not round. The
936 expression self.__abs__(round=False) is equivalent to
937 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000938 """
Facundo Batistae64acfa2007-12-17 14:18:42 +0000939 if not round:
940 return self.copy_abs()
941
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000942 if self._is_special:
943 ans = self._check_nans(context=context)
944 if ans:
945 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000946
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000947 if self._sign:
948 ans = self.__neg__(context=context)
949 else:
950 ans = self.__pos__(context=context)
951
952 return ans
953
954 def __add__(self, other, context=None):
955 """Returns self + other.
956
957 -INF + INF (or the reverse) cause InvalidOperation errors.
958 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000959 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000960 if other is NotImplemented:
961 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000962
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000963 if context is None:
964 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000965
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000966 if self._is_special or other._is_special:
967 ans = self._check_nans(other, context)
968 if ans:
969 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000970
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000971 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000972 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000973 if self._sign != other._sign and other._isinfinity():
974 return context._raise_error(InvalidOperation, '-INF + INF')
975 return Decimal(self)
976 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000977 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000978
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000979 exp = min(self._exp, other._exp)
980 negativezero = 0
981 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +0000982 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000983 negativezero = 1
984
985 if not self and not other:
986 sign = min(self._sign, other._sign)
987 if negativezero:
988 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +0000989 ans = _dec_from_triple(sign, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +0000990 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +0000991 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000992 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +0000993 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +0000994 ans = other._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +0000995 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000996 return ans
997 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +0000998 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +0000999 ans = self._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001000 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001001 return ans
1002
1003 op1 = _WorkRep(self)
1004 op2 = _WorkRep(other)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001005 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001006
1007 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001008 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001010 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001011 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001012 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001013 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001014 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001015 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001016 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001017 if op1.sign == 1:
1018 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001019 op1.sign, op2.sign = op2.sign, op1.sign
1020 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001021 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001022 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001023 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001024 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001025 op1.sign, op2.sign = (0, 0)
1026 else:
1027 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001028 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001029
Raymond Hettinger17931de2004-10-27 06:21:46 +00001030 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001031 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001032 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001033 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001034
1035 result.exp = op1.exp
1036 ans = Decimal(result)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001037 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001038 return ans
1039
1040 __radd__ = __add__
1041
1042 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001043 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001044 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001045 if other is NotImplemented:
1046 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001047
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001048 if self._is_special or other._is_special:
1049 ans = self._check_nans(other, context=context)
1050 if ans:
1051 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001052
Facundo Batista353750c2007-09-13 18:13:15 +00001053 # self - other is computed as self + other.copy_negate()
1054 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055
1056 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001057 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001058 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001059 if other is NotImplemented:
1060 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001061
Facundo Batista353750c2007-09-13 18:13:15 +00001062 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001063
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001064 def __mul__(self, other, context=None):
1065 """Return self * other.
1066
1067 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1068 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001069 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001070 if other is NotImplemented:
1071 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001072
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001073 if context is None:
1074 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001075
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001076 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001077
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001078 if self._is_special or other._is_special:
1079 ans = self._check_nans(other, context)
1080 if ans:
1081 return ans
1082
1083 if self._isinfinity():
1084 if not other:
1085 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1086 return Infsign[resultsign]
1087
1088 if other._isinfinity():
1089 if not self:
1090 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1091 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001092
1093 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001094
1095 # Special case for multiplying by zero
1096 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001097 ans = _dec_from_triple(resultsign, '0', resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001098 # Fixing in case the exponent is out of bounds
1099 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001100 return ans
1101
1102 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001103 if self._int == '1':
1104 ans = _dec_from_triple(resultsign, other._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001105 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001106 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001107 if other._int == '1':
1108 ans = _dec_from_triple(resultsign, self._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001109 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001110 return ans
1111
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001112 op1 = _WorkRep(self)
1113 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001114
Facundo Batista72bc54f2007-11-23 17:59:00 +00001115 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001116 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001117
1118 return ans
1119 __rmul__ = __mul__
1120
1121 def __div__(self, other, context=None):
1122 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001123 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001124 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001125 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001126
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001127 if context is None:
1128 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001129
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001130 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001131
1132 if self._is_special or other._is_special:
1133 ans = self._check_nans(other, context)
1134 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001135 return ans
1136
1137 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001138 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001139
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001140 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001141 return Infsign[sign]
1142
1143 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001144 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001145 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001146
1147 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001148 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001149 if not self:
1150 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001151 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001152
Facundo Batistacce8df22007-09-18 16:53:18 +00001153 if not self:
1154 exp = self._exp - other._exp
1155 coeff = 0
1156 else:
1157 # OK, so neither = 0, INF or NaN
1158 shift = len(other._int) - len(self._int) + context.prec + 1
1159 exp = self._exp - other._exp - shift
1160 op1 = _WorkRep(self)
1161 op2 = _WorkRep(other)
1162 if shift >= 0:
1163 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1164 else:
1165 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1166 if remainder:
1167 # result is not exact; adjust to ensure correct rounding
1168 if coeff % 5 == 0:
1169 coeff += 1
1170 else:
1171 # result is exact; get as close to ideal exponent as possible
1172 ideal_exp = self._exp - other._exp
1173 while exp < ideal_exp and coeff % 10 == 0:
1174 coeff //= 10
1175 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001176
Facundo Batista72bc54f2007-11-23 17:59:00 +00001177 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001178 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001179
Facundo Batistacce8df22007-09-18 16:53:18 +00001180 __truediv__ = __div__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001181
Facundo Batistacce8df22007-09-18 16:53:18 +00001182 def _divide(self, other, context):
1183 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001184
Facundo Batistacce8df22007-09-18 16:53:18 +00001185 Assumes that neither self nor other is a NaN, that self is not
1186 infinite and that other is nonzero.
1187 """
1188 sign = self._sign ^ other._sign
1189 if other._isinfinity():
1190 ideal_exp = self._exp
1191 else:
1192 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001193
Facundo Batistacce8df22007-09-18 16:53:18 +00001194 expdiff = self.adjusted() - other.adjusted()
1195 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001196 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001197 self._rescale(ideal_exp, context.rounding))
1198 if expdiff <= context.prec:
1199 op1 = _WorkRep(self)
1200 op2 = _WorkRep(other)
1201 if op1.exp >= op2.exp:
1202 op1.int *= 10**(op1.exp - op2.exp)
1203 else:
1204 op2.int *= 10**(op2.exp - op1.exp)
1205 q, r = divmod(op1.int, op2.int)
1206 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001207 return (_dec_from_triple(sign, str(q), 0),
1208 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001209
Facundo Batistacce8df22007-09-18 16:53:18 +00001210 # Here the quotient is too large to be representable
1211 ans = context._raise_error(DivisionImpossible,
1212 'quotient too large in //, % or divmod')
1213 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001214
1215 def __rdiv__(self, other, context=None):
1216 """Swaps self/other and returns __div__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001217 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001218 if other is NotImplemented:
1219 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001220 return other.__div__(self, context=context)
1221 __rtruediv__ = __rdiv__
1222
1223 def __divmod__(self, other, context=None):
1224 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001225 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001226 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001227 other = _convert_other(other)
1228 if other is NotImplemented:
1229 return other
1230
1231 if context is None:
1232 context = getcontext()
1233
1234 ans = self._check_nans(other, context)
1235 if ans:
1236 return (ans, ans)
1237
1238 sign = self._sign ^ other._sign
1239 if self._isinfinity():
1240 if other._isinfinity():
1241 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1242 return ans, ans
1243 else:
1244 return (Infsign[sign],
1245 context._raise_error(InvalidOperation, 'INF % x'))
1246
1247 if not other:
1248 if not self:
1249 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1250 return ans, ans
1251 else:
1252 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1253 context._raise_error(InvalidOperation, 'x % 0'))
1254
1255 quotient, remainder = self._divide(other, context)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001256 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001257 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001258
1259 def __rdivmod__(self, other, context=None):
1260 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001261 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001262 if other is NotImplemented:
1263 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001264 return other.__divmod__(self, context=context)
1265
1266 def __mod__(self, other, context=None):
1267 """
1268 self % other
1269 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001270 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001271 if other is NotImplemented:
1272 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001273
Facundo Batistacce8df22007-09-18 16:53:18 +00001274 if context is None:
1275 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001276
Facundo Batistacce8df22007-09-18 16:53:18 +00001277 ans = self._check_nans(other, context)
1278 if ans:
1279 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001280
Facundo Batistacce8df22007-09-18 16:53:18 +00001281 if self._isinfinity():
1282 return context._raise_error(InvalidOperation, 'INF % x')
1283 elif not other:
1284 if self:
1285 return context._raise_error(InvalidOperation, 'x % 0')
1286 else:
1287 return context._raise_error(DivisionUndefined, '0 % 0')
1288
1289 remainder = self._divide(other, context)[1]
Facundo Batistae64acfa2007-12-17 14:18:42 +00001290 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001291 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001292
1293 def __rmod__(self, other, context=None):
1294 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001295 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001296 if other is NotImplemented:
1297 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001298 return other.__mod__(self, context=context)
1299
1300 def remainder_near(self, other, context=None):
1301 """
1302 Remainder nearest to 0- abs(remainder-near) <= other/2
1303 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001304 if context is None:
1305 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001306
Facundo Batista353750c2007-09-13 18:13:15 +00001307 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001308
Facundo Batista353750c2007-09-13 18:13:15 +00001309 ans = self._check_nans(other, context)
1310 if ans:
1311 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001312
Facundo Batista353750c2007-09-13 18:13:15 +00001313 # self == +/-infinity -> InvalidOperation
1314 if self._isinfinity():
1315 return context._raise_error(InvalidOperation,
1316 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001317
Facundo Batista353750c2007-09-13 18:13:15 +00001318 # other == 0 -> either InvalidOperation or DivisionUndefined
1319 if not other:
1320 if self:
1321 return context._raise_error(InvalidOperation,
1322 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001323 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001324 return context._raise_error(DivisionUndefined,
1325 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001326
Facundo Batista353750c2007-09-13 18:13:15 +00001327 # other = +/-infinity -> remainder = self
1328 if other._isinfinity():
1329 ans = Decimal(self)
1330 return ans._fix(context)
1331
1332 # self = 0 -> remainder = self, with ideal exponent
1333 ideal_exponent = min(self._exp, other._exp)
1334 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001335 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001336 return ans._fix(context)
1337
1338 # catch most cases of large or small quotient
1339 expdiff = self.adjusted() - other.adjusted()
1340 if expdiff >= context.prec + 1:
1341 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001342 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001343 if expdiff <= -2:
1344 # expdiff <= -2 => abs(self/other) < 0.1
1345 ans = self._rescale(ideal_exponent, context.rounding)
1346 return ans._fix(context)
1347
1348 # adjust both arguments to have the same exponent, then divide
1349 op1 = _WorkRep(self)
1350 op2 = _WorkRep(other)
1351 if op1.exp >= op2.exp:
1352 op1.int *= 10**(op1.exp - op2.exp)
1353 else:
1354 op2.int *= 10**(op2.exp - op1.exp)
1355 q, r = divmod(op1.int, op2.int)
1356 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1357 # 10**ideal_exponent. Apply correction to ensure that
1358 # abs(remainder) <= abs(other)/2
1359 if 2*r + (q&1) > op2.int:
1360 r -= op2.int
1361 q += 1
1362
1363 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001364 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001365
1366 # result has same sign as self unless r is negative
1367 sign = self._sign
1368 if r < 0:
1369 sign = 1-sign
1370 r = -r
1371
Facundo Batista72bc54f2007-11-23 17:59:00 +00001372 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001373 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001374
1375 def __floordiv__(self, other, context=None):
1376 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001377 other = _convert_other(other)
1378 if other is NotImplemented:
1379 return other
1380
1381 if context is None:
1382 context = getcontext()
1383
1384 ans = self._check_nans(other, context)
1385 if ans:
1386 return ans
1387
1388 if self._isinfinity():
1389 if other._isinfinity():
1390 return context._raise_error(InvalidOperation, 'INF // INF')
1391 else:
1392 return Infsign[self._sign ^ other._sign]
1393
1394 if not other:
1395 if self:
1396 return context._raise_error(DivisionByZero, 'x // 0',
1397 self._sign ^ other._sign)
1398 else:
1399 return context._raise_error(DivisionUndefined, '0 // 0')
1400
1401 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001402
1403 def __rfloordiv__(self, other, context=None):
1404 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001405 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001406 if other is NotImplemented:
1407 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001408 return other.__floordiv__(self, context=context)
1409
1410 def __float__(self):
1411 """Float representation."""
1412 return float(str(self))
1413
1414 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001415 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001416 if self._is_special:
1417 if self._isnan():
1418 context = getcontext()
1419 return context._raise_error(InvalidContext)
1420 elif self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001421 raise OverflowError("Cannot convert infinity to long")
Facundo Batista353750c2007-09-13 18:13:15 +00001422 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001423 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001424 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001425 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001426 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001427
1428 def __long__(self):
1429 """Converts to a long.
1430
1431 Equivalent to long(int(self))
1432 """
1433 return long(self.__int__())
1434
Facundo Batista353750c2007-09-13 18:13:15 +00001435 def _fix_nan(self, context):
1436 """Decapitate the payload of a NaN to fit the context"""
1437 payload = self._int
1438
1439 # maximum length of payload is precision if _clamp=0,
1440 # precision-1 if _clamp=1.
1441 max_payload_len = context.prec - context._clamp
1442 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001443 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1444 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001445 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001446
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001447 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001448 """Round if it is necessary to keep self within prec precision.
1449
1450 Rounds and fixes the exponent. Does not raise on a sNaN.
1451
1452 Arguments:
1453 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001454 context - context used.
1455 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001456
Facundo Batista353750c2007-09-13 18:13:15 +00001457 if self._is_special:
1458 if self._isnan():
1459 # decapitate payload if necessary
1460 return self._fix_nan(context)
1461 else:
1462 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001463 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001464
Facundo Batista353750c2007-09-13 18:13:15 +00001465 # if self is zero then exponent should be between Etiny and
1466 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1467 Etiny = context.Etiny()
1468 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001469 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001470 exp_max = [context.Emax, Etop][context._clamp]
1471 new_exp = min(max(self._exp, Etiny), exp_max)
1472 if new_exp != self._exp:
1473 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001474 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001475 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001476 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001477
1478 # exp_min is the smallest allowable exponent of the result,
1479 # equal to max(self.adjusted()-context.prec+1, Etiny)
1480 exp_min = len(self._int) + self._exp - context.prec
1481 if exp_min > Etop:
1482 # overflow: exp_min > Etop iff self.adjusted() > Emax
1483 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001484 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001485 return context._raise_error(Overflow, 'above Emax', self._sign)
1486 self_is_subnormal = exp_min < Etiny
1487 if self_is_subnormal:
1488 context._raise_error(Subnormal)
1489 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001490
Facundo Batista353750c2007-09-13 18:13:15 +00001491 # round if self has too many digits
1492 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001493 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001494 digits = len(self._int) + self._exp - exp_min
1495 if digits < 0:
1496 self = _dec_from_triple(self._sign, '1', exp_min-1)
1497 digits = 0
1498 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1499 changed = this_function(digits)
1500 coeff = self._int[:digits] or '0'
1501 if changed == 1:
1502 coeff = str(int(coeff)+1)
1503 ans = _dec_from_triple(self._sign, coeff, exp_min)
1504
1505 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001506 context._raise_error(Inexact)
1507 if self_is_subnormal:
1508 context._raise_error(Underflow)
1509 if not ans:
1510 # raise Clamped on underflow to 0
1511 context._raise_error(Clamped)
1512 elif len(ans._int) == context.prec+1:
1513 # we get here only if rescaling rounds the
1514 # cofficient up to exactly 10**context.prec
1515 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001516 ans = _dec_from_triple(ans._sign,
1517 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001518 else:
1519 # Inexact and Rounded have already been raised
1520 ans = context._raise_error(Overflow, 'above Emax',
1521 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001522 return ans
1523
Facundo Batista353750c2007-09-13 18:13:15 +00001524 # fold down if _clamp == 1 and self has too few digits
1525 if context._clamp == 1 and self._exp > Etop:
1526 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001527 self_padded = self._int + '0'*(self._exp - Etop)
1528 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001529
Facundo Batista353750c2007-09-13 18:13:15 +00001530 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001531 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001532
1533 _pick_rounding_function = {}
1534
Facundo Batista353750c2007-09-13 18:13:15 +00001535 # for each of the rounding functions below:
1536 # self is a finite, nonzero Decimal
1537 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001538 #
1539 # each function returns either -1, 0, or 1, as follows:
1540 # 1 indicates that self should be rounded up (away from zero)
1541 # 0 indicates that self should be truncated, and that all the
1542 # digits to be truncated are zeros (so the value is unchanged)
1543 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001544
1545 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001546 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001547 if _all_zeros(self._int, prec):
1548 return 0
1549 else:
1550 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001551
Facundo Batista353750c2007-09-13 18:13:15 +00001552 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001553 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001554 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001555
Facundo Batista353750c2007-09-13 18:13:15 +00001556 def _round_half_up(self, prec):
1557 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001558 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001559 return 1
1560 elif _all_zeros(self._int, prec):
1561 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001562 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001563 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001564
1565 def _round_half_down(self, prec):
1566 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001567 if _exact_half(self._int, prec):
1568 return -1
1569 else:
1570 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001571
1572 def _round_half_even(self, prec):
1573 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001574 if _exact_half(self._int, prec) and \
1575 (prec == 0 or self._int[prec-1] in '02468'):
1576 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001577 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001578 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001579
1580 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001581 """Rounds up (not away from 0 if negative.)"""
1582 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001583 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001584 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001585 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001586
Facundo Batista353750c2007-09-13 18:13:15 +00001587 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001588 """Rounds down (not towards 0 if negative)"""
1589 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001590 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001591 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001592 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001593
Facundo Batista353750c2007-09-13 18:13:15 +00001594 def _round_05up(self, prec):
1595 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001596 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001597 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001598 else:
1599 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001600
Facundo Batista353750c2007-09-13 18:13:15 +00001601 def fma(self, other, third, context=None):
1602 """Fused multiply-add.
1603
1604 Returns self*other+third with no rounding of the intermediate
1605 product self*other.
1606
1607 self and other are multiplied together, with no rounding of
1608 the result. The third operand is then added to the result,
1609 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001610 """
Facundo Batista353750c2007-09-13 18:13:15 +00001611
1612 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001613
1614 # compute product; raise InvalidOperation if either operand is
1615 # a signaling NaN or if the product is zero times infinity.
1616 if self._is_special or other._is_special:
1617 if context is None:
1618 context = getcontext()
1619 if self._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001620 return context._raise_error(InvalidOperation, 'sNaN', self)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001621 if other._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001622 return context._raise_error(InvalidOperation, 'sNaN', other)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001623 if self._exp == 'n':
1624 product = self
1625 elif other._exp == 'n':
1626 product = other
1627 elif self._exp == 'F':
1628 if not other:
1629 return context._raise_error(InvalidOperation,
1630 'INF * 0 in fma')
1631 product = Infsign[self._sign ^ other._sign]
1632 elif other._exp == 'F':
1633 if not self:
1634 return context._raise_error(InvalidOperation,
1635 '0 * INF in fma')
1636 product = Infsign[self._sign ^ other._sign]
1637 else:
1638 product = _dec_from_triple(self._sign ^ other._sign,
1639 str(int(self._int) * int(other._int)),
1640 self._exp + other._exp)
1641
Facundo Batista353750c2007-09-13 18:13:15 +00001642 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001643 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001644
Facundo Batista353750c2007-09-13 18:13:15 +00001645 def _power_modulo(self, other, modulo, context=None):
1646 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001647
Facundo Batista353750c2007-09-13 18:13:15 +00001648 # if can't convert other and modulo to Decimal, raise
1649 # TypeError; there's no point returning NotImplemented (no
1650 # equivalent of __rpow__ for three argument pow)
1651 other = _convert_other(other, raiseit=True)
1652 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001653
Facundo Batista353750c2007-09-13 18:13:15 +00001654 if context is None:
1655 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001656
Facundo Batista353750c2007-09-13 18:13:15 +00001657 # deal with NaNs: if there are any sNaNs then first one wins,
1658 # (i.e. behaviour for NaNs is identical to that of fma)
1659 self_is_nan = self._isnan()
1660 other_is_nan = other._isnan()
1661 modulo_is_nan = modulo._isnan()
1662 if self_is_nan or other_is_nan or modulo_is_nan:
1663 if self_is_nan == 2:
1664 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001665 self)
Facundo Batista353750c2007-09-13 18:13:15 +00001666 if other_is_nan == 2:
1667 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001668 other)
Facundo Batista353750c2007-09-13 18:13:15 +00001669 if modulo_is_nan == 2:
1670 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001671 modulo)
Facundo Batista353750c2007-09-13 18:13:15 +00001672 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001673 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001674 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001675 return other._fix_nan(context)
1676 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001677
Facundo Batista353750c2007-09-13 18:13:15 +00001678 # check inputs: we apply same restrictions as Python's pow()
1679 if not (self._isinteger() and
1680 other._isinteger() and
1681 modulo._isinteger()):
1682 return context._raise_error(InvalidOperation,
1683 'pow() 3rd argument not allowed '
1684 'unless all arguments are integers')
1685 if other < 0:
1686 return context._raise_error(InvalidOperation,
1687 'pow() 2nd argument cannot be '
1688 'negative when 3rd argument specified')
1689 if not modulo:
1690 return context._raise_error(InvalidOperation,
1691 'pow() 3rd argument cannot be 0')
1692
1693 # additional restriction for decimal: the modulus must be less
1694 # than 10**prec in absolute value
1695 if modulo.adjusted() >= context.prec:
1696 return context._raise_error(InvalidOperation,
1697 'insufficient precision: pow() 3rd '
1698 'argument must not have more than '
1699 'precision digits')
1700
1701 # define 0**0 == NaN, for consistency with two-argument pow
1702 # (even though it hurts!)
1703 if not other and not self:
1704 return context._raise_error(InvalidOperation,
1705 'at least one of pow() 1st argument '
1706 'and 2nd argument must be nonzero ;'
1707 '0**0 is not defined')
1708
1709 # compute sign of result
1710 if other._iseven():
1711 sign = 0
1712 else:
1713 sign = self._sign
1714
1715 # convert modulo to a Python integer, and self and other to
1716 # Decimal integers (i.e. force their exponents to be >= 0)
1717 modulo = abs(int(modulo))
1718 base = _WorkRep(self.to_integral_value())
1719 exponent = _WorkRep(other.to_integral_value())
1720
1721 # compute result using integer pow()
1722 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1723 for i in xrange(exponent.exp):
1724 base = pow(base, 10, modulo)
1725 base = pow(base, exponent.int, modulo)
1726
Facundo Batista72bc54f2007-11-23 17:59:00 +00001727 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001728
1729 def _power_exact(self, other, p):
1730 """Attempt to compute self**other exactly.
1731
1732 Given Decimals self and other and an integer p, attempt to
1733 compute an exact result for the power self**other, with p
1734 digits of precision. Return None if self**other is not
1735 exactly representable in p digits.
1736
1737 Assumes that elimination of special cases has already been
1738 performed: self and other must both be nonspecial; self must
1739 be positive and not numerically equal to 1; other must be
1740 nonzero. For efficiency, other._exp should not be too large,
1741 so that 10**abs(other._exp) is a feasible calculation."""
1742
1743 # In the comments below, we write x for the value of self and
1744 # y for the value of other. Write x = xc*10**xe and y =
1745 # yc*10**ye.
1746
1747 # The main purpose of this method is to identify the *failure*
1748 # of x**y to be exactly representable with as little effort as
1749 # possible. So we look for cheap and easy tests that
1750 # eliminate the possibility of x**y being exact. Only if all
1751 # these tests are passed do we go on to actually compute x**y.
1752
1753 # Here's the main idea. First normalize both x and y. We
1754 # express y as a rational m/n, with m and n relatively prime
1755 # and n>0. Then for x**y to be exactly representable (at
1756 # *any* precision), xc must be the nth power of a positive
1757 # integer and xe must be divisible by n. If m is negative
1758 # then additionally xc must be a power of either 2 or 5, hence
1759 # a power of 2**n or 5**n.
1760 #
1761 # There's a limit to how small |y| can be: if y=m/n as above
1762 # then:
1763 #
1764 # (1) if xc != 1 then for the result to be representable we
1765 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1766 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1767 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1768 # representable.
1769 #
1770 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1771 # |y| < 1/|xe| then the result is not representable.
1772 #
1773 # Note that since x is not equal to 1, at least one of (1) and
1774 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1775 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1776 #
1777 # There's also a limit to how large y can be, at least if it's
1778 # positive: the normalized result will have coefficient xc**y,
1779 # so if it's representable then xc**y < 10**p, and y <
1780 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1781 # not exactly representable.
1782
1783 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1784 # so |y| < 1/xe and the result is not representable.
1785 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1786 # < 1/nbits(xc).
1787
1788 x = _WorkRep(self)
1789 xc, xe = x.int, x.exp
1790 while xc % 10 == 0:
1791 xc //= 10
1792 xe += 1
1793
1794 y = _WorkRep(other)
1795 yc, ye = y.int, y.exp
1796 while yc % 10 == 0:
1797 yc //= 10
1798 ye += 1
1799
1800 # case where xc == 1: result is 10**(xe*y), with xe*y
1801 # required to be an integer
1802 if xc == 1:
1803 if ye >= 0:
1804 exponent = xe*yc*10**ye
1805 else:
1806 exponent, remainder = divmod(xe*yc, 10**-ye)
1807 if remainder:
1808 return None
1809 if y.sign == 1:
1810 exponent = -exponent
1811 # if other is a nonnegative integer, use ideal exponent
1812 if other._isinteger() and other._sign == 0:
1813 ideal_exponent = self._exp*int(other)
1814 zeros = min(exponent-ideal_exponent, p-1)
1815 else:
1816 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001817 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001818
1819 # case where y is negative: xc must be either a power
1820 # of 2 or a power of 5.
1821 if y.sign == 1:
1822 last_digit = xc % 10
1823 if last_digit in (2,4,6,8):
1824 # quick test for power of 2
1825 if xc & -xc != xc:
1826 return None
1827 # now xc is a power of 2; e is its exponent
1828 e = _nbits(xc)-1
1829 # find e*y and xe*y; both must be integers
1830 if ye >= 0:
1831 y_as_int = yc*10**ye
1832 e = e*y_as_int
1833 xe = xe*y_as_int
1834 else:
1835 ten_pow = 10**-ye
1836 e, remainder = divmod(e*yc, ten_pow)
1837 if remainder:
1838 return None
1839 xe, remainder = divmod(xe*yc, ten_pow)
1840 if remainder:
1841 return None
1842
1843 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1844 return None
1845 xc = 5**e
1846
1847 elif last_digit == 5:
1848 # e >= log_5(xc) if xc is a power of 5; we have
1849 # equality all the way up to xc=5**2658
1850 e = _nbits(xc)*28//65
1851 xc, remainder = divmod(5**e, xc)
1852 if remainder:
1853 return None
1854 while xc % 5 == 0:
1855 xc //= 5
1856 e -= 1
1857 if ye >= 0:
1858 y_as_integer = yc*10**ye
1859 e = e*y_as_integer
1860 xe = xe*y_as_integer
1861 else:
1862 ten_pow = 10**-ye
1863 e, remainder = divmod(e*yc, ten_pow)
1864 if remainder:
1865 return None
1866 xe, remainder = divmod(xe*yc, ten_pow)
1867 if remainder:
1868 return None
1869 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1870 return None
1871 xc = 2**e
1872 else:
1873 return None
1874
1875 if xc >= 10**p:
1876 return None
1877 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00001878 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00001879
1880 # now y is positive; find m and n such that y = m/n
1881 if ye >= 0:
1882 m, n = yc*10**ye, 1
1883 else:
1884 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1885 return None
1886 xc_bits = _nbits(xc)
1887 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1888 return None
1889 m, n = yc, 10**(-ye)
1890 while m % 2 == n % 2 == 0:
1891 m //= 2
1892 n //= 2
1893 while m % 5 == n % 5 == 0:
1894 m //= 5
1895 n //= 5
1896
1897 # compute nth root of xc*10**xe
1898 if n > 1:
1899 # if 1 < xc < 2**n then xc isn't an nth power
1900 if xc != 1 and xc_bits <= n:
1901 return None
1902
1903 xe, rem = divmod(xe, n)
1904 if rem != 0:
1905 return None
1906
1907 # compute nth root of xc using Newton's method
1908 a = 1L << -(-_nbits(xc)//n) # initial estimate
1909 while True:
1910 q, r = divmod(xc, a**(n-1))
1911 if a <= q:
1912 break
1913 else:
1914 a = (a*(n-1) + q)//n
1915 if not (a == q and r == 0):
1916 return None
1917 xc = a
1918
1919 # now xc*10**xe is the nth root of the original xc*10**xe
1920 # compute mth power of xc*10**xe
1921
1922 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1923 # 10**p and the result is not representable.
1924 if xc > 1 and m > p*100//_log10_lb(xc):
1925 return None
1926 xc = xc**m
1927 xe *= m
1928 if xc > 10**p:
1929 return None
1930
1931 # by this point the result *is* exactly representable
1932 # adjust the exponent to get as close as possible to the ideal
1933 # exponent, if necessary
1934 str_xc = str(xc)
1935 if other._isinteger() and other._sign == 0:
1936 ideal_exponent = self._exp*int(other)
1937 zeros = min(xe-ideal_exponent, p-len(str_xc))
1938 else:
1939 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001940 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001941
1942 def __pow__(self, other, modulo=None, context=None):
1943 """Return self ** other [ % modulo].
1944
1945 With two arguments, compute self**other.
1946
1947 With three arguments, compute (self**other) % modulo. For the
1948 three argument form, the following restrictions on the
1949 arguments hold:
1950
1951 - all three arguments must be integral
1952 - other must be nonnegative
1953 - either self or other (or both) must be nonzero
1954 - modulo must be nonzero and must have at most p digits,
1955 where p is the context precision.
1956
1957 If any of these restrictions is violated the InvalidOperation
1958 flag is raised.
1959
1960 The result of pow(self, other, modulo) is identical to the
1961 result that would be obtained by computing (self**other) %
1962 modulo with unbounded precision, but is computed more
1963 efficiently. It is always exact.
1964 """
1965
1966 if modulo is not None:
1967 return self._power_modulo(other, modulo, context)
1968
1969 other = _convert_other(other)
1970 if other is NotImplemented:
1971 return other
1972
1973 if context is None:
1974 context = getcontext()
1975
1976 # either argument is a NaN => result is NaN
1977 ans = self._check_nans(other, context)
1978 if ans:
1979 return ans
1980
1981 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1982 if not other:
1983 if not self:
1984 return context._raise_error(InvalidOperation, '0 ** 0')
1985 else:
1986 return Dec_p1
1987
1988 # result has sign 1 iff self._sign is 1 and other is an odd integer
1989 result_sign = 0
1990 if self._sign == 1:
1991 if other._isinteger():
1992 if not other._iseven():
1993 result_sign = 1
1994 else:
1995 # -ve**noninteger = NaN
1996 # (-0)**noninteger = 0**noninteger
1997 if self:
1998 return context._raise_error(InvalidOperation,
1999 'x ** y with x negative and y not an integer')
2000 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002001 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002002
2003 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2004 if not self:
2005 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002006 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002007 else:
2008 return Infsign[result_sign]
2009
2010 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002011 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002012 if other._sign == 0:
2013 return Infsign[result_sign]
2014 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002015 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002016
Facundo Batista353750c2007-09-13 18:13:15 +00002017 # 1**other = 1, but the choice of exponent and the flags
2018 # depend on the exponent of self, and on whether other is a
2019 # positive integer, a negative integer, or neither
2020 if self == Dec_p1:
2021 if other._isinteger():
2022 # exp = max(self._exp*max(int(other), 0),
2023 # 1-context.prec) but evaluating int(other) directly
2024 # is dangerous until we know other is small (other
2025 # could be 1e999999999)
2026 if other._sign == 1:
2027 multiplier = 0
2028 elif other > context.prec:
2029 multiplier = context.prec
2030 else:
2031 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002032
Facundo Batista353750c2007-09-13 18:13:15 +00002033 exp = self._exp * multiplier
2034 if exp < 1-context.prec:
2035 exp = 1-context.prec
2036 context._raise_error(Rounded)
2037 else:
2038 context._raise_error(Inexact)
2039 context._raise_error(Rounded)
2040 exp = 1-context.prec
2041
Facundo Batista72bc54f2007-11-23 17:59:00 +00002042 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002043
2044 # compute adjusted exponent of self
2045 self_adj = self.adjusted()
2046
2047 # self ** infinity is infinity if self > 1, 0 if self < 1
2048 # self ** -infinity is infinity if self < 1, 0 if self > 1
2049 if other._isinfinity():
2050 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002051 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002052 else:
2053 return Infsign[result_sign]
2054
2055 # from here on, the result always goes through the call
2056 # to _fix at the end of this function.
2057 ans = None
2058
2059 # crude test to catch cases of extreme overflow/underflow. If
2060 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2061 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2062 # self**other >= 10**(Emax+1), so overflow occurs. The test
2063 # for underflow is similar.
2064 bound = self._log10_exp_bound() + other.adjusted()
2065 if (self_adj >= 0) == (other._sign == 0):
2066 # self > 1 and other +ve, or self < 1 and other -ve
2067 # possibility of overflow
2068 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002069 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002070 else:
2071 # self > 1 and other -ve, or self < 1 and other +ve
2072 # possibility of underflow to 0
2073 Etiny = context.Etiny()
2074 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002075 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002076
2077 # try for an exact result with precision +1
2078 if ans is None:
2079 ans = self._power_exact(other, context.prec + 1)
2080 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002081 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002082
2083 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2084 if ans is None:
2085 p = context.prec
2086 x = _WorkRep(self)
2087 xc, xe = x.int, x.exp
2088 y = _WorkRep(other)
2089 yc, ye = y.int, y.exp
2090 if y.sign == 1:
2091 yc = -yc
2092
2093 # compute correctly rounded result: start with precision +3,
2094 # then increase precision until result is unambiguously roundable
2095 extra = 3
2096 while True:
2097 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2098 if coeff % (5*10**(len(str(coeff))-p-1)):
2099 break
2100 extra += 3
2101
Facundo Batista72bc54f2007-11-23 17:59:00 +00002102 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002103
2104 # the specification says that for non-integer other we need to
2105 # raise Inexact, even when the result is actually exact. In
2106 # the same way, we need to raise Underflow here if the result
2107 # is subnormal. (The call to _fix will take care of raising
2108 # Rounded and Subnormal, as usual.)
2109 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002110 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002111 # pad with zeros up to length context.prec+1 if necessary
2112 if len(ans._int) <= context.prec:
2113 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002114 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2115 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002116 if ans.adjusted() < context.Emin:
2117 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002118
Facundo Batista353750c2007-09-13 18:13:15 +00002119 # unlike exp, ln and log10, the power function respects the
2120 # rounding mode; no need to use ROUND_HALF_EVEN here
2121 ans = ans._fix(context)
2122 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002123
2124 def __rpow__(self, other, context=None):
2125 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002126 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002127 if other is NotImplemented:
2128 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002129 return other.__pow__(self, context=context)
2130
2131 def normalize(self, context=None):
2132 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002133
Facundo Batista353750c2007-09-13 18:13:15 +00002134 if context is None:
2135 context = getcontext()
2136
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002137 if self._is_special:
2138 ans = self._check_nans(context=context)
2139 if ans:
2140 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002141
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002142 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002143 if dup._isinfinity():
2144 return dup
2145
2146 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002147 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002148 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002149 end = len(dup._int)
2150 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002151 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002152 exp += 1
2153 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002154 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002155
Facundo Batistabd2fe832007-09-13 18:42:09 +00002156 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002157 """Quantize self so its exponent is the same as that of exp.
2158
2159 Similar to self._rescale(exp._exp) but with error checking.
2160 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002161 exp = _convert_other(exp, raiseit=True)
2162
Facundo Batista353750c2007-09-13 18:13:15 +00002163 if context is None:
2164 context = getcontext()
2165 if rounding is None:
2166 rounding = context.rounding
2167
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002168 if self._is_special or exp._is_special:
2169 ans = self._check_nans(exp, context)
2170 if ans:
2171 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002172
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002173 if exp._isinfinity() or self._isinfinity():
2174 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002175 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002176 return context._raise_error(InvalidOperation,
2177 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002178
Facundo Batistabd2fe832007-09-13 18:42:09 +00002179 # if we're not watching exponents, do a simple rescale
2180 if not watchexp:
2181 ans = self._rescale(exp._exp, rounding)
2182 # raise Inexact and Rounded where appropriate
2183 if ans._exp > self._exp:
2184 context._raise_error(Rounded)
2185 if ans != self:
2186 context._raise_error(Inexact)
2187 return ans
2188
Facundo Batista353750c2007-09-13 18:13:15 +00002189 # exp._exp should be between Etiny and Emax
2190 if not (context.Etiny() <= exp._exp <= context.Emax):
2191 return context._raise_error(InvalidOperation,
2192 'target exponent out of bounds in quantize')
2193
2194 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002195 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002196 return ans._fix(context)
2197
2198 self_adjusted = self.adjusted()
2199 if self_adjusted > context.Emax:
2200 return context._raise_error(InvalidOperation,
2201 'exponent of quantize result too large for current context')
2202 if self_adjusted - exp._exp + 1 > context.prec:
2203 return context._raise_error(InvalidOperation,
2204 'quantize result has too many digits for current context')
2205
2206 ans = self._rescale(exp._exp, rounding)
2207 if ans.adjusted() > context.Emax:
2208 return context._raise_error(InvalidOperation,
2209 'exponent of quantize result too large for current context')
2210 if len(ans._int) > context.prec:
2211 return context._raise_error(InvalidOperation,
2212 'quantize result has too many digits for current context')
2213
2214 # raise appropriate flags
2215 if ans._exp > self._exp:
2216 context._raise_error(Rounded)
2217 if ans != self:
2218 context._raise_error(Inexact)
2219 if ans and ans.adjusted() < context.Emin:
2220 context._raise_error(Subnormal)
2221
2222 # call to fix takes care of any necessary folddown
2223 ans = ans._fix(context)
2224 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002225
2226 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002227 """Return True if self and other have the same exponent; otherwise
2228 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002229
Facundo Batista1a191df2007-10-02 17:01:24 +00002230 If either operand is a special value, the following rules are used:
2231 * return True if both operands are infinities
2232 * return True if both operands are NaNs
2233 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002234 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002235 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002236 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002237 return (self.is_nan() and other.is_nan() or
2238 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002239 return self._exp == other._exp
2240
Facundo Batista353750c2007-09-13 18:13:15 +00002241 def _rescale(self, exp, rounding):
2242 """Rescale self so that the exponent is exp, either by padding with zeros
2243 or by truncating digits, using the given rounding mode.
2244
2245 Specials are returned without change. This operation is
2246 quiet: it raises no flags, and uses no information from the
2247 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002248
2249 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002250 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002251 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002252 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002253 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002254 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002255 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002256
Facundo Batista353750c2007-09-13 18:13:15 +00002257 if self._exp >= exp:
2258 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002259 return _dec_from_triple(self._sign,
2260 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002261
Facundo Batista353750c2007-09-13 18:13:15 +00002262 # too many digits; round and lose data. If self.adjusted() <
2263 # exp-1, replace self by 10**(exp-1) before rounding
2264 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002265 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002266 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002267 digits = 0
2268 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002269 changed = this_function(digits)
2270 coeff = self._int[:digits] or '0'
2271 if changed == 1:
2272 coeff = str(int(coeff)+1)
2273 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002274
Facundo Batista353750c2007-09-13 18:13:15 +00002275 def to_integral_exact(self, rounding=None, context=None):
2276 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002277
Facundo Batista353750c2007-09-13 18:13:15 +00002278 If no rounding mode is specified, take the rounding mode from
2279 the context. This method raises the Rounded and Inexact flags
2280 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002281
Facundo Batista353750c2007-09-13 18:13:15 +00002282 See also: to_integral_value, which does exactly the same as
2283 this method except that it doesn't raise Inexact or Rounded.
2284 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002285 if self._is_special:
2286 ans = self._check_nans(context=context)
2287 if ans:
2288 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002289 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002290 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002291 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002292 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002293 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002294 if context is None:
2295 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002296 if rounding is None:
2297 rounding = context.rounding
2298 context._raise_error(Rounded)
2299 ans = self._rescale(0, rounding)
2300 if ans != self:
2301 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002302 return ans
2303
Facundo Batista353750c2007-09-13 18:13:15 +00002304 def to_integral_value(self, rounding=None, context=None):
2305 """Rounds to the nearest integer, without raising inexact, rounded."""
2306 if context is None:
2307 context = getcontext()
2308 if rounding is None:
2309 rounding = context.rounding
2310 if self._is_special:
2311 ans = self._check_nans(context=context)
2312 if ans:
2313 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002314 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002315 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002316 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002317 else:
2318 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002319
Facundo Batista353750c2007-09-13 18:13:15 +00002320 # the method name changed, but we provide also the old one, for compatibility
2321 to_integral = to_integral_value
2322
2323 def sqrt(self, context=None):
2324 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002325 if self._is_special:
2326 ans = self._check_nans(context=context)
2327 if ans:
2328 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002329
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002330 if self._isinfinity() and self._sign == 0:
2331 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002332
2333 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002334 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002335 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002336 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002337
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002338 if context is None:
2339 context = getcontext()
2340
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002341 if self._sign == 1:
2342 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2343
Facundo Batista353750c2007-09-13 18:13:15 +00002344 # At this point self represents a positive number. Let p be
2345 # the desired precision and express self in the form c*100**e
2346 # with c a positive real number and e an integer, c and e
2347 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2348 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2349 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2350 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2351 # the closest integer to sqrt(c) with the even integer chosen
2352 # in the case of a tie.
2353 #
2354 # To ensure correct rounding in all cases, we use the
2355 # following trick: we compute the square root to an extra
2356 # place (precision p+1 instead of precision p), rounding down.
2357 # Then, if the result is inexact and its last digit is 0 or 5,
2358 # we increase the last digit to 1 or 6 respectively; if it's
2359 # exact we leave the last digit alone. Now the final round to
2360 # p places (or fewer in the case of underflow) will round
2361 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002362
Facundo Batista353750c2007-09-13 18:13:15 +00002363 # use an extra digit of precision
2364 prec = context.prec+1
2365
2366 # write argument in the form c*100**e where e = self._exp//2
2367 # is the 'ideal' exponent, to be used if the square root is
2368 # exactly representable. l is the number of 'digits' of c in
2369 # base 100, so that 100**(l-1) <= c < 100**l.
2370 op = _WorkRep(self)
2371 e = op.exp >> 1
2372 if op.exp & 1:
2373 c = op.int * 10
2374 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002375 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002376 c = op.int
2377 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002378
Facundo Batista353750c2007-09-13 18:13:15 +00002379 # rescale so that c has exactly prec base 100 'digits'
2380 shift = prec-l
2381 if shift >= 0:
2382 c *= 100**shift
2383 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002384 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002385 c, remainder = divmod(c, 100**-shift)
2386 exact = not remainder
2387 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002388
Facundo Batista353750c2007-09-13 18:13:15 +00002389 # find n = floor(sqrt(c)) using Newton's method
2390 n = 10**prec
2391 while True:
2392 q = c//n
2393 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002394 break
Facundo Batista353750c2007-09-13 18:13:15 +00002395 else:
2396 n = n + q >> 1
2397 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002398
Facundo Batista353750c2007-09-13 18:13:15 +00002399 if exact:
2400 # result is exact; rescale to use ideal exponent e
2401 if shift >= 0:
2402 # assert n % 10**shift == 0
2403 n //= 10**shift
2404 else:
2405 n *= 10**-shift
2406 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002407 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002408 # result is not exact; fix last digit as described above
2409 if n % 5 == 0:
2410 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002411
Facundo Batista72bc54f2007-11-23 17:59:00 +00002412 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002413
Facundo Batista353750c2007-09-13 18:13:15 +00002414 # round, and fit to current context
2415 context = context._shallow_copy()
2416 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002417 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002418 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002419
Facundo Batista353750c2007-09-13 18:13:15 +00002420 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002421
2422 def max(self, other, context=None):
2423 """Returns the larger value.
2424
Facundo Batista353750c2007-09-13 18:13:15 +00002425 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002426 NaN (and signals if one is sNaN). Also rounds.
2427 """
Facundo Batista353750c2007-09-13 18:13:15 +00002428 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002429
Facundo Batista6c398da2007-09-17 17:30:13 +00002430 if context is None:
2431 context = getcontext()
2432
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002433 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002434 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002435 # number is always returned
2436 sn = self._isnan()
2437 on = other._isnan()
2438 if sn or on:
2439 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002440 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002441 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002442 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002443 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002444
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002445 c = self.__cmp__(other)
2446 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002447 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002448 # then an ordering is applied:
2449 #
Facundo Batista59c58842007-04-10 12:58:45 +00002450 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002451 # positive sign and min returns the operand with the negative sign
2452 #
Facundo Batista59c58842007-04-10 12:58:45 +00002453 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002454 # the result. This is exactly the ordering used in compare_total.
2455 c = self.compare_total(other)
2456
2457 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002458 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002459 else:
2460 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002461
Facundo Batistae64acfa2007-12-17 14:18:42 +00002462 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002463
2464 def min(self, other, context=None):
2465 """Returns the smaller value.
2466
Facundo Batista59c58842007-04-10 12:58:45 +00002467 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002468 NaN (and signals if one is sNaN). Also rounds.
2469 """
Facundo Batista353750c2007-09-13 18:13:15 +00002470 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002471
Facundo Batista6c398da2007-09-17 17:30:13 +00002472 if context is None:
2473 context = getcontext()
2474
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002475 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002476 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002477 # number is always returned
2478 sn = self._isnan()
2479 on = other._isnan()
2480 if sn or on:
2481 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002482 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002483 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002484 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002485 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002486
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002487 c = self.__cmp__(other)
2488 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002489 c = self.compare_total(other)
2490
2491 if c == -1:
2492 ans = self
2493 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002494 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002495
Facundo Batistae64acfa2007-12-17 14:18:42 +00002496 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002497
2498 def _isinteger(self):
2499 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002500 if self._is_special:
2501 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002502 if self._exp >= 0:
2503 return True
2504 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002505 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002506
2507 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002508 """Returns True if self is even. Assumes self is an integer."""
2509 if not self or self._exp > 0:
2510 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002511 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002512
2513 def adjusted(self):
2514 """Return the adjusted exponent of self"""
2515 try:
2516 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002517 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002518 except TypeError:
2519 return 0
2520
Facundo Batista353750c2007-09-13 18:13:15 +00002521 def canonical(self, context=None):
2522 """Returns the same Decimal object.
2523
2524 As we do not have different encodings for the same number, the
2525 received object already is in its canonical form.
2526 """
2527 return self
2528
2529 def compare_signal(self, other, context=None):
2530 """Compares self to the other operand numerically.
2531
2532 It's pretty much like compare(), but all NaNs signal, with signaling
2533 NaNs taking precedence over quiet NaNs.
2534 """
2535 if context is None:
2536 context = getcontext()
2537
2538 self_is_nan = self._isnan()
2539 other_is_nan = other._isnan()
2540 if self_is_nan == 2:
2541 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002542 self)
Facundo Batista353750c2007-09-13 18:13:15 +00002543 if other_is_nan == 2:
2544 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002545 other)
Facundo Batista353750c2007-09-13 18:13:15 +00002546 if self_is_nan:
2547 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002548 self)
Facundo Batista353750c2007-09-13 18:13:15 +00002549 if other_is_nan:
2550 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00002551 other)
Facundo Batista353750c2007-09-13 18:13:15 +00002552 return self.compare(other, context=context)
2553
2554 def compare_total(self, other):
2555 """Compares self to other using the abstract representations.
2556
2557 This is not like the standard compare, which use their numerical
2558 value. Note that a total ordering is defined for all possible abstract
2559 representations.
2560 """
2561 # if one is negative and the other is positive, it's easy
2562 if self._sign and not other._sign:
2563 return Dec_n1
2564 if not self._sign and other._sign:
2565 return Dec_p1
2566 sign = self._sign
2567
2568 # let's handle both NaN types
2569 self_nan = self._isnan()
2570 other_nan = other._isnan()
2571 if self_nan or other_nan:
2572 if self_nan == other_nan:
2573 if self._int < other._int:
2574 if sign:
2575 return Dec_p1
2576 else:
2577 return Dec_n1
2578 if self._int > other._int:
2579 if sign:
2580 return Dec_n1
2581 else:
2582 return Dec_p1
2583 return Dec_0
2584
2585 if sign:
2586 if self_nan == 1:
2587 return Dec_n1
2588 if other_nan == 1:
2589 return Dec_p1
2590 if self_nan == 2:
2591 return Dec_n1
2592 if other_nan == 2:
2593 return Dec_p1
2594 else:
2595 if self_nan == 1:
2596 return Dec_p1
2597 if other_nan == 1:
2598 return Dec_n1
2599 if self_nan == 2:
2600 return Dec_p1
2601 if other_nan == 2:
2602 return Dec_n1
2603
2604 if self < other:
2605 return Dec_n1
2606 if self > other:
2607 return Dec_p1
2608
2609 if self._exp < other._exp:
2610 if sign:
2611 return Dec_p1
2612 else:
2613 return Dec_n1
2614 if self._exp > other._exp:
2615 if sign:
2616 return Dec_n1
2617 else:
2618 return Dec_p1
2619 return Dec_0
2620
2621
2622 def compare_total_mag(self, other):
2623 """Compares self to other using abstract repr., ignoring sign.
2624
2625 Like compare_total, but with operand's sign ignored and assumed to be 0.
2626 """
2627 s = self.copy_abs()
2628 o = other.copy_abs()
2629 return s.compare_total(o)
2630
2631 def copy_abs(self):
2632 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002633 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002634
2635 def copy_negate(self):
2636 """Returns a copy with the sign inverted."""
2637 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002638 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002639 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002640 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002641
2642 def copy_sign(self, other):
2643 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002644 return _dec_from_triple(other._sign, self._int,
2645 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002646
2647 def exp(self, context=None):
2648 """Returns e ** self."""
2649
2650 if context is None:
2651 context = getcontext()
2652
2653 # exp(NaN) = NaN
2654 ans = self._check_nans(context=context)
2655 if ans:
2656 return ans
2657
2658 # exp(-Infinity) = 0
2659 if self._isinfinity() == -1:
2660 return Dec_0
2661
2662 # exp(0) = 1
2663 if not self:
2664 return Dec_p1
2665
2666 # exp(Infinity) = Infinity
2667 if self._isinfinity() == 1:
2668 return Decimal(self)
2669
2670 # the result is now guaranteed to be inexact (the true
2671 # mathematical result is transcendental). There's no need to
2672 # raise Rounded and Inexact here---they'll always be raised as
2673 # a result of the call to _fix.
2674 p = context.prec
2675 adj = self.adjusted()
2676
2677 # we only need to do any computation for quite a small range
2678 # of adjusted exponents---for example, -29 <= adj <= 10 for
2679 # the default context. For smaller exponent the result is
2680 # indistinguishable from 1 at the given precision, while for
2681 # larger exponent the result either overflows or underflows.
2682 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2683 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002684 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002685 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2686 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002687 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002688 elif self._sign == 0 and adj < -p:
2689 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002690 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002691 elif self._sign == 1 and adj < -p-1:
2692 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002693 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002694 # general case
2695 else:
2696 op = _WorkRep(self)
2697 c, e = op.int, op.exp
2698 if op.sign == 1:
2699 c = -c
2700
2701 # compute correctly rounded result: increase precision by
2702 # 3 digits at a time until we get an unambiguously
2703 # roundable result
2704 extra = 3
2705 while True:
2706 coeff, exp = _dexp(c, e, p+extra)
2707 if coeff % (5*10**(len(str(coeff))-p-1)):
2708 break
2709 extra += 3
2710
Facundo Batista72bc54f2007-11-23 17:59:00 +00002711 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002712
2713 # at this stage, ans should round correctly with *any*
2714 # rounding mode, not just with ROUND_HALF_EVEN
2715 context = context._shallow_copy()
2716 rounding = context._set_rounding(ROUND_HALF_EVEN)
2717 ans = ans._fix(context)
2718 context.rounding = rounding
2719
2720 return ans
2721
2722 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002723 """Return True if self is canonical; otherwise return False.
2724
2725 Currently, the encoding of a Decimal instance is always
2726 canonical, so this method returns True for any Decimal.
2727 """
2728 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002729
2730 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002731 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002732
Facundo Batista1a191df2007-10-02 17:01:24 +00002733 A Decimal instance is considered finite if it is neither
2734 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002735 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002736 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002737
2738 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002739 """Return True if self is infinite; otherwise return False."""
2740 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002741
2742 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002743 """Return True if self is a qNaN or sNaN; otherwise return False."""
2744 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002745
2746 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002747 """Return True if self is a normal number; otherwise return False."""
2748 if self._is_special or not self:
2749 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002750 if context is None:
2751 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002752 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002753
2754 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002755 """Return True if self is a quiet NaN; otherwise return False."""
2756 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002757
2758 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002759 """Return True if self is negative; otherwise return False."""
2760 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002761
2762 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002763 """Return True if self is a signaling NaN; otherwise return False."""
2764 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002765
2766 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002767 """Return True if self is subnormal; otherwise return False."""
2768 if self._is_special or not self:
2769 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002770 if context is None:
2771 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002772 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002773
2774 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002775 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002776 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002777
2778 def _ln_exp_bound(self):
2779 """Compute a lower bound for the adjusted exponent of self.ln().
2780 In other words, compute r such that self.ln() >= 10**r. Assumes
2781 that self is finite and positive and that self != 1.
2782 """
2783
2784 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2785 adj = self._exp + len(self._int) - 1
2786 if adj >= 1:
2787 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2788 return len(str(adj*23//10)) - 1
2789 if adj <= -2:
2790 # argument <= 0.1
2791 return len(str((-1-adj)*23//10)) - 1
2792 op = _WorkRep(self)
2793 c, e = op.int, op.exp
2794 if adj == 0:
2795 # 1 < self < 10
2796 num = str(c-10**-e)
2797 den = str(c)
2798 return len(num) - len(den) - (num < den)
2799 # adj == -1, 0.1 <= self < 1
2800 return e + len(str(10**-e - c)) - 1
2801
2802
2803 def ln(self, context=None):
2804 """Returns the natural (base e) logarithm of self."""
2805
2806 if context is None:
2807 context = getcontext()
2808
2809 # ln(NaN) = NaN
2810 ans = self._check_nans(context=context)
2811 if ans:
2812 return ans
2813
2814 # ln(0.0) == -Infinity
2815 if not self:
2816 return negInf
2817
2818 # ln(Infinity) = Infinity
2819 if self._isinfinity() == 1:
2820 return Inf
2821
2822 # ln(1.0) == 0.0
2823 if self == Dec_p1:
2824 return Dec_0
2825
2826 # ln(negative) raises InvalidOperation
2827 if self._sign == 1:
2828 return context._raise_error(InvalidOperation,
2829 'ln of a negative value')
2830
2831 # result is irrational, so necessarily inexact
2832 op = _WorkRep(self)
2833 c, e = op.int, op.exp
2834 p = context.prec
2835
2836 # correctly rounded result: repeatedly increase precision by 3
2837 # until we get an unambiguously roundable result
2838 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2839 while True:
2840 coeff = _dlog(c, e, places)
2841 # assert len(str(abs(coeff)))-p >= 1
2842 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2843 break
2844 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002845 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002846
2847 context = context._shallow_copy()
2848 rounding = context._set_rounding(ROUND_HALF_EVEN)
2849 ans = ans._fix(context)
2850 context.rounding = rounding
2851 return ans
2852
2853 def _log10_exp_bound(self):
2854 """Compute a lower bound for the adjusted exponent of self.log10().
2855 In other words, find r such that self.log10() >= 10**r.
2856 Assumes that self is finite and positive and that self != 1.
2857 """
2858
2859 # For x >= 10 or x < 0.1 we only need a bound on the integer
2860 # part of log10(self), and this comes directly from the
2861 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2862 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2863 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2864
2865 adj = self._exp + len(self._int) - 1
2866 if adj >= 1:
2867 # self >= 10
2868 return len(str(adj))-1
2869 if adj <= -2:
2870 # self < 0.1
2871 return len(str(-1-adj))-1
2872 op = _WorkRep(self)
2873 c, e = op.int, op.exp
2874 if adj == 0:
2875 # 1 < self < 10
2876 num = str(c-10**-e)
2877 den = str(231*c)
2878 return len(num) - len(den) - (num < den) + 2
2879 # adj == -1, 0.1 <= self < 1
2880 num = str(10**-e-c)
2881 return len(num) + e - (num < "231") - 1
2882
2883 def log10(self, context=None):
2884 """Returns the base 10 logarithm of self."""
2885
2886 if context is None:
2887 context = getcontext()
2888
2889 # log10(NaN) = NaN
2890 ans = self._check_nans(context=context)
2891 if ans:
2892 return ans
2893
2894 # log10(0.0) == -Infinity
2895 if not self:
2896 return negInf
2897
2898 # log10(Infinity) = Infinity
2899 if self._isinfinity() == 1:
2900 return Inf
2901
2902 # log10(negative or -Infinity) raises InvalidOperation
2903 if self._sign == 1:
2904 return context._raise_error(InvalidOperation,
2905 'log10 of a negative value')
2906
2907 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00002908 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00002909 # answer may need rounding
2910 ans = Decimal(self._exp + len(self._int) - 1)
2911 else:
2912 # result is irrational, so necessarily inexact
2913 op = _WorkRep(self)
2914 c, e = op.int, op.exp
2915 p = context.prec
2916
2917 # correctly rounded result: repeatedly increase precision
2918 # until result is unambiguously roundable
2919 places = p-self._log10_exp_bound()+2
2920 while True:
2921 coeff = _dlog10(c, e, places)
2922 # assert len(str(abs(coeff)))-p >= 1
2923 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2924 break
2925 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002926 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002927
2928 context = context._shallow_copy()
2929 rounding = context._set_rounding(ROUND_HALF_EVEN)
2930 ans = ans._fix(context)
2931 context.rounding = rounding
2932 return ans
2933
2934 def logb(self, context=None):
2935 """ Returns the exponent of the magnitude of self's MSD.
2936
2937 The result is the integer which is the exponent of the magnitude
2938 of the most significant digit of self (as though it were truncated
2939 to a single digit while maintaining the value of that digit and
2940 without limiting the resulting exponent).
2941 """
2942 # logb(NaN) = NaN
2943 ans = self._check_nans(context=context)
2944 if ans:
2945 return ans
2946
2947 if context is None:
2948 context = getcontext()
2949
2950 # logb(+/-Inf) = +Inf
2951 if self._isinfinity():
2952 return Inf
2953
2954 # logb(0) = -Inf, DivisionByZero
2955 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00002956 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00002957
2958 # otherwise, simply return the adjusted exponent of self, as a
2959 # Decimal. Note that no attempt is made to fit the result
2960 # into the current context.
2961 return Decimal(self.adjusted())
2962
2963 def _islogical(self):
2964 """Return True if self is a logical operand.
2965
2966 For being logical, it must be a finite numbers with a sign of 0,
2967 an exponent of 0, and a coefficient whose digits must all be
2968 either 0 or 1.
2969 """
2970 if self._sign != 0 or self._exp != 0:
2971 return False
2972 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002973 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00002974 return False
2975 return True
2976
2977 def _fill_logical(self, context, opa, opb):
2978 dif = context.prec - len(opa)
2979 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002980 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00002981 elif dif < 0:
2982 opa = opa[-context.prec:]
2983 dif = context.prec - len(opb)
2984 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002985 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00002986 elif dif < 0:
2987 opb = opb[-context.prec:]
2988 return opa, opb
2989
2990 def logical_and(self, other, context=None):
2991 """Applies an 'and' operation between self and other's digits."""
2992 if context is None:
2993 context = getcontext()
2994 if not self._islogical() or not other._islogical():
2995 return context._raise_error(InvalidOperation)
2996
2997 # fill to context.prec
2998 (opa, opb) = self._fill_logical(context, self._int, other._int)
2999
3000 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003001 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3002 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003003
3004 def logical_invert(self, context=None):
3005 """Invert all its digits."""
3006 if context is None:
3007 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003008 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3009 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003010
3011 def logical_or(self, other, context=None):
3012 """Applies an 'or' operation between self and other's digits."""
3013 if context is None:
3014 context = getcontext()
3015 if not self._islogical() or not other._islogical():
3016 return context._raise_error(InvalidOperation)
3017
3018 # fill to context.prec
3019 (opa, opb) = self._fill_logical(context, self._int, other._int)
3020
3021 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003022 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3023 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003024
3025 def logical_xor(self, other, context=None):
3026 """Applies an 'xor' operation between self and other's digits."""
3027 if context is None:
3028 context = getcontext()
3029 if not self._islogical() or not other._islogical():
3030 return context._raise_error(InvalidOperation)
3031
3032 # fill to context.prec
3033 (opa, opb) = self._fill_logical(context, self._int, other._int)
3034
3035 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003036 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3037 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003038
3039 def max_mag(self, other, context=None):
3040 """Compares the values numerically with their sign ignored."""
3041 other = _convert_other(other, raiseit=True)
3042
Facundo Batista6c398da2007-09-17 17:30:13 +00003043 if context is None:
3044 context = getcontext()
3045
Facundo Batista353750c2007-09-13 18:13:15 +00003046 if self._is_special or other._is_special:
3047 # If one operand is a quiet NaN and the other is number, then the
3048 # number is always returned
3049 sn = self._isnan()
3050 on = other._isnan()
3051 if sn or on:
3052 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003053 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003054 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003055 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003056 return self._check_nans(other, context)
3057
3058 c = self.copy_abs().__cmp__(other.copy_abs())
3059 if c == 0:
3060 c = self.compare_total(other)
3061
3062 if c == -1:
3063 ans = other
3064 else:
3065 ans = self
3066
Facundo Batistae64acfa2007-12-17 14:18:42 +00003067 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003068
3069 def min_mag(self, other, context=None):
3070 """Compares the values numerically with their sign ignored."""
3071 other = _convert_other(other, raiseit=True)
3072
Facundo Batista6c398da2007-09-17 17:30:13 +00003073 if context is None:
3074 context = getcontext()
3075
Facundo Batista353750c2007-09-13 18:13:15 +00003076 if self._is_special or other._is_special:
3077 # If one operand is a quiet NaN and the other is number, then the
3078 # number is always returned
3079 sn = self._isnan()
3080 on = other._isnan()
3081 if sn or on:
3082 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003083 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003084 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003085 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003086 return self._check_nans(other, context)
3087
3088 c = self.copy_abs().__cmp__(other.copy_abs())
3089 if c == 0:
3090 c = self.compare_total(other)
3091
3092 if c == -1:
3093 ans = self
3094 else:
3095 ans = other
3096
Facundo Batistae64acfa2007-12-17 14:18:42 +00003097 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003098
3099 def next_minus(self, context=None):
3100 """Returns the largest representable number smaller than itself."""
3101 if context is None:
3102 context = getcontext()
3103
3104 ans = self._check_nans(context=context)
3105 if ans:
3106 return ans
3107
3108 if self._isinfinity() == -1:
3109 return negInf
3110 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003111 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003112
3113 context = context.copy()
3114 context._set_rounding(ROUND_FLOOR)
3115 context._ignore_all_flags()
3116 new_self = self._fix(context)
3117 if new_self != self:
3118 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003119 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3120 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003121
3122 def next_plus(self, context=None):
3123 """Returns the smallest representable number larger than itself."""
3124 if context is None:
3125 context = getcontext()
3126
3127 ans = self._check_nans(context=context)
3128 if ans:
3129 return ans
3130
3131 if self._isinfinity() == 1:
3132 return Inf
3133 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003134 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003135
3136 context = context.copy()
3137 context._set_rounding(ROUND_CEILING)
3138 context._ignore_all_flags()
3139 new_self = self._fix(context)
3140 if new_self != self:
3141 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003142 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3143 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003144
3145 def next_toward(self, other, context=None):
3146 """Returns the number closest to self, in the direction towards other.
3147
3148 The result is the closest representable number to self
3149 (excluding self) that is in the direction towards other,
3150 unless both have the same value. If the two operands are
3151 numerically equal, then the result is a copy of self with the
3152 sign set to be the same as the sign of other.
3153 """
3154 other = _convert_other(other, raiseit=True)
3155
3156 if context is None:
3157 context = getcontext()
3158
3159 ans = self._check_nans(other, context)
3160 if ans:
3161 return ans
3162
3163 comparison = self.__cmp__(other)
3164 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003165 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003166
3167 if comparison == -1:
3168 ans = self.next_plus(context)
3169 else: # comparison == 1
3170 ans = self.next_minus(context)
3171
3172 # decide which flags to raise using value of ans
3173 if ans._isinfinity():
3174 context._raise_error(Overflow,
3175 'Infinite result from next_toward',
3176 ans._sign)
3177 context._raise_error(Rounded)
3178 context._raise_error(Inexact)
3179 elif ans.adjusted() < context.Emin:
3180 context._raise_error(Underflow)
3181 context._raise_error(Subnormal)
3182 context._raise_error(Rounded)
3183 context._raise_error(Inexact)
3184 # if precision == 1 then we don't raise Clamped for a
3185 # result 0E-Etiny.
3186 if not ans:
3187 context._raise_error(Clamped)
3188
3189 return ans
3190
3191 def number_class(self, context=None):
3192 """Returns an indication of the class of self.
3193
3194 The class is one of the following strings:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00003195 sNaN
3196 NaN
Facundo Batista353750c2007-09-13 18:13:15 +00003197 -Infinity
3198 -Normal
3199 -Subnormal
3200 -Zero
3201 +Zero
3202 +Subnormal
3203 +Normal
3204 +Infinity
3205 """
3206 if self.is_snan():
3207 return "sNaN"
3208 if self.is_qnan():
3209 return "NaN"
3210 inf = self._isinfinity()
3211 if inf == 1:
3212 return "+Infinity"
3213 if inf == -1:
3214 return "-Infinity"
3215 if self.is_zero():
3216 if self._sign:
3217 return "-Zero"
3218 else:
3219 return "+Zero"
3220 if context is None:
3221 context = getcontext()
3222 if self.is_subnormal(context=context):
3223 if self._sign:
3224 return "-Subnormal"
3225 else:
3226 return "+Subnormal"
3227 # just a normal, regular, boring number, :)
3228 if self._sign:
3229 return "-Normal"
3230 else:
3231 return "+Normal"
3232
3233 def radix(self):
3234 """Just returns 10, as this is Decimal, :)"""
3235 return Decimal(10)
3236
3237 def rotate(self, other, context=None):
3238 """Returns a rotated copy of self, value-of-other times."""
3239 if context is None:
3240 context = getcontext()
3241
3242 ans = self._check_nans(other, context)
3243 if ans:
3244 return ans
3245
3246 if other._exp != 0:
3247 return context._raise_error(InvalidOperation)
3248 if not (-context.prec <= int(other) <= context.prec):
3249 return context._raise_error(InvalidOperation)
3250
3251 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003252 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003253
3254 # get values, pad if necessary
3255 torot = int(other)
3256 rotdig = self._int
3257 topad = context.prec - len(rotdig)
3258 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003259 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003260
3261 # let's rotate!
3262 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003263 return _dec_from_triple(self._sign,
3264 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003265
3266 def scaleb (self, other, context=None):
3267 """Returns self operand after adding the second value to its exp."""
3268 if context is None:
3269 context = getcontext()
3270
3271 ans = self._check_nans(other, context)
3272 if ans:
3273 return ans
3274
3275 if other._exp != 0:
3276 return context._raise_error(InvalidOperation)
3277 liminf = -2 * (context.Emax + context.prec)
3278 limsup = 2 * (context.Emax + context.prec)
3279 if not (liminf <= int(other) <= limsup):
3280 return context._raise_error(InvalidOperation)
3281
3282 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003283 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003284
Facundo Batista72bc54f2007-11-23 17:59:00 +00003285 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003286 d = d._fix(context)
3287 return d
3288
3289 def shift(self, other, context=None):
3290 """Returns a shifted copy of self, value-of-other times."""
3291 if context is None:
3292 context = getcontext()
3293
3294 ans = self._check_nans(other, context)
3295 if ans:
3296 return ans
3297
3298 if other._exp != 0:
3299 return context._raise_error(InvalidOperation)
3300 if not (-context.prec <= int(other) <= context.prec):
3301 return context._raise_error(InvalidOperation)
3302
3303 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003304 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003305
3306 # get values, pad if necessary
3307 torot = int(other)
3308 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003309 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003310 rotdig = self._int
3311 topad = context.prec - len(rotdig)
3312 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003313 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003314
3315 # let's shift!
3316 if torot < 0:
3317 rotated = rotdig[:torot]
3318 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003319 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003320 rotated = rotated[-context.prec:]
3321
Facundo Batista72bc54f2007-11-23 17:59:00 +00003322 return _dec_from_triple(self._sign,
3323 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003324
Facundo Batista59c58842007-04-10 12:58:45 +00003325 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003326 def __reduce__(self):
3327 return (self.__class__, (str(self),))
3328
3329 def __copy__(self):
3330 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003331 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003332 return self.__class__(str(self))
3333
3334 def __deepcopy__(self, memo):
3335 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003336 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003337 return self.__class__(str(self))
3338
Facundo Batista72bc54f2007-11-23 17:59:00 +00003339def _dec_from_triple(sign, coefficient, exponent, special=False):
3340 """Create a decimal instance directly, without any validation,
3341 normalization (e.g. removal of leading zeros) or argument
3342 conversion.
3343
3344 This function is for *internal use only*.
3345 """
3346
3347 self = object.__new__(Decimal)
3348 self._sign = sign
3349 self._int = coefficient
3350 self._exp = exponent
3351 self._is_special = special
3352
3353 return self
3354
Facundo Batista59c58842007-04-10 12:58:45 +00003355##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003356
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003357
3358# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003359rounding_functions = [name for name in Decimal.__dict__.keys()
3360 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003361for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003362 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003363 globalname = name[1:].upper()
3364 val = globals()[globalname]
3365 Decimal._pick_rounding_function[val] = name
3366
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003367del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003368
Nick Coghlanced12182006-09-02 03:54:17 +00003369class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003370 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003371
Nick Coghlanced12182006-09-02 03:54:17 +00003372 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003373 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003374 """
3375 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003376 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003377 def __enter__(self):
3378 self.saved_context = getcontext()
3379 setcontext(self.new_context)
3380 return self.new_context
3381 def __exit__(self, t, v, tb):
3382 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003383
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003384class Context(object):
3385 """Contains the context for a Decimal instance.
3386
3387 Contains:
3388 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003389 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003390 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003391 raised when it is caused. Otherwise, a value is
3392 substituted in.
3393 flags - When an exception is caused, flags[exception] is incremented.
3394 (Whether or not the trap_enabler is set)
3395 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003396 Emin - Minimum exponent
3397 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003398 capitals - If 1, 1*10^1 is printed as 1E+1.
3399 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003400 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003401 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003402
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003403 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003404 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003405 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003406 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003407 _ignored_flags=None):
3408 if flags is None:
3409 flags = []
3410 if _ignored_flags is None:
3411 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003412 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003413 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003414 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003415 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003416 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003417 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003418 for name, val in locals().items():
3419 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003420 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003421 else:
3422 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003423 del self.self
3424
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003425 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003426 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003427 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003428 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3429 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3430 % vars(self))
3431 names = [f.__name__ for f, v in self.flags.items() if v]
3432 s.append('flags=[' + ', '.join(names) + ']')
3433 names = [t.__name__ for t, v in self.traps.items() if v]
3434 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003435 return ', '.join(s) + ')'
3436
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003437 def clear_flags(self):
3438 """Reset all flags to zero"""
3439 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003440 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003441
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003442 def _shallow_copy(self):
3443 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003444 nc = Context(self.prec, self.rounding, self.traps,
3445 self.flags, self.Emin, self.Emax,
3446 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003447 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003448
3449 def copy(self):
3450 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003451 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003452 self.flags.copy(), self.Emin, self.Emax,
3453 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003454 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003455 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003456
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003457 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003458 """Handles an error
3459
3460 If the flag is in _ignored_flags, returns the default response.
3461 Otherwise, it increments the flag, then, if the corresponding
3462 trap_enabler is set, it reaises the exception. Otherwise, it returns
3463 the default value after incrementing the flag.
3464 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003465 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003466 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003467 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003468 return error().handle(self, *args)
3469
3470 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003471 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003472 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003473 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003474
3475 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003476 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003477 raise error, explanation
3478
3479 def _ignore_all_flags(self):
3480 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003481 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003482
3483 def _ignore_flags(self, *flags):
3484 """Ignore the flags, if they are raised"""
3485 # Do not mutate-- This way, copies of a context leave the original
3486 # alone.
3487 self._ignored_flags = (self._ignored_flags + list(flags))
3488 return list(flags)
3489
3490 def _regard_flags(self, *flags):
3491 """Stop ignoring the flags, if they are raised"""
3492 if flags and isinstance(flags[0], (tuple,list)):
3493 flags = flags[0]
3494 for flag in flags:
3495 self._ignored_flags.remove(flag)
3496
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003497 def __hash__(self):
3498 """A Context cannot be hashed."""
3499 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003500 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003501
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003502 def Etiny(self):
3503 """Returns Etiny (= Emin - prec + 1)"""
3504 return int(self.Emin - self.prec + 1)
3505
3506 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003507 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003508 return int(self.Emax - self.prec + 1)
3509
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003510 def _set_rounding(self, type):
3511 """Sets the rounding type.
3512
3513 Sets the rounding type, and returns the current (previous)
3514 rounding type. Often used like:
3515
3516 context = context.copy()
3517 # so you don't change the calling context
3518 # if an error occurs in the middle.
3519 rounding = context._set_rounding(ROUND_UP)
3520 val = self.__sub__(other, context=context)
3521 context._set_rounding(rounding)
3522
3523 This will make it round up for that operation.
3524 """
3525 rounding = self.rounding
3526 self.rounding= type
3527 return rounding
3528
Raymond Hettingerfed52962004-07-14 15:41:57 +00003529 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003530 """Creates a new Decimal instance but using self as context."""
3531 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003532 if d._isnan() and len(d._int) > self.prec - self._clamp:
3533 return self._raise_error(ConversionSyntax,
3534 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003535 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003536
Facundo Batista59c58842007-04-10 12:58:45 +00003537 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003538 def abs(self, a):
3539 """Returns the absolute value of the operand.
3540
3541 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003542 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003543 the plus operation on the operand.
3544
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003545 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003546 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003547 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003548 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003549 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003550 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003551 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003552 Decimal("101.5")
3553 """
3554 return a.__abs__(context=self)
3555
3556 def add(self, a, b):
3557 """Return the sum of the two operands.
3558
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003559 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003560 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003561 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003562 Decimal("1.02E+4")
3563 """
3564 return a.__add__(b, context=self)
3565
3566 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003567 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003568
Facundo Batista353750c2007-09-13 18:13:15 +00003569 def canonical(self, a):
3570 """Returns the same Decimal object.
3571
3572 As we do not have different encodings for the same number, the
3573 received object already is in its canonical form.
3574
3575 >>> ExtendedContext.canonical(Decimal('2.50'))
3576 Decimal("2.50")
3577 """
3578 return a.canonical(context=self)
3579
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003580 def compare(self, a, b):
3581 """Compares values numerically.
3582
3583 If the signs of the operands differ, a value representing each operand
3584 ('-1' if the operand is less than zero, '0' if the operand is zero or
3585 negative zero, or '1' if the operand is greater than zero) is used in
3586 place of that operand for the comparison instead of the actual
3587 operand.
3588
3589 The comparison is then effected by subtracting the second operand from
3590 the first and then returning a value according to the result of the
3591 subtraction: '-1' if the result is less than zero, '0' if the result is
3592 zero or negative zero, or '1' if the result is greater than zero.
3593
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('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003597 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003598 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003599 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003600 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003601 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003602 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003603 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003604 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003605 Decimal("-1")
3606 """
3607 return a.compare(b, context=self)
3608
Facundo Batista353750c2007-09-13 18:13:15 +00003609 def compare_signal(self, a, b):
3610 """Compares the values of the two operands numerically.
3611
3612 It's pretty much like compare(), but all NaNs signal, with signaling
3613 NaNs taking precedence over quiet NaNs.
3614
3615 >>> c = ExtendedContext
3616 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3617 Decimal("-1")
3618 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3619 Decimal("0")
3620 >>> c.flags[InvalidOperation] = 0
3621 >>> print c.flags[InvalidOperation]
3622 0
3623 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3624 Decimal("NaN")
3625 >>> print c.flags[InvalidOperation]
3626 1
3627 >>> c.flags[InvalidOperation] = 0
3628 >>> print c.flags[InvalidOperation]
3629 0
3630 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3631 Decimal("NaN")
3632 >>> print c.flags[InvalidOperation]
3633 1
3634 """
3635 return a.compare_signal(b, context=self)
3636
3637 def compare_total(self, a, b):
3638 """Compares two operands using their abstract representation.
3639
3640 This is not like the standard compare, which use their numerical
3641 value. Note that a total ordering is defined for all possible abstract
3642 representations.
3643
3644 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3645 Decimal("-1")
3646 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3647 Decimal("-1")
3648 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3649 Decimal("-1")
3650 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3651 Decimal("0")
3652 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3653 Decimal("1")
3654 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3655 Decimal("-1")
3656 """
3657 return a.compare_total(b)
3658
3659 def compare_total_mag(self, a, b):
3660 """Compares two operands using their abstract representation ignoring sign.
3661
3662 Like compare_total, but with operand's sign ignored and assumed to be 0.
3663 """
3664 return a.compare_total_mag(b)
3665
3666 def copy_abs(self, a):
3667 """Returns a copy of the operand with the sign set to 0.
3668
3669 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3670 Decimal("2.1")
3671 >>> ExtendedContext.copy_abs(Decimal('-100'))
3672 Decimal("100")
3673 """
3674 return a.copy_abs()
3675
3676 def copy_decimal(self, a):
3677 """Returns a copy of the decimal objet.
3678
3679 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3680 Decimal("2.1")
3681 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3682 Decimal("-1.00")
3683 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003684 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003685
3686 def copy_negate(self, a):
3687 """Returns a copy of the operand with the sign inverted.
3688
3689 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3690 Decimal("-101.5")
3691 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3692 Decimal("101.5")
3693 """
3694 return a.copy_negate()
3695
3696 def copy_sign(self, a, b):
3697 """Copies the second operand's sign to the first one.
3698
3699 In detail, it returns a copy of the first operand with the sign
3700 equal to the sign of the second operand.
3701
3702 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3703 Decimal("1.50")
3704 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3705 Decimal("1.50")
3706 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3707 Decimal("-1.50")
3708 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3709 Decimal("-1.50")
3710 """
3711 return a.copy_sign(b)
3712
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003713 def divide(self, a, b):
3714 """Decimal division in a specified context.
3715
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003716 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003717 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003718 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003719 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003720 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003721 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003722 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003723 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003724 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003725 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003726 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003727 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003728 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003729 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003730 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003731 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003732 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003733 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003734 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003735 Decimal("1.20E+6")
3736 """
3737 return a.__div__(b, context=self)
3738
3739 def divide_int(self, a, b):
3740 """Divides two numbers and returns the integer part of the result.
3741
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003742 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003743 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003744 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003745 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003746 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003747 Decimal("3")
3748 """
3749 return a.__floordiv__(b, context=self)
3750
3751 def divmod(self, a, b):
3752 return a.__divmod__(b, context=self)
3753
Facundo Batista353750c2007-09-13 18:13:15 +00003754 def exp(self, a):
3755 """Returns e ** a.
3756
3757 >>> c = ExtendedContext.copy()
3758 >>> c.Emin = -999
3759 >>> c.Emax = 999
3760 >>> c.exp(Decimal('-Infinity'))
3761 Decimal("0")
3762 >>> c.exp(Decimal('-1'))
3763 Decimal("0.367879441")
3764 >>> c.exp(Decimal('0'))
3765 Decimal("1")
3766 >>> c.exp(Decimal('1'))
3767 Decimal("2.71828183")
3768 >>> c.exp(Decimal('0.693147181'))
3769 Decimal("2.00000000")
3770 >>> c.exp(Decimal('+Infinity'))
3771 Decimal("Infinity")
3772 """
3773 return a.exp(context=self)
3774
3775 def fma(self, a, b, c):
3776 """Returns a multiplied by b, plus c.
3777
3778 The first two operands are multiplied together, using multiply,
3779 the third operand is then added to the result of that
3780 multiplication, using add, all with only one final rounding.
3781
3782 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3783 Decimal("22")
3784 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3785 Decimal("-8")
3786 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3787 Decimal("1.38435736E+12")
3788 """
3789 return a.fma(b, c, context=self)
3790
3791 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003792 """Return True if the operand is canonical; otherwise return False.
3793
3794 Currently, the encoding of a Decimal instance is always
3795 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00003796
3797 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003798 True
Facundo Batista353750c2007-09-13 18:13:15 +00003799 """
Facundo Batista1a191df2007-10-02 17:01:24 +00003800 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00003801
3802 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003803 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003804
Facundo Batista1a191df2007-10-02 17:01:24 +00003805 A Decimal instance is considered finite if it is neither
3806 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00003807
3808 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003809 True
Facundo Batista353750c2007-09-13 18:13:15 +00003810 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003811 True
Facundo Batista353750c2007-09-13 18:13:15 +00003812 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003813 True
Facundo Batista353750c2007-09-13 18:13:15 +00003814 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003815 False
Facundo Batista353750c2007-09-13 18:13:15 +00003816 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003817 False
Facundo Batista353750c2007-09-13 18:13:15 +00003818 """
3819 return a.is_finite()
3820
3821 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003822 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003823
3824 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003825 False
Facundo Batista353750c2007-09-13 18:13:15 +00003826 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003827 True
Facundo Batista353750c2007-09-13 18:13:15 +00003828 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003829 False
Facundo Batista353750c2007-09-13 18:13:15 +00003830 """
3831 return a.is_infinite()
3832
3833 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003834 """Return True if the operand is a qNaN or sNaN;
3835 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003836
3837 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003838 False
Facundo Batista353750c2007-09-13 18:13:15 +00003839 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003840 True
Facundo Batista353750c2007-09-13 18:13:15 +00003841 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003842 True
Facundo Batista353750c2007-09-13 18:13:15 +00003843 """
3844 return a.is_nan()
3845
3846 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003847 """Return True if the operand is a normal number;
3848 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003849
3850 >>> c = ExtendedContext.copy()
3851 >>> c.Emin = -999
3852 >>> c.Emax = 999
3853 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003854 True
Facundo Batista353750c2007-09-13 18:13:15 +00003855 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003856 False
Facundo Batista353750c2007-09-13 18:13:15 +00003857 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003858 False
Facundo Batista353750c2007-09-13 18:13:15 +00003859 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003860 False
Facundo Batista353750c2007-09-13 18:13:15 +00003861 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003862 False
Facundo Batista353750c2007-09-13 18:13:15 +00003863 """
3864 return a.is_normal(context=self)
3865
3866 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003867 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003868
3869 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003870 False
Facundo Batista353750c2007-09-13 18:13:15 +00003871 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003872 True
Facundo Batista353750c2007-09-13 18:13:15 +00003873 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003874 False
Facundo Batista353750c2007-09-13 18:13:15 +00003875 """
3876 return a.is_qnan()
3877
3878 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003879 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003880
3881 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003882 False
Facundo Batista353750c2007-09-13 18:13:15 +00003883 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003884 True
Facundo Batista353750c2007-09-13 18:13:15 +00003885 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003886 True
Facundo Batista353750c2007-09-13 18:13:15 +00003887 """
3888 return a.is_signed()
3889
3890 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003891 """Return True if the operand is a signaling NaN;
3892 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003893
3894 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003895 False
Facundo Batista353750c2007-09-13 18:13:15 +00003896 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003897 False
Facundo Batista353750c2007-09-13 18:13:15 +00003898 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003899 True
Facundo Batista353750c2007-09-13 18:13:15 +00003900 """
3901 return a.is_snan()
3902
3903 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003904 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003905
3906 >>> c = ExtendedContext.copy()
3907 >>> c.Emin = -999
3908 >>> c.Emax = 999
3909 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003910 False
Facundo Batista353750c2007-09-13 18:13:15 +00003911 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003912 True
Facundo Batista353750c2007-09-13 18:13:15 +00003913 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003914 False
Facundo Batista353750c2007-09-13 18:13:15 +00003915 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003916 False
Facundo Batista353750c2007-09-13 18:13:15 +00003917 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003918 False
Facundo Batista353750c2007-09-13 18:13:15 +00003919 """
3920 return a.is_subnormal(context=self)
3921
3922 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003923 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003924
3925 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003926 True
Facundo Batista353750c2007-09-13 18:13:15 +00003927 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003928 False
Facundo Batista353750c2007-09-13 18:13:15 +00003929 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003930 True
Facundo Batista353750c2007-09-13 18:13:15 +00003931 """
3932 return a.is_zero()
3933
3934 def ln(self, a):
3935 """Returns the natural (base e) logarithm of the operand.
3936
3937 >>> c = ExtendedContext.copy()
3938 >>> c.Emin = -999
3939 >>> c.Emax = 999
3940 >>> c.ln(Decimal('0'))
3941 Decimal("-Infinity")
3942 >>> c.ln(Decimal('1.000'))
3943 Decimal("0")
3944 >>> c.ln(Decimal('2.71828183'))
3945 Decimal("1.00000000")
3946 >>> c.ln(Decimal('10'))
3947 Decimal("2.30258509")
3948 >>> c.ln(Decimal('+Infinity'))
3949 Decimal("Infinity")
3950 """
3951 return a.ln(context=self)
3952
3953 def log10(self, a):
3954 """Returns the base 10 logarithm of the operand.
3955
3956 >>> c = ExtendedContext.copy()
3957 >>> c.Emin = -999
3958 >>> c.Emax = 999
3959 >>> c.log10(Decimal('0'))
3960 Decimal("-Infinity")
3961 >>> c.log10(Decimal('0.001'))
3962 Decimal("-3")
3963 >>> c.log10(Decimal('1.000'))
3964 Decimal("0")
3965 >>> c.log10(Decimal('2'))
3966 Decimal("0.301029996")
3967 >>> c.log10(Decimal('10'))
3968 Decimal("1")
3969 >>> c.log10(Decimal('70'))
3970 Decimal("1.84509804")
3971 >>> c.log10(Decimal('+Infinity'))
3972 Decimal("Infinity")
3973 """
3974 return a.log10(context=self)
3975
3976 def logb(self, a):
3977 """ Returns the exponent of the magnitude of the operand's MSD.
3978
3979 The result is the integer which is the exponent of the magnitude
3980 of the most significant digit of the operand (as though the
3981 operand were truncated to a single digit while maintaining the
3982 value of that digit and without limiting the resulting exponent).
3983
3984 >>> ExtendedContext.logb(Decimal('250'))
3985 Decimal("2")
3986 >>> ExtendedContext.logb(Decimal('2.50'))
3987 Decimal("0")
3988 >>> ExtendedContext.logb(Decimal('0.03'))
3989 Decimal("-2")
3990 >>> ExtendedContext.logb(Decimal('0'))
3991 Decimal("-Infinity")
3992 """
3993 return a.logb(context=self)
3994
3995 def logical_and(self, a, b):
3996 """Applies the logical operation 'and' between each operand's digits.
3997
3998 The operands must be both logical numbers.
3999
4000 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4001 Decimal("0")
4002 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4003 Decimal("0")
4004 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4005 Decimal("0")
4006 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4007 Decimal("1")
4008 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4009 Decimal("1000")
4010 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4011 Decimal("10")
4012 """
4013 return a.logical_and(b, context=self)
4014
4015 def logical_invert(self, a):
4016 """Invert all the digits in the operand.
4017
4018 The operand must be a logical number.
4019
4020 >>> ExtendedContext.logical_invert(Decimal('0'))
4021 Decimal("111111111")
4022 >>> ExtendedContext.logical_invert(Decimal('1'))
4023 Decimal("111111110")
4024 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4025 Decimal("0")
4026 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4027 Decimal("10101010")
4028 """
4029 return a.logical_invert(context=self)
4030
4031 def logical_or(self, a, b):
4032 """Applies the logical operation 'or' between each operand's digits.
4033
4034 The operands must be both logical numbers.
4035
4036 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4037 Decimal("0")
4038 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4039 Decimal("1")
4040 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4041 Decimal("1")
4042 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4043 Decimal("1")
4044 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4045 Decimal("1110")
4046 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4047 Decimal("1110")
4048 """
4049 return a.logical_or(b, context=self)
4050
4051 def logical_xor(self, a, b):
4052 """Applies the logical operation 'xor' between each operand's digits.
4053
4054 The operands must be both logical numbers.
4055
4056 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4057 Decimal("0")
4058 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4059 Decimal("1")
4060 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4061 Decimal("1")
4062 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4063 Decimal("0")
4064 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4065 Decimal("110")
4066 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4067 Decimal("1101")
4068 """
4069 return a.logical_xor(b, context=self)
4070
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004071 def max(self, a,b):
4072 """max compares two values numerically and returns the maximum.
4073
4074 If either operand is a NaN then the general rules apply.
4075 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004076 operation. If they are numerically equal then the left-hand operand
4077 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004078 infinity) of the two operands is chosen as the result.
4079
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004080 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004081 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004082 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004083 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004084 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004085 Decimal("1")
4086 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4087 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004088 """
4089 return a.max(b, context=self)
4090
Facundo Batista353750c2007-09-13 18:13:15 +00004091 def max_mag(self, a, b):
4092 """Compares the values numerically with their sign ignored."""
4093 return a.max_mag(b, context=self)
4094
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004095 def min(self, a,b):
4096 """min compares two values numerically and returns the minimum.
4097
4098 If either operand is a NaN then the general rules apply.
4099 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004100 operation. If they are numerically equal then the left-hand operand
4101 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004102 infinity) of the two operands is chosen as the result.
4103
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004104 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004105 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004106 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004107 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004108 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004109 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004110 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4111 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004112 """
4113 return a.min(b, context=self)
4114
Facundo Batista353750c2007-09-13 18:13:15 +00004115 def min_mag(self, a, b):
4116 """Compares the values numerically with their sign ignored."""
4117 return a.min_mag(b, context=self)
4118
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004119 def minus(self, a):
4120 """Minus corresponds to unary prefix minus in Python.
4121
4122 The operation is evaluated using the same rules as subtract; the
4123 operation minus(a) is calculated as subtract('0', a) where the '0'
4124 has the same exponent as the operand.
4125
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004126 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004127 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004128 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004129 Decimal("1.3")
4130 """
4131 return a.__neg__(context=self)
4132
4133 def multiply(self, a, b):
4134 """multiply multiplies two operands.
4135
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004136 If either operand is a special value then the general rules apply.
4137 Otherwise, the operands are multiplied together ('long multiplication'),
4138 resulting in a number which may be as long as the sum of the lengths
4139 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004140
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004141 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004142 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004143 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004144 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004145 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004146 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004147 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004148 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004149 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004150 Decimal("4.28135971E+11")
4151 """
4152 return a.__mul__(b, context=self)
4153
Facundo Batista353750c2007-09-13 18:13:15 +00004154 def next_minus(self, a):
4155 """Returns the largest representable number smaller than a.
4156
4157 >>> c = ExtendedContext.copy()
4158 >>> c.Emin = -999
4159 >>> c.Emax = 999
4160 >>> ExtendedContext.next_minus(Decimal('1'))
4161 Decimal("0.999999999")
4162 >>> c.next_minus(Decimal('1E-1007'))
4163 Decimal("0E-1007")
4164 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4165 Decimal("-1.00000004")
4166 >>> c.next_minus(Decimal('Infinity'))
4167 Decimal("9.99999999E+999")
4168 """
4169 return a.next_minus(context=self)
4170
4171 def next_plus(self, a):
4172 """Returns the smallest representable number larger than a.
4173
4174 >>> c = ExtendedContext.copy()
4175 >>> c.Emin = -999
4176 >>> c.Emax = 999
4177 >>> ExtendedContext.next_plus(Decimal('1'))
4178 Decimal("1.00000001")
4179 >>> c.next_plus(Decimal('-1E-1007'))
4180 Decimal("-0E-1007")
4181 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4182 Decimal("-1.00000002")
4183 >>> c.next_plus(Decimal('-Infinity'))
4184 Decimal("-9.99999999E+999")
4185 """
4186 return a.next_plus(context=self)
4187
4188 def next_toward(self, a, b):
4189 """Returns the number closest to a, in direction towards b.
4190
4191 The result is the closest representable number from the first
4192 operand (but not the first operand) that is in the direction
4193 towards the second operand, unless the operands have the same
4194 value.
4195
4196 >>> c = ExtendedContext.copy()
4197 >>> c.Emin = -999
4198 >>> c.Emax = 999
4199 >>> c.next_toward(Decimal('1'), Decimal('2'))
4200 Decimal("1.00000001")
4201 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4202 Decimal("-0E-1007")
4203 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4204 Decimal("-1.00000002")
4205 >>> c.next_toward(Decimal('1'), Decimal('0'))
4206 Decimal("0.999999999")
4207 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4208 Decimal("0E-1007")
4209 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4210 Decimal("-1.00000004")
4211 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4212 Decimal("-0.00")
4213 """
4214 return a.next_toward(b, context=self)
4215
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004216 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004217 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004218
4219 Essentially a plus operation with all trailing zeros removed from the
4220 result.
4221
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004222 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004223 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004224 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004225 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004226 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004227 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004228 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004229 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004230 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004231 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004232 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004233 Decimal("0")
4234 """
4235 return a.normalize(context=self)
4236
Facundo Batista353750c2007-09-13 18:13:15 +00004237 def number_class(self, a):
4238 """Returns an indication of the class of the operand.
4239
4240 The class is one of the following strings:
4241 -sNaN
4242 -NaN
4243 -Infinity
4244 -Normal
4245 -Subnormal
4246 -Zero
4247 +Zero
4248 +Subnormal
4249 +Normal
4250 +Infinity
4251
4252 >>> c = Context(ExtendedContext)
4253 >>> c.Emin = -999
4254 >>> c.Emax = 999
4255 >>> c.number_class(Decimal('Infinity'))
4256 '+Infinity'
4257 >>> c.number_class(Decimal('1E-10'))
4258 '+Normal'
4259 >>> c.number_class(Decimal('2.50'))
4260 '+Normal'
4261 >>> c.number_class(Decimal('0.1E-999'))
4262 '+Subnormal'
4263 >>> c.number_class(Decimal('0'))
4264 '+Zero'
4265 >>> c.number_class(Decimal('-0'))
4266 '-Zero'
4267 >>> c.number_class(Decimal('-0.1E-999'))
4268 '-Subnormal'
4269 >>> c.number_class(Decimal('-1E-10'))
4270 '-Normal'
4271 >>> c.number_class(Decimal('-2.50'))
4272 '-Normal'
4273 >>> c.number_class(Decimal('-Infinity'))
4274 '-Infinity'
4275 >>> c.number_class(Decimal('NaN'))
4276 'NaN'
4277 >>> c.number_class(Decimal('-NaN'))
4278 'NaN'
4279 >>> c.number_class(Decimal('sNaN'))
4280 'sNaN'
4281 """
4282 return a.number_class(context=self)
4283
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004284 def plus(self, a):
4285 """Plus corresponds to unary prefix plus in Python.
4286
4287 The operation is evaluated using the same rules as add; the
4288 operation plus(a) is calculated as add('0', a) where the '0'
4289 has the same exponent as the operand.
4290
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004291 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004292 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004293 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004294 Decimal("-1.3")
4295 """
4296 return a.__pos__(context=self)
4297
4298 def power(self, a, b, modulo=None):
4299 """Raises a to the power of b, to modulo if given.
4300
Facundo Batista353750c2007-09-13 18:13:15 +00004301 With two arguments, compute a**b. If a is negative then b
4302 must be integral. The result will be inexact unless b is
4303 integral and the result is finite and can be expressed exactly
4304 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004305
Facundo Batista353750c2007-09-13 18:13:15 +00004306 With three arguments, compute (a**b) % modulo. For the
4307 three argument form, the following restrictions on the
4308 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004309
Facundo Batista353750c2007-09-13 18:13:15 +00004310 - all three arguments must be integral
4311 - b must be nonnegative
4312 - at least one of a or b must be nonzero
4313 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004314
Facundo Batista353750c2007-09-13 18:13:15 +00004315 The result of pow(a, b, modulo) is identical to the result
4316 that would be obtained by computing (a**b) % modulo with
4317 unbounded precision, but is computed more efficiently. It is
4318 always exact.
4319
4320 >>> c = ExtendedContext.copy()
4321 >>> c.Emin = -999
4322 >>> c.Emax = 999
4323 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004324 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004325 >>> c.power(Decimal('-2'), Decimal('3'))
4326 Decimal("-8")
4327 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004328 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004329 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004330 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004331 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4332 Decimal("2.00000000")
4333 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004334 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004335 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004336 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004337 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004338 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004339 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004340 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004341 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004342 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004343 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004344 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004345 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004346 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004347 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004348 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004349
4350 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4351 Decimal("11")
4352 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4353 Decimal("-11")
4354 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4355 Decimal("1")
4356 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4357 Decimal("11")
4358 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4359 Decimal("11729830")
4360 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4361 Decimal("-0")
4362 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4363 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004364 """
4365 return a.__pow__(b, modulo, context=self)
4366
4367 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004368 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004369
4370 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004371 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004372 exponent is being increased), multiplied by a positive power of ten (if
4373 the exponent is being decreased), or is unchanged (if the exponent is
4374 already equal to that of the right-hand operand).
4375
4376 Unlike other operations, if the length of the coefficient after the
4377 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004378 operation condition is raised. This guarantees that, unless there is
4379 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004380 equal to that of the right-hand operand.
4381
4382 Also unlike other operations, quantize will never raise Underflow, even
4383 if the result is subnormal and inexact.
4384
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004385 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004386 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004387 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004388 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004389 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004390 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004391 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004392 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004393 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004394 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004395 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004396 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004397 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004398 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004399 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004400 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004401 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004402 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004403 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004404 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004405 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004406 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004407 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004408 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004409 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004410 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004411 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004412 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004413 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004414 Decimal("2E+2")
4415 """
4416 return a.quantize(b, context=self)
4417
Facundo Batista353750c2007-09-13 18:13:15 +00004418 def radix(self):
4419 """Just returns 10, as this is Decimal, :)
4420
4421 >>> ExtendedContext.radix()
4422 Decimal("10")
4423 """
4424 return Decimal(10)
4425
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004426 def remainder(self, a, b):
4427 """Returns the remainder from integer division.
4428
4429 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004430 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004431 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004432 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004433
4434 This operation will fail under the same conditions as integer division
4435 (that is, if integer division on the same two operands would fail, the
4436 remainder cannot be calculated).
4437
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004438 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004439 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004440 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004441 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004442 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004443 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004444 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004445 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004446 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004447 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004448 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004449 Decimal("1.0")
4450 """
4451 return a.__mod__(b, context=self)
4452
4453 def remainder_near(self, a, b):
4454 """Returns to be "a - b * n", where n is the integer nearest the exact
4455 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004456 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004457 sign of a.
4458
4459 This operation will fail under the same conditions as integer division
4460 (that is, if integer division on the same two operands would fail, the
4461 remainder cannot be calculated).
4462
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004463 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004464 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004465 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004466 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004467 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004468 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004469 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004470 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004471 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004472 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004473 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004474 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004475 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004476 Decimal("-0.3")
4477 """
4478 return a.remainder_near(b, context=self)
4479
Facundo Batista353750c2007-09-13 18:13:15 +00004480 def rotate(self, a, b):
4481 """Returns a rotated copy of a, b times.
4482
4483 The coefficient of the result is a rotated copy of the digits in
4484 the coefficient of the first operand. The number of places of
4485 rotation is taken from the absolute value of the second operand,
4486 with the rotation being to the left if the second operand is
4487 positive or to the right otherwise.
4488
4489 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4490 Decimal("400000003")
4491 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4492 Decimal("12")
4493 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4494 Decimal("891234567")
4495 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4496 Decimal("123456789")
4497 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4498 Decimal("345678912")
4499 """
4500 return a.rotate(b, context=self)
4501
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004502 def same_quantum(self, a, b):
4503 """Returns True if the two operands have the same exponent.
4504
4505 The result is never affected by either the sign or the coefficient of
4506 either operand.
4507
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004508 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004509 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004510 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004511 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004512 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004513 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004514 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004515 True
4516 """
4517 return a.same_quantum(b)
4518
Facundo Batista353750c2007-09-13 18:13:15 +00004519 def scaleb (self, a, b):
4520 """Returns the first operand after adding the second value its exp.
4521
4522 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4523 Decimal("0.0750")
4524 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4525 Decimal("7.50")
4526 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4527 Decimal("7.50E+3")
4528 """
4529 return a.scaleb (b, context=self)
4530
4531 def shift(self, a, b):
4532 """Returns a shifted copy of a, b times.
4533
4534 The coefficient of the result is a shifted copy of the digits
4535 in the coefficient of the first operand. The number of places
4536 to shift is taken from the absolute value of the second operand,
4537 with the shift being to the left if the second operand is
4538 positive or to the right otherwise. Digits shifted into the
4539 coefficient are zeros.
4540
4541 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4542 Decimal("400000000")
4543 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4544 Decimal("0")
4545 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4546 Decimal("1234567")
4547 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4548 Decimal("123456789")
4549 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4550 Decimal("345678900")
4551 """
4552 return a.shift(b, context=self)
4553
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004554 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004555 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004556
4557 If the result must be inexact, it is rounded using the round-half-even
4558 algorithm.
4559
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004560 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004561 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004562 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004563 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004564 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004565 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004566 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004567 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004568 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004569 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004570 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004571 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004572 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004573 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004574 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004575 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004576 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004577 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004578 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004579 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004580 """
4581 return a.sqrt(context=self)
4582
4583 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004584 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004585
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004586 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004587 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004588 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004589 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004590 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004591 Decimal("-0.77")
4592 """
4593 return a.__sub__(b, context=self)
4594
4595 def to_eng_string(self, a):
4596 """Converts a number to a string, using scientific notation.
4597
4598 The operation is not affected by the context.
4599 """
4600 return a.to_eng_string(context=self)
4601
4602 def to_sci_string(self, a):
4603 """Converts a number to a string, using scientific notation.
4604
4605 The operation is not affected by the context.
4606 """
4607 return a.__str__(context=self)
4608
Facundo Batista353750c2007-09-13 18:13:15 +00004609 def to_integral_exact(self, a):
4610 """Rounds to an integer.
4611
4612 When the operand has a negative exponent, the result is the same
4613 as using the quantize() operation using the given operand as the
4614 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4615 of the operand as the precision setting; Inexact and Rounded flags
4616 are allowed in this operation. The rounding mode is taken from the
4617 context.
4618
4619 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4620 Decimal("2")
4621 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4622 Decimal("100")
4623 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4624 Decimal("100")
4625 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4626 Decimal("102")
4627 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4628 Decimal("-102")
4629 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4630 Decimal("1.0E+6")
4631 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4632 Decimal("7.89E+77")
4633 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4634 Decimal("-Infinity")
4635 """
4636 return a.to_integral_exact(context=self)
4637
4638 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004639 """Rounds to an integer.
4640
4641 When the operand has a negative exponent, the result is the same
4642 as using the quantize() operation using the given operand as the
4643 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4644 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004645 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004646
Facundo Batista353750c2007-09-13 18:13:15 +00004647 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004648 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004649 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004650 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004651 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004652 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004653 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004654 Decimal("102")
Facundo Batista353750c2007-09-13 18:13:15 +00004655 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004656 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004657 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004658 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004659 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004660 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004661 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004662 Decimal("-Infinity")
4663 """
Facundo Batista353750c2007-09-13 18:13:15 +00004664 return a.to_integral_value(context=self)
4665
4666 # the method name changed, but we provide also the old one, for compatibility
4667 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004668
4669class _WorkRep(object):
4670 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004671 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004672 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004673 # exp: None, int, or string
4674
4675 def __init__(self, value=None):
4676 if value is None:
4677 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004678 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004679 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004680 elif isinstance(value, Decimal):
4681 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004682 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004683 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004684 else:
4685 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004686 self.sign = value[0]
4687 self.int = value[1]
4688 self.exp = value[2]
4689
4690 def __repr__(self):
4691 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4692
4693 __str__ = __repr__
4694
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004695
4696
Facundo Batistae64acfa2007-12-17 14:18:42 +00004697def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004698 """Normalizes op1, op2 to have the same exp and length of coefficient.
4699
4700 Done during addition.
4701 """
Facundo Batista353750c2007-09-13 18:13:15 +00004702 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004703 tmp = op2
4704 other = op1
4705 else:
4706 tmp = op1
4707 other = op2
4708
Facundo Batista353750c2007-09-13 18:13:15 +00004709 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4710 # Then adding 10**exp to tmp has the same effect (after rounding)
4711 # as adding any positive quantity smaller than 10**exp; similarly
4712 # for subtraction. So if other is smaller than 10**exp we replace
4713 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00004714 tmp_len = len(str(tmp.int))
4715 other_len = len(str(other.int))
4716 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4717 if other_len + other.exp - 1 < exp:
4718 other.int = 1
4719 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004720
Facundo Batista353750c2007-09-13 18:13:15 +00004721 tmp.int *= 10 ** (tmp.exp - other.exp)
4722 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004723 return op1, op2
4724
Facundo Batista353750c2007-09-13 18:13:15 +00004725##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4726
4727# This function from Tim Peters was taken from here:
4728# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4729# The correction being in the function definition is for speed, and
4730# the whole function is not resolved with math.log because of avoiding
4731# the use of floats.
4732def _nbits(n, correction = {
4733 '0': 4, '1': 3, '2': 2, '3': 2,
4734 '4': 1, '5': 1, '6': 1, '7': 1,
4735 '8': 0, '9': 0, 'a': 0, 'b': 0,
4736 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4737 """Number of bits in binary representation of the positive integer n,
4738 or 0 if n == 0.
4739 """
4740 if n < 0:
4741 raise ValueError("The argument to _nbits should be nonnegative.")
4742 hex_n = "%x" % n
4743 return 4*len(hex_n) - correction[hex_n[0]]
4744
4745def _sqrt_nearest(n, a):
4746 """Closest integer to the square root of the positive integer n. a is
4747 an initial approximation to the square root. Any positive integer
4748 will do for a, but the closer a is to the square root of n the
4749 faster convergence will be.
4750
4751 """
4752 if n <= 0 or a <= 0:
4753 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4754
4755 b=0
4756 while a != b:
4757 b, a = a, a--n//a>>1
4758 return a
4759
4760def _rshift_nearest(x, shift):
4761 """Given an integer x and a nonnegative integer shift, return closest
4762 integer to x / 2**shift; use round-to-even in case of a tie.
4763
4764 """
4765 b, q = 1L << shift, x >> shift
4766 return q + (2*(x & (b-1)) + (q&1) > b)
4767
4768def _div_nearest(a, b):
4769 """Closest integer to a/b, a and b positive integers; rounds to even
4770 in the case of a tie.
4771
4772 """
4773 q, r = divmod(a, b)
4774 return q + (2*r + (q&1) > b)
4775
4776def _ilog(x, M, L = 8):
4777 """Integer approximation to M*log(x/M), with absolute error boundable
4778 in terms only of x/M.
4779
4780 Given positive integers x and M, return an integer approximation to
4781 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4782 between the approximation and the exact result is at most 22. For
4783 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4784 both cases these are upper bounds on the error; it will usually be
4785 much smaller."""
4786
4787 # The basic algorithm is the following: let log1p be the function
4788 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4789 # the reduction
4790 #
4791 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4792 #
4793 # repeatedly until the argument to log1p is small (< 2**-L in
4794 # absolute value). For small y we can use the Taylor series
4795 # expansion
4796 #
4797 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4798 #
4799 # truncating at T such that y**T is small enough. The whole
4800 # computation is carried out in a form of fixed-point arithmetic,
4801 # with a real number z being represented by an integer
4802 # approximation to z*M. To avoid loss of precision, the y below
4803 # is actually an integer approximation to 2**R*y*M, where R is the
4804 # number of reductions performed so far.
4805
4806 y = x-M
4807 # argument reduction; R = number of reductions performed
4808 R = 0
4809 while (R <= L and long(abs(y)) << L-R >= M or
4810 R > L and abs(y) >> R-L >= M):
4811 y = _div_nearest(long(M*y) << 1,
4812 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4813 R += 1
4814
4815 # Taylor series with T terms
4816 T = -int(-10*len(str(M))//(3*L))
4817 yshift = _rshift_nearest(y, R)
4818 w = _div_nearest(M, T)
4819 for k in xrange(T-1, 0, -1):
4820 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4821
4822 return _div_nearest(w*y, M)
4823
4824def _dlog10(c, e, p):
4825 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4826 approximation to 10**p * log10(c*10**e), with an absolute error of
4827 at most 1. Assumes that c*10**e is not exactly 1."""
4828
4829 # increase precision by 2; compensate for this by dividing
4830 # final result by 100
4831 p += 2
4832
4833 # write c*10**e as d*10**f with either:
4834 # f >= 0 and 1 <= d <= 10, or
4835 # f <= 0 and 0.1 <= d <= 1.
4836 # Thus for c*10**e close to 1, f = 0
4837 l = len(str(c))
4838 f = e+l - (e+l >= 1)
4839
4840 if p > 0:
4841 M = 10**p
4842 k = e+p-f
4843 if k >= 0:
4844 c *= 10**k
4845 else:
4846 c = _div_nearest(c, 10**-k)
4847
4848 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004849 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004850 log_d = _div_nearest(log_d*M, log_10)
4851 log_tenpower = f*M # exact
4852 else:
4853 log_d = 0 # error < 2.31
4854 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4855
4856 return _div_nearest(log_tenpower+log_d, 100)
4857
4858def _dlog(c, e, p):
4859 """Given integers c, e and p with c > 0, compute an integer
4860 approximation to 10**p * log(c*10**e), with an absolute error of
4861 at most 1. Assumes that c*10**e is not exactly 1."""
4862
4863 # Increase precision by 2. The precision increase is compensated
4864 # for at the end with a division by 100.
4865 p += 2
4866
4867 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4868 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4869 # as 10**p * log(d) + 10**p*f * log(10).
4870 l = len(str(c))
4871 f = e+l - (e+l >= 1)
4872
4873 # compute approximation to 10**p*log(d), with error < 27
4874 if p > 0:
4875 k = e+p-f
4876 if k >= 0:
4877 c *= 10**k
4878 else:
4879 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4880
4881 # _ilog magnifies existing error in c by a factor of at most 10
4882 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4883 else:
4884 # p <= 0: just approximate the whole thing by 0; error < 2.31
4885 log_d = 0
4886
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004887 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00004888 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004889 extra = len(str(abs(f)))-1
4890 if p + extra >= 0:
4891 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4892 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4893 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00004894 else:
4895 f_log_ten = 0
4896 else:
4897 f_log_ten = 0
4898
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004899 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004900 return _div_nearest(f_log_ten + log_d, 100)
4901
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004902class _Log10Memoize(object):
4903 """Class to compute, store, and allow retrieval of, digits of the
4904 constant log(10) = 2.302585.... This constant is needed by
4905 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4906 def __init__(self):
4907 self.digits = "23025850929940456840179914546843642076011014886"
4908
4909 def getdigits(self, p):
4910 """Given an integer p >= 0, return floor(10**p)*log(10).
4911
4912 For example, self.getdigits(3) returns 2302.
4913 """
4914 # digits are stored as a string, for quick conversion to
4915 # integer in the case that we've already computed enough
4916 # digits; the stored digits should always be correct
4917 # (truncated, not rounded to nearest).
4918 if p < 0:
4919 raise ValueError("p should be nonnegative")
4920
4921 if p >= len(self.digits):
4922 # compute p+3, p+6, p+9, ... digits; continue until at
4923 # least one of the extra digits is nonzero
4924 extra = 3
4925 while True:
4926 # compute p+extra digits, correct to within 1ulp
4927 M = 10**(p+extra+2)
4928 digits = str(_div_nearest(_ilog(10*M, M), 100))
4929 if digits[-extra:] != '0'*extra:
4930 break
4931 extra += 3
4932 # keep all reliable digits so far; remove trailing zeros
4933 # and next nonzero digit
4934 self.digits = digits.rstrip('0')[:-1]
4935 return int(self.digits[:p+1])
4936
4937_log10_digits = _Log10Memoize().getdigits
4938
Facundo Batista353750c2007-09-13 18:13:15 +00004939def _iexp(x, M, L=8):
4940 """Given integers x and M, M > 0, such that x/M is small in absolute
4941 value, compute an integer approximation to M*exp(x/M). For 0 <=
4942 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4943 is usually much smaller)."""
4944
4945 # Algorithm: to compute exp(z) for a real number z, first divide z
4946 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4947 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4948 # series
4949 #
4950 # expm1(x) = x + x**2/2! + x**3/3! + ...
4951 #
4952 # Now use the identity
4953 #
4954 # expm1(2x) = expm1(x)*(expm1(x)+2)
4955 #
4956 # R times to compute the sequence expm1(z/2**R),
4957 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
4958
4959 # Find R such that x/2**R/M <= 2**-L
4960 R = _nbits((long(x)<<L)//M)
4961
4962 # Taylor series. (2**L)**T > M
4963 T = -int(-10*len(str(M))//(3*L))
4964 y = _div_nearest(x, T)
4965 Mshift = long(M)<<R
4966 for i in xrange(T-1, 0, -1):
4967 y = _div_nearest(x*(Mshift + y), Mshift * i)
4968
4969 # Expansion
4970 for k in xrange(R-1, -1, -1):
4971 Mshift = long(M)<<(k+2)
4972 y = _div_nearest(y*(y+Mshift), Mshift)
4973
4974 return M+y
4975
4976def _dexp(c, e, p):
4977 """Compute an approximation to exp(c*10**e), with p decimal places of
4978 precision.
4979
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004980 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00004981
4982 10**(p-1) <= d <= 10**p, and
4983 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
4984
4985 In other words, d*10**f is an approximation to exp(c*10**e) with p
4986 digits of precision, and with an error in d of at most 1. This is
4987 almost, but not quite, the same as the error being < 1ulp: when d
4988 = 10**(p-1) the error could be up to 10 ulp."""
4989
4990 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
4991 p += 2
4992
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004993 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00004994 extra = max(0, e + len(str(c)) - 1)
4995 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00004996
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004997 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00004998 # rounding down
4999 shift = e+q
5000 if shift >= 0:
5001 cshift = c*10**shift
5002 else:
5003 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005004 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005005
5006 # reduce remainder back to original precision
5007 rem = _div_nearest(rem, 10**extra)
5008
5009 # error in result of _iexp < 120; error after division < 0.62
5010 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5011
5012def _dpower(xc, xe, yc, ye, p):
5013 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5014 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5015
5016 10**(p-1) <= c <= 10**p, and
5017 (c-1)*10**e < x**y < (c+1)*10**e
5018
5019 in other words, c*10**e is an approximation to x**y with p digits
5020 of precision, and with an error in c of at most 1. (This is
5021 almost, but not quite, the same as the error being < 1ulp: when c
5022 == 10**(p-1) we can only guarantee error < 10ulp.)
5023
5024 We assume that: x is positive and not equal to 1, and y is nonzero.
5025 """
5026
5027 # Find b such that 10**(b-1) <= |y| <= 10**b
5028 b = len(str(abs(yc))) + ye
5029
5030 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5031 lxc = _dlog(xc, xe, p+b+1)
5032
5033 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5034 shift = ye-b
5035 if shift >= 0:
5036 pc = lxc*yc*10**shift
5037 else:
5038 pc = _div_nearest(lxc*yc, 10**-shift)
5039
5040 if pc == 0:
5041 # we prefer a result that isn't exactly 1; this makes it
5042 # easier to compute a correctly rounded result in __pow__
5043 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5044 coeff, exp = 10**(p-1)+1, 1-p
5045 else:
5046 coeff, exp = 10**p-1, -p
5047 else:
5048 coeff, exp = _dexp(pc, -(p+1), p+1)
5049 coeff = _div_nearest(coeff, 10)
5050 exp += 1
5051
5052 return coeff, exp
5053
5054def _log10_lb(c, correction = {
5055 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5056 '6': 23, '7': 16, '8': 10, '9': 5}):
5057 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5058 if c <= 0:
5059 raise ValueError("The argument to _log10_lb should be nonnegative.")
5060 str_c = str(c)
5061 return 100*len(str_c) - correction[str_c[0]]
5062
Facundo Batista59c58842007-04-10 12:58:45 +00005063##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005064
Facundo Batista353750c2007-09-13 18:13:15 +00005065def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005066 """Convert other to Decimal.
5067
5068 Verifies that it's ok to use in an implicit construction.
5069 """
5070 if isinstance(other, Decimal):
5071 return other
5072 if isinstance(other, (int, long)):
5073 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005074 if raiseit:
5075 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005076 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005077
Facundo Batista59c58842007-04-10 12:58:45 +00005078##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005079
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005080# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005081# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005082
5083DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005084 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005085 traps=[DivisionByZero, Overflow, InvalidOperation],
5086 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005087 Emax=999999999,
5088 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005089 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005090)
5091
5092# Pre-made alternate contexts offered by the specification
5093# Don't change these; the user should be able to select these
5094# contexts and be able to reproduce results from other implementations
5095# of the spec.
5096
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005097BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005098 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005099 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5100 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005101)
5102
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005103ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005104 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005105 traps=[],
5106 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005107)
5108
5109
Facundo Batista72bc54f2007-11-23 17:59:00 +00005110##### crud for parsing strings #############################################
5111import re
5112
5113# Regular expression used for parsing numeric strings. Additional
5114# comments:
5115#
5116# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5117# whitespace. But note that the specification disallows whitespace in
5118# a numeric string.
5119#
5120# 2. For finite numbers (not infinities and NaNs) the body of the
5121# number between the optional sign and the optional exponent must have
5122# at least one decimal digit, possibly after the decimal point. The
5123# lookahead expression '(?=\d|\.\d)' checks this.
5124#
5125# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5126# other meaning for \d than the numbers [0-9].
5127
5128import re
5129_parser = re.compile(r""" # A numeric string consists of:
5130# \s*
5131 (?P<sign>[-+])? # an optional sign, followed by either...
5132 (
5133 (?=\d|\.\d) # ...a number (with at least one digit)
5134 (?P<int>\d*) # consisting of a (possibly empty) integer part
5135 (\.(?P<frac>\d*))? # followed by an optional fractional part
5136 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5137 |
5138 Inf(inity)? # ...an infinity, or...
5139 |
5140 (?P<signal>s)? # ...an (optionally signaling)
5141 NaN # NaN
5142 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5143 )
5144# \s*
5145 $
5146""", re.VERBOSE | re.IGNORECASE).match
5147
Facundo Batista2ec74152007-12-03 17:55:00 +00005148_all_zeros = re.compile('0*$').match
5149_exact_half = re.compile('50*$').match
Facundo Batista72bc54f2007-11-23 17:59:00 +00005150del re
5151
5152
Facundo Batista59c58842007-04-10 12:58:45 +00005153##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005154
Facundo Batista59c58842007-04-10 12:58:45 +00005155# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005156Inf = Decimal('Inf')
5157negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005158NaN = Decimal('NaN')
5159Dec_0 = Decimal(0)
5160Dec_p1 = Decimal(1)
5161Dec_n1 = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005162
Facundo Batista59c58842007-04-10 12:58:45 +00005163# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005164Infsign = (Inf, negInf)
5165
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005166
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005167
5168if __name__ == '__main__':
5169 import doctest, sys
5170 doctest.testmod(sys.modules[__name__])