blob: 6a3ee8494ef9d8caf088aa5a5dbe2cc22494fe3c [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# Rounding decision (not part of the public API)
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000150NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY
151ALWAYS_ROUND = 'ALWAYS_ROUND' # Every operation rounds at end.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000152
Facundo Batista59c58842007-04-10 12:58:45 +0000153# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000154
155class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000156 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000157
158 Used exceptions derive from this.
159 If an exception derives from another exception besides this (such as
160 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
161 called if the others are present. This isn't actually used for
162 anything, though.
163
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000164 handle -- Called when context._raise_error is called and the
165 trap_enabler is set. First argument is self, second is the
166 context. More arguments can be given, those being after
167 the explanation in _raise_error (For example,
168 context._raise_error(NewError, '(-x)!', self._sign) would
169 call NewError().handle(context, self._sign).)
170
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000171 To define a new exception, it should be sufficient to have it derive
172 from DecimalException.
173 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000174 def handle(self, context, *args):
175 pass
176
177
178class Clamped(DecimalException):
179 """Exponent of a 0 changed to fit bounds.
180
181 This occurs and signals clamped if the exponent of a result has been
182 altered in order to fit the constraints of a specific concrete
Facundo Batista59c58842007-04-10 12:58:45 +0000183 representation. This may occur when the exponent of a zero result would
184 be outside the bounds of a representation, or when a large normal
185 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000186 this latter case, the exponent is reduced to fit and the corresponding
187 number of zero digits are appended to the coefficient ("fold-down").
188 """
189
190
191class InvalidOperation(DecimalException):
192 """An invalid operation was performed.
193
194 Various bad things cause this:
195
196 Something creates a signaling NaN
197 -INF + INF
Facundo Batista59c58842007-04-10 12:58:45 +0000198 0 * (+-)INF
199 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000200 x % 0
201 (+-)INF % x
202 x._rescale( non-integer )
203 sqrt(-x) , x > 0
204 0 ** 0
205 x ** (non-integer)
206 x ** (+-)INF
207 An operand is invalid
Facundo Batista353750c2007-09-13 18:13:15 +0000208
209 The result of the operation after these is a quiet positive NaN,
210 except when the cause is a signaling NaN, in which case the result is
211 also a quiet NaN, but with the original sign, and an optional
212 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000213 """
214 def handle(self, context, *args):
215 if args:
Facundo Batista59c58842007-04-10 12:58:45 +0000216 if args[0] == 1: # sNaN, must drop 's' but keep diagnostics
Facundo Batista72bc54f2007-11-23 17:59:00 +0000217 ans = _dec_from_triple(args[1]._sign, args[1]._int, 'n', True)
Facundo Batista353750c2007-09-13 18:13:15 +0000218 return ans._fix_nan(context)
219 elif args[0] == 2:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000220 return _dec_from_triple(args[1], args[2], 'n', True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000221 return NaN
222
Facundo Batista353750c2007-09-13 18:13:15 +0000223
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000224class ConversionSyntax(InvalidOperation):
225 """Trying to convert badly formed string.
226
227 This occurs and signals invalid-operation if an string is being
228 converted to a number and it does not conform to the numeric string
Facundo Batista59c58842007-04-10 12:58:45 +0000229 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000230 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000231 def handle(self, context, *args):
Facundo Batista353750c2007-09-13 18:13:15 +0000232 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000233
234class DivisionByZero(DecimalException, ZeroDivisionError):
235 """Division by 0.
236
237 This occurs and signals division-by-zero if division of a finite number
238 by zero was attempted (during a divide-integer or divide operation, or a
239 power operation with negative right-hand operand), and the dividend was
240 not zero.
241
242 The result of the operation is [sign,inf], where sign is the exclusive
243 or of the signs of the operands for divide, or is 1 for an odd power of
244 -0, for power.
245 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000246
Facundo Batistacce8df22007-09-18 16:53:18 +0000247 def handle(self, context, sign, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000248 return Infsign[sign]
249
250class DivisionImpossible(InvalidOperation):
251 """Cannot perform the division adequately.
252
253 This occurs and signals invalid-operation if the integer result of a
254 divide-integer or remainder operation had too many digits (would be
Facundo Batista59c58842007-04-10 12:58:45 +0000255 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000256 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000257
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000258 def handle(self, context, *args):
Facundo Batistacce8df22007-09-18 16:53:18 +0000259 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000260
261class DivisionUndefined(InvalidOperation, ZeroDivisionError):
262 """Undefined result of division.
263
264 This occurs and signals invalid-operation if division by zero was
265 attempted (during a divide-integer, divide, or remainder operation), and
Facundo Batista59c58842007-04-10 12:58:45 +0000266 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000267 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000268
Facundo Batistacce8df22007-09-18 16:53:18 +0000269 def handle(self, context, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000270 return NaN
271
272class Inexact(DecimalException):
273 """Had to round, losing information.
274
275 This occurs and signals inexact whenever the result of an operation is
276 not exact (that is, it needed to be rounded and any discarded digits
Facundo Batista59c58842007-04-10 12:58:45 +0000277 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000278 result in all cases is unchanged.
279
280 The inexact signal may be tested (or trapped) to determine if a given
281 operation (or sequence of operations) was inexact.
282 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000283 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000284
285class InvalidContext(InvalidOperation):
286 """Invalid context. Unknown rounding, for example.
287
288 This occurs and signals invalid-operation if an invalid context was
Facundo Batista59c58842007-04-10 12:58:45 +0000289 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000290 on creation and either the precision exceeds the capability of the
291 underlying concrete representation or an unknown or unsupported rounding
Facundo Batista59c58842007-04-10 12:58:45 +0000292 was specified. These aspects of the context need only be checked when
293 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000294 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000295
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000296 def handle(self, context, *args):
297 return NaN
298
299class Rounded(DecimalException):
300 """Number got rounded (not necessarily changed during rounding).
301
302 This occurs and signals rounded whenever the result of an operation is
303 rounded (that is, some zero or non-zero digits were discarded from the
Facundo Batista59c58842007-04-10 12:58:45 +0000304 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000305 result in all cases is unchanged.
306
307 The rounded signal may be tested (or trapped) to determine if a given
308 operation (or sequence of operations) caused a loss of precision.
309 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000310 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000311
312class Subnormal(DecimalException):
313 """Exponent < Emin before rounding.
314
315 This occurs and signals subnormal whenever the result of a conversion or
316 operation is subnormal (that is, its adjusted exponent is less than
Facundo Batista59c58842007-04-10 12:58:45 +0000317 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000318
319 The subnormal signal may be tested (or trapped) to determine if a given
320 or operation (or sequence of operations) yielded a subnormal result.
321 """
322 pass
323
324class Overflow(Inexact, Rounded):
325 """Numerical overflow.
326
327 This occurs and signals overflow if the adjusted exponent of a result
328 (from a conversion or from an operation that is not an attempt to divide
329 by zero), after rounding, would be greater than the largest value that
330 can be handled by the implementation (the value Emax).
331
332 The result depends on the rounding mode:
333
334 For round-half-up and round-half-even (and for round-half-down and
335 round-up, if implemented), the result of the operation is [sign,inf],
Facundo Batista59c58842007-04-10 12:58:45 +0000336 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 result is the largest finite number that can be represented in the
Facundo Batista59c58842007-04-10 12:58:45 +0000338 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000339 round-ceiling, the result is the same as for round-down if the sign of
Facundo Batista59c58842007-04-10 12:58:45 +0000340 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000341 the result is the same as for round-down if the sign of the intermediate
Facundo Batista59c58842007-04-10 12:58:45 +0000342 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000343 will also be raised.
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000344 """
345
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000346 def handle(self, context, sign, *args):
347 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Facundo Batista353750c2007-09-13 18:13:15 +0000348 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000349 return Infsign[sign]
350 if sign == 0:
351 if context.rounding == ROUND_CEILING:
352 return Infsign[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000353 return _dec_from_triple(sign, '9'*context.prec,
354 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000355 if sign == 1:
356 if context.rounding == ROUND_FLOOR:
357 return Infsign[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000358 return _dec_from_triple(sign, '9'*context.prec,
359 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000360
361
362class Underflow(Inexact, Rounded, Subnormal):
363 """Numerical underflow with result rounded to 0.
364
365 This occurs and signals underflow if a result is inexact and the
366 adjusted exponent of the result would be smaller (more negative) than
367 the smallest value that can be handled by the implementation (the value
Facundo Batista59c58842007-04-10 12:58:45 +0000368 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000369
370 The result after an underflow will be a subnormal number rounded, if
Facundo Batista59c58842007-04-10 12:58:45 +0000371 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000372 in 0 with the sign of the intermediate result and an exponent of Etiny.
373
374 In all cases, Inexact, Rounded, and Subnormal will also be raised.
375 """
376
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000377# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000378_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000379 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000380
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000381# Map conditions (per the spec) to signals
382_condition_map = {ConversionSyntax:InvalidOperation,
383 DivisionImpossible:InvalidOperation,
384 DivisionUndefined:InvalidOperation,
385 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000386
Facundo Batista59c58842007-04-10 12:58:45 +0000387##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000388
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000389# The getcontext() and setcontext() function manage access to a thread-local
390# current context. Py2.4 offers direct support for thread locals. If that
391# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000392# work for older Pythons. If threads are not part of the build, create a
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000393# mock threading object with threading.local() returning the module namespace.
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000394
395try:
396 import threading
397except ImportError:
398 # Python was compiled without threads; create a mock object instead
399 import sys
Facundo Batista59c58842007-04-10 12:58:45 +0000400 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000401 def local(self, sys=sys):
402 return sys.modules[__name__]
403 threading = MockThreading()
404 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000405
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000406try:
407 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000408
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000409except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000410
Facundo Batista59c58842007-04-10 12:58:45 +0000411 # To fix reloading, force it to create a new context
412 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000413 if hasattr(threading.currentThread(), '__decimal_context__'):
414 del threading.currentThread().__decimal_context__
415
416 def setcontext(context):
417 """Set this thread's context to context."""
418 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000419 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000420 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000421 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000422
423 def getcontext():
424 """Returns this thread's context.
425
426 If this thread does not yet have a context, returns
427 a new context and sets this thread's context.
428 New contexts are copies of DefaultContext.
429 """
430 try:
431 return threading.currentThread().__decimal_context__
432 except AttributeError:
433 context = Context()
434 threading.currentThread().__decimal_context__ = context
435 return context
436
437else:
438
439 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000440 if hasattr(local, '__decimal_context__'):
441 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000442
443 def getcontext(_local=local):
444 """Returns this thread's context.
445
446 If this thread does not yet have a context, returns
447 a new context and sets this thread's context.
448 New contexts are copies of DefaultContext.
449 """
450 try:
451 return _local.__decimal_context__
452 except AttributeError:
453 context = Context()
454 _local.__decimal_context__ = context
455 return context
456
457 def setcontext(context, _local=local):
458 """Set this thread's context to context."""
459 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000460 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000461 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000462 _local.__decimal_context__ = context
463
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000464 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000465
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000466def localcontext(ctx=None):
467 """Return a context manager for a copy of the supplied context
468
469 Uses a copy of the current context if no context is specified
470 The returned context manager creates a local decimal context
471 in a with statement:
472 def sin(x):
473 with localcontext() as ctx:
474 ctx.prec += 2
475 # Rest of sin calculation algorithm
476 # uses a precision 2 greater than normal
Facundo Batista59c58842007-04-10 12:58:45 +0000477 return +s # Convert result to normal precision
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000478
479 def sin(x):
480 with localcontext(ExtendedContext):
481 # Rest of sin calculation algorithm
482 # uses the Extended Context from the
483 # General Decimal Arithmetic Specification
Facundo Batista59c58842007-04-10 12:58:45 +0000484 return +s # Convert result to normal context
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000485
486 """
Neal Norwitz681d8672006-09-02 18:51:34 +0000487 # The string below can't be included in the docstring until Python 2.6
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000488 # as the doctest module doesn't understand __future__ statements
489 """
490 >>> from __future__ import with_statement
491 >>> print getcontext().prec
492 28
493 >>> with localcontext():
494 ... ctx = getcontext()
Raymond Hettinger495df472007-02-08 01:42:35 +0000495 ... ctx.prec += 2
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000496 ... print ctx.prec
497 ...
498 30
499 >>> with localcontext(ExtendedContext):
500 ... print getcontext().prec
501 ...
502 9
503 >>> print getcontext().prec
504 28
505 """
Nick Coghlanced12182006-09-02 03:54:17 +0000506 if ctx is None: ctx = getcontext()
507 return _ContextManager(ctx)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000508
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000509
Facundo Batista59c58842007-04-10 12:58:45 +0000510##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000511
512class Decimal(object):
513 """Floating point class for decimal arithmetic."""
514
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000515 __slots__ = ('_exp','_int','_sign', '_is_special')
516 # Generally, the value of the Decimal instance is given by
517 # (-1)**_sign * _int * 10**_exp
518 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000519
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000520 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000521 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000522 """Create a decimal point instance.
523
524 >>> Decimal('3.14') # string input
525 Decimal("3.14")
Facundo Batista59c58842007-04-10 12:58:45 +0000526 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000527 Decimal("3.14")
528 >>> Decimal(314) # int or long
529 Decimal("314")
530 >>> Decimal(Decimal(314)) # another decimal instance
531 Decimal("314")
532 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000533
Facundo Batista72bc54f2007-11-23 17:59:00 +0000534 # Note that the coefficient, self._int, is actually stored as
535 # a string rather than as a tuple of digits. This speeds up
536 # the "digits to integer" and "integer to digits" conversions
537 # that are used in almost every arithmetic operation on
538 # Decimals. This is an internal detail: the as_tuple function
539 # and the Decimal constructor still deal with tuples of
540 # digits.
541
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000542 self = object.__new__(cls)
543 self._is_special = False
544
545 # From an internal working value
546 if isinstance(value, _WorkRep):
Raymond Hettinger17931de2004-10-27 06:21:46 +0000547 self._sign = value.sign
Facundo Batista72bc54f2007-11-23 17:59:00 +0000548 self._int = str(value.int)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000549 self._exp = int(value.exp)
550 return self
551
552 # From another decimal
553 if isinstance(value, Decimal):
554 self._exp = value._exp
555 self._sign = value._sign
556 self._int = value._int
557 self._is_special = value._is_special
558 return self
559
560 # From an integer
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000561 if isinstance(value, (int,long)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000562 if value >= 0:
563 self._sign = 0
564 else:
565 self._sign = 1
566 self._exp = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +0000567 self._int = str(abs(value))
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000568 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000569
570 # tuple/list conversion (possibly from as_tuple())
571 if isinstance(value, (list,tuple)):
572 if len(value) != 3:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000573 raise ValueError('Invalid tuple size in creation of Decimal '
574 'from list or tuple. The list or tuple '
575 'should have exactly three elements.')
576 # process sign. The isinstance test rejects floats
577 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
578 raise ValueError("Invalid sign. The first value in the tuple "
579 "should be an integer; either 0 for a "
580 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000581 self._sign = value[0]
Facundo Batista9b5e2312007-10-19 19:25:57 +0000582 if value[2] == 'F':
583 # infinity: value[1] is ignored
Facundo Batista72bc54f2007-11-23 17:59:00 +0000584 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000585 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000586 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000587 else:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000588 # process and validate the digits in value[1]
589 digits = []
590 for digit in value[1]:
591 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
592 # skip leading zeros
593 if digits or digit != 0:
594 digits.append(digit)
595 else:
596 raise ValueError("The second value in the tuple must "
597 "be composed of integers in the range "
598 "0 through 9.")
599 if value[2] in ('n', 'N'):
600 # NaN: digits form the diagnostic
Facundo Batista72bc54f2007-11-23 17:59:00 +0000601 self._int = ''.join(map(str, digits))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000602 self._exp = value[2]
603 self._is_special = True
604 elif isinstance(value[2], (int, long)):
605 # finite number: digits give the coefficient
Facundo Batista72bc54f2007-11-23 17:59:00 +0000606 self._int = ''.join(map(str, digits or [0]))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000607 self._exp = value[2]
608 self._is_special = False
609 else:
610 raise ValueError("The third value in the tuple must "
611 "be an integer, or one of the "
612 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000613 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000614
Raymond Hettingerbf440692004-07-10 14:14:37 +0000615 if isinstance(value, float):
616 raise TypeError("Cannot convert float to Decimal. " +
617 "First convert the float to a string")
618
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000619 # From a string
620 # REs insist on real strings, so we can too.
621 if isinstance(value, basestring):
Facundo Batista72bc54f2007-11-23 17:59:00 +0000622 m = _parser(value)
623 if m is None:
624 if context is None:
625 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +0000626 return context._raise_error(ConversionSyntax,
Facundo Batista72bc54f2007-11-23 17:59:00 +0000627 "Invalid literal for Decimal: %r" % value)
628
629 if m.group('sign') == "-":
630 self._sign = 1
631 else:
632 self._sign = 0
633 intpart = m.group('int')
634 if intpart is not None:
635 # finite number
636 fracpart = m.group('frac')
637 exp = int(m.group('exp') or '0')
638 if fracpart is not None:
639 self._int = (intpart+fracpart).lstrip('0') or '0'
640 self._exp = exp - len(fracpart)
641 else:
642 self._int = intpart.lstrip('0') or '0'
643 self._exp = exp
644 self._is_special = False
645 else:
646 diag = m.group('diag')
647 if diag is not None:
648 # NaN
649 self._int = diag.lstrip('0')
650 if m.group('signal'):
651 self._exp = 'N'
652 else:
653 self._exp = 'n'
654 else:
655 # infinity
656 self._int = '0'
657 self._exp = 'F'
658 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000659 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000660
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000661 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000662
663 def _isnan(self):
664 """Returns whether the number is not actually one.
665
666 0 if a number
Facundo Batista353750c2007-09-13 18:13:15 +0000667 1 if NaN (it could be a normal quiet NaN or a phantom one)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000668 2 if sNaN
669 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000670 if self._is_special:
671 exp = self._exp
672 if exp == 'n':
673 return 1
674 elif exp == 'N':
675 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000676 return 0
677
678 def _isinfinity(self):
679 """Returns whether the number is infinite
680
681 0 if finite or not a number
682 1 if +INF
683 -1 if -INF
684 """
685 if self._exp == 'F':
686 if self._sign:
687 return -1
688 return 1
689 return 0
690
Facundo Batista353750c2007-09-13 18:13:15 +0000691 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000692 """Returns whether the number is not actually one.
693
694 if self, other are sNaN, signal
695 if self, other are NaN return nan
696 return 0
697
698 Done before operations.
699 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000700
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000701 self_is_nan = self._isnan()
702 if other is None:
703 other_is_nan = False
704 else:
705 other_is_nan = other._isnan()
706
707 if self_is_nan or other_is_nan:
708 if context is None:
709 context = getcontext()
710
711 if self_is_nan == 2:
712 return context._raise_error(InvalidOperation, 'sNaN',
713 1, self)
714 if other_is_nan == 2:
715 return context._raise_error(InvalidOperation, 'sNaN',
716 1, other)
717 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000718 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000719
Facundo Batista353750c2007-09-13 18:13:15 +0000720 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000721 return 0
722
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000723 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000724 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000725
Facundo Batista1a191df2007-10-02 17:01:24 +0000726 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000727 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000728 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000729
Facundo Batista353750c2007-09-13 18:13:15 +0000730 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000731 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000732 if other is NotImplemented:
Facundo Batista353750c2007-09-13 18:13:15 +0000733 # Never return NotImplemented
734 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000735
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000736 if self._is_special or other._is_special:
Facundo Batista353750c2007-09-13 18:13:15 +0000737 # check for nans, without raising on a signaling nan
738 if self._isnan() or other._isnan():
Facundo Batista59c58842007-04-10 12:58:45 +0000739 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000740
741 # INF = INF
742 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000743
Facundo Batista353750c2007-09-13 18:13:15 +0000744 # check for zeros; note that cmp(0, -0) should return 0
745 if not self:
746 if not other:
747 return 0
748 else:
749 return -((-1)**other._sign)
750 if not other:
751 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000752
Facundo Batista59c58842007-04-10 12:58:45 +0000753 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000754 if other._sign < self._sign:
755 return -1
756 if self._sign < other._sign:
757 return 1
758
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000759 self_adjusted = self.adjusted()
760 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000761 if self_adjusted == other_adjusted:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000762 self_padded = self._int + '0'*(self._exp - other._exp)
763 other_padded = other._int + '0'*(other._exp - self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +0000764 return cmp(self_padded, other_padded) * (-1)**self._sign
765 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000766 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000767 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000768 return -((-1)**self._sign)
769
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000770 def __eq__(self, other):
771 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000772 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000773 return self.__cmp__(other) == 0
774
775 def __ne__(self, other):
776 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000777 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000778 return self.__cmp__(other) != 0
779
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000780 def compare(self, other, context=None):
781 """Compares one to another.
782
783 -1 => a < b
784 0 => a = b
785 1 => a > b
786 NaN => one is NaN
787 Like __cmp__, but returns Decimal instances.
788 """
Facundo Batista353750c2007-09-13 18:13:15 +0000789 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000790
Facundo Batista59c58842007-04-10 12:58:45 +0000791 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000792 if (self._is_special or other and other._is_special):
793 ans = self._check_nans(other, context)
794 if ans:
795 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000796
Facundo Batista353750c2007-09-13 18:13:15 +0000797 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000798
799 def __hash__(self):
800 """x.__hash__() <==> hash(x)"""
801 # Decimal integers must hash the same as the ints
802 # Non-integer decimals are normalized and hashed as strings
Georg Brandl1fb9f522006-05-11 19:57:09 +0000803 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000804 if self._is_special:
805 if self._isnan():
806 raise TypeError('Cannot hash a NaN value.')
807 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000808 if not self:
809 return 0
810 if self._isinteger():
811 op = _WorkRep(self.to_integral_value())
812 # to make computation feasible for Decimals with large
813 # exponent, we use the fact that hash(n) == hash(m) for
814 # any two nonzero integers n and m such that (i) n and m
815 # have the same sign, and (ii) n is congruent to m modulo
816 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
817 # hash((-1)**s*c*pow(10, e, 2**64-1).
818 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000819 return hash(str(self.normalize()))
820
821 def as_tuple(self):
822 """Represents the number as a triple tuple.
823
824 To show the internals exactly as they are.
825 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000826 return (self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000827
828 def __repr__(self):
829 """Represents the number as an instance of Decimal."""
830 # Invariant: eval(repr(d)) == d
831 return 'Decimal("%s")' % str(self)
832
Facundo Batista353750c2007-09-13 18:13:15 +0000833 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000834 """Return string representation of the number in scientific notation.
835
836 Captures all of the information in the underlying representation.
837 """
838
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000839 if self._is_special:
840 if self._isnan():
841 minus = '-'*self._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +0000842 if self._int == '0':
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000843 info = ''
844 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000845 info = self._int
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000846 if self._isnan() == 2:
847 return minus + 'sNaN' + info
848 return minus + 'NaN' + info
849 if self._isinfinity():
850 minus = '-'*self._sign
851 return minus + 'Infinity'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000852
853 if context is None:
854 context = getcontext()
855
Facundo Batista72bc54f2007-11-23 17:59:00 +0000856 tmp = list(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000857 numdigits = len(self._int)
858 leftdigits = self._exp + numdigits
Facundo Batista59c58842007-04-10 12:58:45 +0000859 if eng and not self: # self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
860 if self._exp < 0 and self._exp >= -6: # short, no need for e/E
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000861 s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
862 return s
Facundo Batista59c58842007-04-10 12:58:45 +0000863 # exp is closest mult. of 3 >= self._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000864 exp = ((self._exp - 1)// 3 + 1) * 3
865 if exp != self._exp:
866 s = '0.'+'0'*(exp - self._exp)
867 else:
868 s = '0'
869 if exp != 0:
870 if context.capitals:
871 s += 'E'
872 else:
873 s += 'e'
874 if exp > 0:
Facundo Batista59c58842007-04-10 12:58:45 +0000875 s += '+' # 0.0e+3, not 0.0e3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000876 s += str(exp)
877 s = '-'*self._sign + s
878 return s
879 if eng:
880 dotplace = (leftdigits-1)%3+1
881 adjexp = leftdigits -1 - (leftdigits-1)%3
882 else:
883 adjexp = leftdigits-1
884 dotplace = 1
885 if self._exp == 0:
886 pass
887 elif self._exp < 0 and adjexp >= 0:
888 tmp.insert(leftdigits, '.')
889 elif self._exp < 0 and adjexp >= -6:
890 tmp[0:0] = ['0'] * int(-leftdigits)
891 tmp.insert(0, '0.')
892 else:
893 if numdigits > dotplace:
894 tmp.insert(dotplace, '.')
895 elif numdigits < dotplace:
896 tmp.extend(['0']*(dotplace-numdigits))
897 if adjexp:
898 if not context.capitals:
899 tmp.append('e')
900 else:
901 tmp.append('E')
902 if adjexp > 0:
903 tmp.append('+')
904 tmp.append(str(adjexp))
905 if eng:
906 while tmp[0:1] == ['0']:
907 tmp[0:1] = []
908 if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
909 tmp[0:0] = ['0']
910 if self._sign:
911 tmp.insert(0, '-')
912
913 return ''.join(tmp)
914
915 def to_eng_string(self, context=None):
916 """Convert to engineering-type string.
917
918 Engineering notation has an exponent which is a multiple of 3, so there
919 are up to 3 digits left of the decimal place.
920
921 Same rules for when in exponential and when as a value as in __str__.
922 """
Facundo Batista353750c2007-09-13 18:13:15 +0000923 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000924
925 def __neg__(self, context=None):
926 """Returns a copy with the sign switched.
927
928 Rounds, if it has reason.
929 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000930 if self._is_special:
931 ans = self._check_nans(context=context)
932 if ans:
933 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000934
935 if not self:
936 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +0000937 ans = self.copy_sign(Dec_0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000938 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000939 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000940
941 if context is None:
942 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000943 if context._rounding_decision == ALWAYS_ROUND:
Facundo Batista353750c2007-09-13 18:13:15 +0000944 return ans._fix(context)
945 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000946
947 def __pos__(self, context=None):
948 """Returns a copy, unless it is a sNaN.
949
950 Rounds the number (if more then precision digits)
951 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000952 if self._is_special:
953 ans = self._check_nans(context=context)
954 if ans:
955 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000956
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000957 if not self:
958 # + (-0) = 0
Facundo Batista353750c2007-09-13 18:13:15 +0000959 ans = self.copy_sign(Dec_0)
960 else:
961 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000962
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000963 if context is None:
964 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000965 if context._rounding_decision == ALWAYS_ROUND:
Facundo Batista353750c2007-09-13 18:13:15 +0000966 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000967 return ans
968
969 def __abs__(self, round=1, context=None):
970 """Returns the absolute value of self.
971
972 If the second argument is 0, do not round.
973 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000974 if self._is_special:
975 ans = self._check_nans(context=context)
976 if ans:
977 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000978
979 if not round:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000980 if context is None:
981 context = getcontext()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000982 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000983 context._set_rounding_decision(NEVER_ROUND)
984
985 if self._sign:
986 ans = self.__neg__(context=context)
987 else:
988 ans = self.__pos__(context=context)
989
990 return ans
991
992 def __add__(self, other, context=None):
993 """Returns self + other.
994
995 -INF + INF (or the reverse) cause InvalidOperation errors.
996 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000997 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000998 if other is NotImplemented:
999 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001000
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001001 if context is None:
1002 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001003
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001004 if self._is_special or other._is_special:
1005 ans = self._check_nans(other, context)
1006 if ans:
1007 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001008
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001009 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001010 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001011 if self._sign != other._sign and other._isinfinity():
1012 return context._raise_error(InvalidOperation, '-INF + INF')
1013 return Decimal(self)
1014 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001015 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001016
1017 shouldround = context._rounding_decision == ALWAYS_ROUND
1018
1019 exp = min(self._exp, other._exp)
1020 negativezero = 0
1021 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +00001022 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001023 negativezero = 1
1024
1025 if not self and not other:
1026 sign = min(self._sign, other._sign)
1027 if negativezero:
1028 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001029 ans = _dec_from_triple(sign, '0', exp)
Facundo Batista353750c2007-09-13 18:13:15 +00001030 if shouldround:
1031 ans = ans._fix(context)
1032 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001033 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001034 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001035 ans = other._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001036 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001037 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001038 return ans
1039 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001040 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001041 ans = self._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001042 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001043 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001044 return ans
1045
1046 op1 = _WorkRep(self)
1047 op2 = _WorkRep(other)
1048 op1, op2 = _normalize(op1, op2, shouldround, context.prec)
1049
1050 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001051 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001052 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001053 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001054 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batista353750c2007-09-13 18:13:15 +00001055 if shouldround:
1056 ans = ans._fix(context)
1057 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001058 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001059 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001060 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001061 if op1.sign == 1:
1062 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001063 op1.sign, op2.sign = op2.sign, op1.sign
1064 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001065 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001066 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001067 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001068 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001069 op1.sign, op2.sign = (0, 0)
1070 else:
1071 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001072 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001073
Raymond Hettinger17931de2004-10-27 06:21:46 +00001074 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001075 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001076 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001077 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001078
1079 result.exp = op1.exp
1080 ans = Decimal(result)
1081 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001082 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001083 return ans
1084
1085 __radd__ = __add__
1086
1087 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001088 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001089 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001090 if other is NotImplemented:
1091 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001092
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001093 if self._is_special or other._is_special:
1094 ans = self._check_nans(other, context=context)
1095 if ans:
1096 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001097
Facundo Batista353750c2007-09-13 18:13:15 +00001098 # self - other is computed as self + other.copy_negate()
1099 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001100
1101 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001102 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001103 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001104 if other is NotImplemented:
1105 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001106
Facundo Batista353750c2007-09-13 18:13:15 +00001107 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001108
Facundo Batista353750c2007-09-13 18:13:15 +00001109 def _increment(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001110 """Special case of add, adding 1eExponent
1111
1112 Since it is common, (rounding, for example) this adds
1113 (sign)*one E self._exp to the number more efficiently than add.
1114
Facundo Batista353750c2007-09-13 18:13:15 +00001115 Assumes that self is nonspecial.
1116
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001117 For example:
1118 Decimal('5.624e10')._increment() == Decimal('5.625e10')
1119 """
Facundo Batista72bc54f2007-11-23 17:59:00 +00001120 L = map(int, self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001121 L[-1] += 1
1122 spot = len(L)-1
1123 while L[spot] == 10:
1124 L[spot] = 0
1125 if spot == 0:
1126 L[0:0] = [1]
1127 break
1128 L[spot-1] += 1
1129 spot -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001130 return _dec_from_triple(self._sign, "".join(map(str, L)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001131
1132 def __mul__(self, other, context=None):
1133 """Return self * other.
1134
1135 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1136 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001137 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001138 if other is NotImplemented:
1139 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001140
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141 if context is None:
1142 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001143
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001144 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001145
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001146 if self._is_special or other._is_special:
1147 ans = self._check_nans(other, context)
1148 if ans:
1149 return ans
1150
1151 if self._isinfinity():
1152 if not other:
1153 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1154 return Infsign[resultsign]
1155
1156 if other._isinfinity():
1157 if not self:
1158 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1159 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001160
1161 resultexp = self._exp + other._exp
1162 shouldround = context._rounding_decision == ALWAYS_ROUND
1163
1164 # Special case for multiplying by zero
1165 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001166 ans = _dec_from_triple(resultsign, '0', resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001167 if shouldround:
Facundo Batista59c58842007-04-10 12:58:45 +00001168 # Fixing in case the exponent is out of bounds
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001169 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001170 return ans
1171
1172 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001173 if self._int == '1':
1174 ans = _dec_from_triple(resultsign, other._int, resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001175 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001176 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001177 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001178 if other._int == '1':
1179 ans = _dec_from_triple(resultsign, self._int, resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001180 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001181 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001182 return ans
1183
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001184 op1 = _WorkRep(self)
1185 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001186
Facundo Batista72bc54f2007-11-23 17:59:00 +00001187 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001188 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001189 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001190
1191 return ans
1192 __rmul__ = __mul__
1193
1194 def __div__(self, other, context=None):
1195 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001196 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001197 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001198 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001199
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001200 if context is None:
1201 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001202
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001203 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001204
1205 if self._is_special or other._is_special:
1206 ans = self._check_nans(other, context)
1207 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001208 return ans
1209
1210 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001211 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001212
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001213 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001214 return Infsign[sign]
1215
1216 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001217 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001218 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001219
1220 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001221 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001222 if not self:
1223 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001224 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001225
Facundo Batistacce8df22007-09-18 16:53:18 +00001226 if not self:
1227 exp = self._exp - other._exp
1228 coeff = 0
1229 else:
1230 # OK, so neither = 0, INF or NaN
1231 shift = len(other._int) - len(self._int) + context.prec + 1
1232 exp = self._exp - other._exp - shift
1233 op1 = _WorkRep(self)
1234 op2 = _WorkRep(other)
1235 if shift >= 0:
1236 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1237 else:
1238 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1239 if remainder:
1240 # result is not exact; adjust to ensure correct rounding
1241 if coeff % 5 == 0:
1242 coeff += 1
1243 else:
1244 # result is exact; get as close to ideal exponent as possible
1245 ideal_exp = self._exp - other._exp
1246 while exp < ideal_exp and coeff % 10 == 0:
1247 coeff //= 10
1248 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001249
Facundo Batista72bc54f2007-11-23 17:59:00 +00001250 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001251 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001252
Facundo Batistacce8df22007-09-18 16:53:18 +00001253 __truediv__ = __div__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001254
Facundo Batistacce8df22007-09-18 16:53:18 +00001255 def _divide(self, other, context):
1256 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001257
Facundo Batistacce8df22007-09-18 16:53:18 +00001258 Assumes that neither self nor other is a NaN, that self is not
1259 infinite and that other is nonzero.
1260 """
1261 sign = self._sign ^ other._sign
1262 if other._isinfinity():
1263 ideal_exp = self._exp
1264 else:
1265 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001266
Facundo Batistacce8df22007-09-18 16:53:18 +00001267 expdiff = self.adjusted() - other.adjusted()
1268 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001269 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001270 self._rescale(ideal_exp, context.rounding))
1271 if expdiff <= context.prec:
1272 op1 = _WorkRep(self)
1273 op2 = _WorkRep(other)
1274 if op1.exp >= op2.exp:
1275 op1.int *= 10**(op1.exp - op2.exp)
1276 else:
1277 op2.int *= 10**(op2.exp - op1.exp)
1278 q, r = divmod(op1.int, op2.int)
1279 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001280 return (_dec_from_triple(sign, str(q), 0),
1281 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001282
Facundo Batistacce8df22007-09-18 16:53:18 +00001283 # Here the quotient is too large to be representable
1284 ans = context._raise_error(DivisionImpossible,
1285 'quotient too large in //, % or divmod')
1286 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001287
1288 def __rdiv__(self, other, context=None):
1289 """Swaps self/other and returns __div__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001290 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001291 if other is NotImplemented:
1292 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001293 return other.__div__(self, context=context)
1294 __rtruediv__ = __rdiv__
1295
1296 def __divmod__(self, other, context=None):
1297 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001298 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001299 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001300 other = _convert_other(other)
1301 if other is NotImplemented:
1302 return other
1303
1304 if context is None:
1305 context = getcontext()
1306
1307 ans = self._check_nans(other, context)
1308 if ans:
1309 return (ans, ans)
1310
1311 sign = self._sign ^ other._sign
1312 if self._isinfinity():
1313 if other._isinfinity():
1314 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1315 return ans, ans
1316 else:
1317 return (Infsign[sign],
1318 context._raise_error(InvalidOperation, 'INF % x'))
1319
1320 if not other:
1321 if not self:
1322 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1323 return ans, ans
1324 else:
1325 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1326 context._raise_error(InvalidOperation, 'x % 0'))
1327
1328 quotient, remainder = self._divide(other, context)
1329 if context._rounding_decision == ALWAYS_ROUND:
1330 remainder = remainder._fix(context)
1331 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001332
1333 def __rdivmod__(self, other, context=None):
1334 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001335 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001336 if other is NotImplemented:
1337 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001338 return other.__divmod__(self, context=context)
1339
1340 def __mod__(self, other, context=None):
1341 """
1342 self % other
1343 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001344 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001345 if other is NotImplemented:
1346 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001347
Facundo Batistacce8df22007-09-18 16:53:18 +00001348 if context is None:
1349 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001350
Facundo Batistacce8df22007-09-18 16:53:18 +00001351 ans = self._check_nans(other, context)
1352 if ans:
1353 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001354
Facundo Batistacce8df22007-09-18 16:53:18 +00001355 if self._isinfinity():
1356 return context._raise_error(InvalidOperation, 'INF % x')
1357 elif not other:
1358 if self:
1359 return context._raise_error(InvalidOperation, 'x % 0')
1360 else:
1361 return context._raise_error(DivisionUndefined, '0 % 0')
1362
1363 remainder = self._divide(other, context)[1]
1364 if context._rounding_decision == ALWAYS_ROUND:
1365 remainder = remainder._fix(context)
1366 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001367
1368 def __rmod__(self, other, context=None):
1369 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001370 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001371 if other is NotImplemented:
1372 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001373 return other.__mod__(self, context=context)
1374
1375 def remainder_near(self, other, context=None):
1376 """
1377 Remainder nearest to 0- abs(remainder-near) <= other/2
1378 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001379 if context is None:
1380 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001381
Facundo Batista353750c2007-09-13 18:13:15 +00001382 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001383
Facundo Batista353750c2007-09-13 18:13:15 +00001384 ans = self._check_nans(other, context)
1385 if ans:
1386 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001387
Facundo Batista353750c2007-09-13 18:13:15 +00001388 # self == +/-infinity -> InvalidOperation
1389 if self._isinfinity():
1390 return context._raise_error(InvalidOperation,
1391 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001392
Facundo Batista353750c2007-09-13 18:13:15 +00001393 # other == 0 -> either InvalidOperation or DivisionUndefined
1394 if not other:
1395 if self:
1396 return context._raise_error(InvalidOperation,
1397 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001398 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001399 return context._raise_error(DivisionUndefined,
1400 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001401
Facundo Batista353750c2007-09-13 18:13:15 +00001402 # other = +/-infinity -> remainder = self
1403 if other._isinfinity():
1404 ans = Decimal(self)
1405 return ans._fix(context)
1406
1407 # self = 0 -> remainder = self, with ideal exponent
1408 ideal_exponent = min(self._exp, other._exp)
1409 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001410 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001411 return ans._fix(context)
1412
1413 # catch most cases of large or small quotient
1414 expdiff = self.adjusted() - other.adjusted()
1415 if expdiff >= context.prec + 1:
1416 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001417 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001418 if expdiff <= -2:
1419 # expdiff <= -2 => abs(self/other) < 0.1
1420 ans = self._rescale(ideal_exponent, context.rounding)
1421 return ans._fix(context)
1422
1423 # adjust both arguments to have the same exponent, then divide
1424 op1 = _WorkRep(self)
1425 op2 = _WorkRep(other)
1426 if op1.exp >= op2.exp:
1427 op1.int *= 10**(op1.exp - op2.exp)
1428 else:
1429 op2.int *= 10**(op2.exp - op1.exp)
1430 q, r = divmod(op1.int, op2.int)
1431 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1432 # 10**ideal_exponent. Apply correction to ensure that
1433 # abs(remainder) <= abs(other)/2
1434 if 2*r + (q&1) > op2.int:
1435 r -= op2.int
1436 q += 1
1437
1438 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001439 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001440
1441 # result has same sign as self unless r is negative
1442 sign = self._sign
1443 if r < 0:
1444 sign = 1-sign
1445 r = -r
1446
Facundo Batista72bc54f2007-11-23 17:59:00 +00001447 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001448 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001449
1450 def __floordiv__(self, other, context=None):
1451 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001452 other = _convert_other(other)
1453 if other is NotImplemented:
1454 return other
1455
1456 if context is None:
1457 context = getcontext()
1458
1459 ans = self._check_nans(other, context)
1460 if ans:
1461 return ans
1462
1463 if self._isinfinity():
1464 if other._isinfinity():
1465 return context._raise_error(InvalidOperation, 'INF // INF')
1466 else:
1467 return Infsign[self._sign ^ other._sign]
1468
1469 if not other:
1470 if self:
1471 return context._raise_error(DivisionByZero, 'x // 0',
1472 self._sign ^ other._sign)
1473 else:
1474 return context._raise_error(DivisionUndefined, '0 // 0')
1475
1476 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001477
1478 def __rfloordiv__(self, other, context=None):
1479 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001480 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001481 if other is NotImplemented:
1482 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001483 return other.__floordiv__(self, context=context)
1484
1485 def __float__(self):
1486 """Float representation."""
1487 return float(str(self))
1488
1489 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001490 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001491 if self._is_special:
1492 if self._isnan():
1493 context = getcontext()
1494 return context._raise_error(InvalidContext)
1495 elif self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001496 raise OverflowError("Cannot convert infinity to long")
Facundo Batista353750c2007-09-13 18:13:15 +00001497 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001498 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001499 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001500 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001501 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001502
1503 def __long__(self):
1504 """Converts to a long.
1505
1506 Equivalent to long(int(self))
1507 """
1508 return long(self.__int__())
1509
Facundo Batista353750c2007-09-13 18:13:15 +00001510 def _fix_nan(self, context):
1511 """Decapitate the payload of a NaN to fit the context"""
1512 payload = self._int
1513
1514 # maximum length of payload is precision if _clamp=0,
1515 # precision-1 if _clamp=1.
1516 max_payload_len = context.prec - context._clamp
1517 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001518 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1519 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001520 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001521
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001522 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001523 """Round if it is necessary to keep self within prec precision.
1524
1525 Rounds and fixes the exponent. Does not raise on a sNaN.
1526
1527 Arguments:
1528 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001529 context - context used.
1530 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001531
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001532 if context is None:
1533 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001534
Facundo Batista353750c2007-09-13 18:13:15 +00001535 if self._is_special:
1536 if self._isnan():
1537 # decapitate payload if necessary
1538 return self._fix_nan(context)
1539 else:
1540 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001541 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001542
Facundo Batista353750c2007-09-13 18:13:15 +00001543 # if self is zero then exponent should be between Etiny and
1544 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1545 Etiny = context.Etiny()
1546 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001547 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001548 exp_max = [context.Emax, Etop][context._clamp]
1549 new_exp = min(max(self._exp, Etiny), exp_max)
1550 if new_exp != self._exp:
1551 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001552 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001553 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001554 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001555
1556 # exp_min is the smallest allowable exponent of the result,
1557 # equal to max(self.adjusted()-context.prec+1, Etiny)
1558 exp_min = len(self._int) + self._exp - context.prec
1559 if exp_min > Etop:
1560 # overflow: exp_min > Etop iff self.adjusted() > Emax
1561 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001562 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001563 return context._raise_error(Overflow, 'above Emax', self._sign)
1564 self_is_subnormal = exp_min < Etiny
1565 if self_is_subnormal:
1566 context._raise_error(Subnormal)
1567 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001568
Facundo Batista353750c2007-09-13 18:13:15 +00001569 # round if self has too many digits
1570 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001571 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001572 ans = self._rescale(exp_min, context.rounding)
1573 if ans != self:
1574 context._raise_error(Inexact)
1575 if self_is_subnormal:
1576 context._raise_error(Underflow)
1577 if not ans:
1578 # raise Clamped on underflow to 0
1579 context._raise_error(Clamped)
1580 elif len(ans._int) == context.prec+1:
1581 # we get here only if rescaling rounds the
1582 # cofficient up to exactly 10**context.prec
1583 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001584 ans = _dec_from_triple(ans._sign,
1585 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001586 else:
1587 # Inexact and Rounded have already been raised
1588 ans = context._raise_error(Overflow, 'above Emax',
1589 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001590 return ans
1591
Facundo Batista353750c2007-09-13 18:13:15 +00001592 # fold down if _clamp == 1 and self has too few digits
1593 if context._clamp == 1 and self._exp > Etop:
1594 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001595 self_padded = self._int + '0'*(self._exp - Etop)
1596 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001597
Facundo Batista353750c2007-09-13 18:13:15 +00001598 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001599 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001600
1601 _pick_rounding_function = {}
1602
Facundo Batista353750c2007-09-13 18:13:15 +00001603 # for each of the rounding functions below:
1604 # self is a finite, nonzero Decimal
1605 # prec is an integer satisfying 0 <= prec < len(self._int)
1606 # the rounded result will have exponent self._exp + len(self._int) - prec;
1607
1608 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001609 """Also known as round-towards-0, truncate."""
Facundo Batista353750c2007-09-13 18:13:15 +00001610 newexp = self._exp + len(self._int) - prec
Facundo Batista72bc54f2007-11-23 17:59:00 +00001611 return _dec_from_triple(self._sign, self._int[:prec] or '0', newexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001612
Facundo Batista353750c2007-09-13 18:13:15 +00001613 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001614 """Rounds away from 0."""
Facundo Batista353750c2007-09-13 18:13:15 +00001615 newexp = self._exp + len(self._int) - prec
Facundo Batista72bc54f2007-11-23 17:59:00 +00001616 tmp = _dec_from_triple(self._sign, self._int[:prec] or '0', newexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001617 for digit in self._int[prec:]:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001618 if digit != '0':
Facundo Batista353750c2007-09-13 18:13:15 +00001619 return tmp._increment()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001620 return tmp
1621
Facundo Batista353750c2007-09-13 18:13:15 +00001622 def _round_half_up(self, prec):
1623 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001624 if self._int[prec] in '56789':
Facundo Batista353750c2007-09-13 18:13:15 +00001625 return self._round_up(prec)
1626 else:
1627 return self._round_down(prec)
1628
1629 def _round_half_down(self, prec):
1630 """Round 5 down"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001631 if self._int[prec] == '5':
Facundo Batista353750c2007-09-13 18:13:15 +00001632 for digit in self._int[prec+1:]:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001633 if digit != '0':
Facundo Batista353750c2007-09-13 18:13:15 +00001634 break
1635 else:
1636 return self._round_down(prec)
1637 return self._round_half_up(prec)
1638
1639 def _round_half_even(self, prec):
1640 """Round 5 to even, rest to nearest."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001641 if prec and self._int[prec-1] in '13579':
Facundo Batista353750c2007-09-13 18:13:15 +00001642 return self._round_half_up(prec)
1643 else:
1644 return self._round_half_down(prec)
1645
1646 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001647 """Rounds up (not away from 0 if negative.)"""
1648 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001649 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001650 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001651 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001652
Facundo Batista353750c2007-09-13 18:13:15 +00001653 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001654 """Rounds down (not towards 0 if negative)"""
1655 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001656 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001657 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001658 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001659
Facundo Batista353750c2007-09-13 18:13:15 +00001660 def _round_05up(self, prec):
1661 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001662 if prec == 0 or self._int[prec-1] in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001663 return self._round_up(prec)
1664 else:
1665 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001666
Facundo Batista353750c2007-09-13 18:13:15 +00001667 def fma(self, other, third, context=None):
1668 """Fused multiply-add.
1669
1670 Returns self*other+third with no rounding of the intermediate
1671 product self*other.
1672
1673 self and other are multiplied together, with no rounding of
1674 the result. The third operand is then added to the result,
1675 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001676 """
Facundo Batista353750c2007-09-13 18:13:15 +00001677
1678 other = _convert_other(other, raiseit=True)
1679 third = _convert_other(third, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001680
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001681 if context is None:
1682 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001683
Facundo Batista353750c2007-09-13 18:13:15 +00001684 # do self*other in fresh context with no traps and no rounding
1685 mul_context = Context(traps=[], flags=[],
1686 _rounding_decision=NEVER_ROUND)
1687 product = self.__mul__(other, mul_context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001688
Facundo Batista353750c2007-09-13 18:13:15 +00001689 if mul_context.flags[InvalidOperation]:
1690 # reraise in current context
1691 return context._raise_error(InvalidOperation,
1692 'invalid multiplication in fma',
1693 1, product)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001694
Facundo Batista353750c2007-09-13 18:13:15 +00001695 ans = product.__add__(third, context)
1696 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001697
Facundo Batista353750c2007-09-13 18:13:15 +00001698 def _power_modulo(self, other, modulo, context=None):
1699 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001700
Facundo Batista353750c2007-09-13 18:13:15 +00001701 # if can't convert other and modulo to Decimal, raise
1702 # TypeError; there's no point returning NotImplemented (no
1703 # equivalent of __rpow__ for three argument pow)
1704 other = _convert_other(other, raiseit=True)
1705 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001706
Facundo Batista353750c2007-09-13 18:13:15 +00001707 if context is None:
1708 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001709
Facundo Batista353750c2007-09-13 18:13:15 +00001710 # deal with NaNs: if there are any sNaNs then first one wins,
1711 # (i.e. behaviour for NaNs is identical to that of fma)
1712 self_is_nan = self._isnan()
1713 other_is_nan = other._isnan()
1714 modulo_is_nan = modulo._isnan()
1715 if self_is_nan or other_is_nan or modulo_is_nan:
1716 if self_is_nan == 2:
1717 return context._raise_error(InvalidOperation, 'sNaN',
1718 1, self)
1719 if other_is_nan == 2:
1720 return context._raise_error(InvalidOperation, 'sNaN',
1721 1, other)
1722 if modulo_is_nan == 2:
1723 return context._raise_error(InvalidOperation, 'sNaN',
1724 1, modulo)
1725 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001726 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001727 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001728 return other._fix_nan(context)
1729 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001730
Facundo Batista353750c2007-09-13 18:13:15 +00001731 # check inputs: we apply same restrictions as Python's pow()
1732 if not (self._isinteger() and
1733 other._isinteger() and
1734 modulo._isinteger()):
1735 return context._raise_error(InvalidOperation,
1736 'pow() 3rd argument not allowed '
1737 'unless all arguments are integers')
1738 if other < 0:
1739 return context._raise_error(InvalidOperation,
1740 'pow() 2nd argument cannot be '
1741 'negative when 3rd argument specified')
1742 if not modulo:
1743 return context._raise_error(InvalidOperation,
1744 'pow() 3rd argument cannot be 0')
1745
1746 # additional restriction for decimal: the modulus must be less
1747 # than 10**prec in absolute value
1748 if modulo.adjusted() >= context.prec:
1749 return context._raise_error(InvalidOperation,
1750 'insufficient precision: pow() 3rd '
1751 'argument must not have more than '
1752 'precision digits')
1753
1754 # define 0**0 == NaN, for consistency with two-argument pow
1755 # (even though it hurts!)
1756 if not other and not self:
1757 return context._raise_error(InvalidOperation,
1758 'at least one of pow() 1st argument '
1759 'and 2nd argument must be nonzero ;'
1760 '0**0 is not defined')
1761
1762 # compute sign of result
1763 if other._iseven():
1764 sign = 0
1765 else:
1766 sign = self._sign
1767
1768 # convert modulo to a Python integer, and self and other to
1769 # Decimal integers (i.e. force their exponents to be >= 0)
1770 modulo = abs(int(modulo))
1771 base = _WorkRep(self.to_integral_value())
1772 exponent = _WorkRep(other.to_integral_value())
1773
1774 # compute result using integer pow()
1775 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1776 for i in xrange(exponent.exp):
1777 base = pow(base, 10, modulo)
1778 base = pow(base, exponent.int, modulo)
1779
Facundo Batista72bc54f2007-11-23 17:59:00 +00001780 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001781
1782 def _power_exact(self, other, p):
1783 """Attempt to compute self**other exactly.
1784
1785 Given Decimals self and other and an integer p, attempt to
1786 compute an exact result for the power self**other, with p
1787 digits of precision. Return None if self**other is not
1788 exactly representable in p digits.
1789
1790 Assumes that elimination of special cases has already been
1791 performed: self and other must both be nonspecial; self must
1792 be positive and not numerically equal to 1; other must be
1793 nonzero. For efficiency, other._exp should not be too large,
1794 so that 10**abs(other._exp) is a feasible calculation."""
1795
1796 # In the comments below, we write x for the value of self and
1797 # y for the value of other. Write x = xc*10**xe and y =
1798 # yc*10**ye.
1799
1800 # The main purpose of this method is to identify the *failure*
1801 # of x**y to be exactly representable with as little effort as
1802 # possible. So we look for cheap and easy tests that
1803 # eliminate the possibility of x**y being exact. Only if all
1804 # these tests are passed do we go on to actually compute x**y.
1805
1806 # Here's the main idea. First normalize both x and y. We
1807 # express y as a rational m/n, with m and n relatively prime
1808 # and n>0. Then for x**y to be exactly representable (at
1809 # *any* precision), xc must be the nth power of a positive
1810 # integer and xe must be divisible by n. If m is negative
1811 # then additionally xc must be a power of either 2 or 5, hence
1812 # a power of 2**n or 5**n.
1813 #
1814 # There's a limit to how small |y| can be: if y=m/n as above
1815 # then:
1816 #
1817 # (1) if xc != 1 then for the result to be representable we
1818 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1819 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1820 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1821 # representable.
1822 #
1823 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1824 # |y| < 1/|xe| then the result is not representable.
1825 #
1826 # Note that since x is not equal to 1, at least one of (1) and
1827 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1828 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1829 #
1830 # There's also a limit to how large y can be, at least if it's
1831 # positive: the normalized result will have coefficient xc**y,
1832 # so if it's representable then xc**y < 10**p, and y <
1833 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1834 # not exactly representable.
1835
1836 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1837 # so |y| < 1/xe and the result is not representable.
1838 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1839 # < 1/nbits(xc).
1840
1841 x = _WorkRep(self)
1842 xc, xe = x.int, x.exp
1843 while xc % 10 == 0:
1844 xc //= 10
1845 xe += 1
1846
1847 y = _WorkRep(other)
1848 yc, ye = y.int, y.exp
1849 while yc % 10 == 0:
1850 yc //= 10
1851 ye += 1
1852
1853 # case where xc == 1: result is 10**(xe*y), with xe*y
1854 # required to be an integer
1855 if xc == 1:
1856 if ye >= 0:
1857 exponent = xe*yc*10**ye
1858 else:
1859 exponent, remainder = divmod(xe*yc, 10**-ye)
1860 if remainder:
1861 return None
1862 if y.sign == 1:
1863 exponent = -exponent
1864 # if other is a nonnegative integer, use ideal exponent
1865 if other._isinteger() and other._sign == 0:
1866 ideal_exponent = self._exp*int(other)
1867 zeros = min(exponent-ideal_exponent, p-1)
1868 else:
1869 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001870 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001871
1872 # case where y is negative: xc must be either a power
1873 # of 2 or a power of 5.
1874 if y.sign == 1:
1875 last_digit = xc % 10
1876 if last_digit in (2,4,6,8):
1877 # quick test for power of 2
1878 if xc & -xc != xc:
1879 return None
1880 # now xc is a power of 2; e is its exponent
1881 e = _nbits(xc)-1
1882 # find e*y and xe*y; both must be integers
1883 if ye >= 0:
1884 y_as_int = yc*10**ye
1885 e = e*y_as_int
1886 xe = xe*y_as_int
1887 else:
1888 ten_pow = 10**-ye
1889 e, remainder = divmod(e*yc, ten_pow)
1890 if remainder:
1891 return None
1892 xe, remainder = divmod(xe*yc, ten_pow)
1893 if remainder:
1894 return None
1895
1896 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1897 return None
1898 xc = 5**e
1899
1900 elif last_digit == 5:
1901 # e >= log_5(xc) if xc is a power of 5; we have
1902 # equality all the way up to xc=5**2658
1903 e = _nbits(xc)*28//65
1904 xc, remainder = divmod(5**e, xc)
1905 if remainder:
1906 return None
1907 while xc % 5 == 0:
1908 xc //= 5
1909 e -= 1
1910 if ye >= 0:
1911 y_as_integer = yc*10**ye
1912 e = e*y_as_integer
1913 xe = xe*y_as_integer
1914 else:
1915 ten_pow = 10**-ye
1916 e, remainder = divmod(e*yc, ten_pow)
1917 if remainder:
1918 return None
1919 xe, remainder = divmod(xe*yc, ten_pow)
1920 if remainder:
1921 return None
1922 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1923 return None
1924 xc = 2**e
1925 else:
1926 return None
1927
1928 if xc >= 10**p:
1929 return None
1930 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00001931 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00001932
1933 # now y is positive; find m and n such that y = m/n
1934 if ye >= 0:
1935 m, n = yc*10**ye, 1
1936 else:
1937 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1938 return None
1939 xc_bits = _nbits(xc)
1940 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1941 return None
1942 m, n = yc, 10**(-ye)
1943 while m % 2 == n % 2 == 0:
1944 m //= 2
1945 n //= 2
1946 while m % 5 == n % 5 == 0:
1947 m //= 5
1948 n //= 5
1949
1950 # compute nth root of xc*10**xe
1951 if n > 1:
1952 # if 1 < xc < 2**n then xc isn't an nth power
1953 if xc != 1 and xc_bits <= n:
1954 return None
1955
1956 xe, rem = divmod(xe, n)
1957 if rem != 0:
1958 return None
1959
1960 # compute nth root of xc using Newton's method
1961 a = 1L << -(-_nbits(xc)//n) # initial estimate
1962 while True:
1963 q, r = divmod(xc, a**(n-1))
1964 if a <= q:
1965 break
1966 else:
1967 a = (a*(n-1) + q)//n
1968 if not (a == q and r == 0):
1969 return None
1970 xc = a
1971
1972 # now xc*10**xe is the nth root of the original xc*10**xe
1973 # compute mth power of xc*10**xe
1974
1975 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1976 # 10**p and the result is not representable.
1977 if xc > 1 and m > p*100//_log10_lb(xc):
1978 return None
1979 xc = xc**m
1980 xe *= m
1981 if xc > 10**p:
1982 return None
1983
1984 # by this point the result *is* exactly representable
1985 # adjust the exponent to get as close as possible to the ideal
1986 # exponent, if necessary
1987 str_xc = str(xc)
1988 if other._isinteger() and other._sign == 0:
1989 ideal_exponent = self._exp*int(other)
1990 zeros = min(xe-ideal_exponent, p-len(str_xc))
1991 else:
1992 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001993 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001994
1995 def __pow__(self, other, modulo=None, context=None):
1996 """Return self ** other [ % modulo].
1997
1998 With two arguments, compute self**other.
1999
2000 With three arguments, compute (self**other) % modulo. For the
2001 three argument form, the following restrictions on the
2002 arguments hold:
2003
2004 - all three arguments must be integral
2005 - other must be nonnegative
2006 - either self or other (or both) must be nonzero
2007 - modulo must be nonzero and must have at most p digits,
2008 where p is the context precision.
2009
2010 If any of these restrictions is violated the InvalidOperation
2011 flag is raised.
2012
2013 The result of pow(self, other, modulo) is identical to the
2014 result that would be obtained by computing (self**other) %
2015 modulo with unbounded precision, but is computed more
2016 efficiently. It is always exact.
2017 """
2018
2019 if modulo is not None:
2020 return self._power_modulo(other, modulo, context)
2021
2022 other = _convert_other(other)
2023 if other is NotImplemented:
2024 return other
2025
2026 if context is None:
2027 context = getcontext()
2028
2029 # either argument is a NaN => result is NaN
2030 ans = self._check_nans(other, context)
2031 if ans:
2032 return ans
2033
2034 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2035 if not other:
2036 if not self:
2037 return context._raise_error(InvalidOperation, '0 ** 0')
2038 else:
2039 return Dec_p1
2040
2041 # result has sign 1 iff self._sign is 1 and other is an odd integer
2042 result_sign = 0
2043 if self._sign == 1:
2044 if other._isinteger():
2045 if not other._iseven():
2046 result_sign = 1
2047 else:
2048 # -ve**noninteger = NaN
2049 # (-0)**noninteger = 0**noninteger
2050 if self:
2051 return context._raise_error(InvalidOperation,
2052 'x ** y with x negative and y not an integer')
2053 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002054 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002055
2056 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2057 if not self:
2058 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002059 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002060 else:
2061 return Infsign[result_sign]
2062
2063 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002064 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002065 if other._sign == 0:
2066 return Infsign[result_sign]
2067 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002068 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002069
Facundo Batista353750c2007-09-13 18:13:15 +00002070 # 1**other = 1, but the choice of exponent and the flags
2071 # depend on the exponent of self, and on whether other is a
2072 # positive integer, a negative integer, or neither
2073 if self == Dec_p1:
2074 if other._isinteger():
2075 # exp = max(self._exp*max(int(other), 0),
2076 # 1-context.prec) but evaluating int(other) directly
2077 # is dangerous until we know other is small (other
2078 # could be 1e999999999)
2079 if other._sign == 1:
2080 multiplier = 0
2081 elif other > context.prec:
2082 multiplier = context.prec
2083 else:
2084 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002085
Facundo Batista353750c2007-09-13 18:13:15 +00002086 exp = self._exp * multiplier
2087 if exp < 1-context.prec:
2088 exp = 1-context.prec
2089 context._raise_error(Rounded)
2090 else:
2091 context._raise_error(Inexact)
2092 context._raise_error(Rounded)
2093 exp = 1-context.prec
2094
Facundo Batista72bc54f2007-11-23 17:59:00 +00002095 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002096
2097 # compute adjusted exponent of self
2098 self_adj = self.adjusted()
2099
2100 # self ** infinity is infinity if self > 1, 0 if self < 1
2101 # self ** -infinity is infinity if self < 1, 0 if self > 1
2102 if other._isinfinity():
2103 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002104 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002105 else:
2106 return Infsign[result_sign]
2107
2108 # from here on, the result always goes through the call
2109 # to _fix at the end of this function.
2110 ans = None
2111
2112 # crude test to catch cases of extreme overflow/underflow. If
2113 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2114 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2115 # self**other >= 10**(Emax+1), so overflow occurs. The test
2116 # for underflow is similar.
2117 bound = self._log10_exp_bound() + other.adjusted()
2118 if (self_adj >= 0) == (other._sign == 0):
2119 # self > 1 and other +ve, or self < 1 and other -ve
2120 # possibility of overflow
2121 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002122 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002123 else:
2124 # self > 1 and other -ve, or self < 1 and other +ve
2125 # possibility of underflow to 0
2126 Etiny = context.Etiny()
2127 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002128 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002129
2130 # try for an exact result with precision +1
2131 if ans is None:
2132 ans = self._power_exact(other, context.prec + 1)
2133 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002134 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002135
2136 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2137 if ans is None:
2138 p = context.prec
2139 x = _WorkRep(self)
2140 xc, xe = x.int, x.exp
2141 y = _WorkRep(other)
2142 yc, ye = y.int, y.exp
2143 if y.sign == 1:
2144 yc = -yc
2145
2146 # compute correctly rounded result: start with precision +3,
2147 # then increase precision until result is unambiguously roundable
2148 extra = 3
2149 while True:
2150 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2151 if coeff % (5*10**(len(str(coeff))-p-1)):
2152 break
2153 extra += 3
2154
Facundo Batista72bc54f2007-11-23 17:59:00 +00002155 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002156
2157 # the specification says that for non-integer other we need to
2158 # raise Inexact, even when the result is actually exact. In
2159 # the same way, we need to raise Underflow here if the result
2160 # is subnormal. (The call to _fix will take care of raising
2161 # Rounded and Subnormal, as usual.)
2162 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002163 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002164 # pad with zeros up to length context.prec+1 if necessary
2165 if len(ans._int) <= context.prec:
2166 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002167 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2168 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002169 if ans.adjusted() < context.Emin:
2170 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002171
Facundo Batista353750c2007-09-13 18:13:15 +00002172 # unlike exp, ln and log10, the power function respects the
2173 # rounding mode; no need to use ROUND_HALF_EVEN here
2174 ans = ans._fix(context)
2175 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002176
2177 def __rpow__(self, other, context=None):
2178 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002179 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002180 if other is NotImplemented:
2181 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002182 return other.__pow__(self, context=context)
2183
2184 def normalize(self, context=None):
2185 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002186
Facundo Batista353750c2007-09-13 18:13:15 +00002187 if context is None:
2188 context = getcontext()
2189
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002190 if self._is_special:
2191 ans = self._check_nans(context=context)
2192 if ans:
2193 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002194
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002195 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002196 if dup._isinfinity():
2197 return dup
2198
2199 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002200 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002201 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002202 end = len(dup._int)
2203 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002204 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002205 exp += 1
2206 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002207 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002208
Facundo Batistabd2fe832007-09-13 18:42:09 +00002209 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002210 """Quantize self so its exponent is the same as that of exp.
2211
2212 Similar to self._rescale(exp._exp) but with error checking.
2213 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002214 exp = _convert_other(exp, raiseit=True)
2215
Facundo Batista353750c2007-09-13 18:13:15 +00002216 if context is None:
2217 context = getcontext()
2218 if rounding is None:
2219 rounding = context.rounding
2220
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002221 if self._is_special or exp._is_special:
2222 ans = self._check_nans(exp, context)
2223 if ans:
2224 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002225
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002226 if exp._isinfinity() or self._isinfinity():
2227 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002228 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002229 return context._raise_error(InvalidOperation,
2230 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002231
Facundo Batistabd2fe832007-09-13 18:42:09 +00002232 # if we're not watching exponents, do a simple rescale
2233 if not watchexp:
2234 ans = self._rescale(exp._exp, rounding)
2235 # raise Inexact and Rounded where appropriate
2236 if ans._exp > self._exp:
2237 context._raise_error(Rounded)
2238 if ans != self:
2239 context._raise_error(Inexact)
2240 return ans
2241
Facundo Batista353750c2007-09-13 18:13:15 +00002242 # exp._exp should be between Etiny and Emax
2243 if not (context.Etiny() <= exp._exp <= context.Emax):
2244 return context._raise_error(InvalidOperation,
2245 'target exponent out of bounds in quantize')
2246
2247 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002248 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002249 return ans._fix(context)
2250
2251 self_adjusted = self.adjusted()
2252 if self_adjusted > context.Emax:
2253 return context._raise_error(InvalidOperation,
2254 'exponent of quantize result too large for current context')
2255 if self_adjusted - exp._exp + 1 > context.prec:
2256 return context._raise_error(InvalidOperation,
2257 'quantize result has too many digits for current context')
2258
2259 ans = self._rescale(exp._exp, rounding)
2260 if ans.adjusted() > context.Emax:
2261 return context._raise_error(InvalidOperation,
2262 'exponent of quantize result too large for current context')
2263 if len(ans._int) > context.prec:
2264 return context._raise_error(InvalidOperation,
2265 'quantize result has too many digits for current context')
2266
2267 # raise appropriate flags
2268 if ans._exp > self._exp:
2269 context._raise_error(Rounded)
2270 if ans != self:
2271 context._raise_error(Inexact)
2272 if ans and ans.adjusted() < context.Emin:
2273 context._raise_error(Subnormal)
2274
2275 # call to fix takes care of any necessary folddown
2276 ans = ans._fix(context)
2277 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002278
2279 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002280 """Return True if self and other have the same exponent; otherwise
2281 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002282
Facundo Batista1a191df2007-10-02 17:01:24 +00002283 If either operand is a special value, the following rules are used:
2284 * return True if both operands are infinities
2285 * return True if both operands are NaNs
2286 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002287 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002288 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002289 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002290 return (self.is_nan() and other.is_nan() or
2291 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002292 return self._exp == other._exp
2293
Facundo Batista353750c2007-09-13 18:13:15 +00002294 def _rescale(self, exp, rounding):
2295 """Rescale self so that the exponent is exp, either by padding with zeros
2296 or by truncating digits, using the given rounding mode.
2297
2298 Specials are returned without change. This operation is
2299 quiet: it raises no flags, and uses no information from the
2300 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002301
2302 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002303 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002304 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002305 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002306 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002307 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002308 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002309
Facundo Batista353750c2007-09-13 18:13:15 +00002310 if self._exp >= exp:
2311 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002312 return _dec_from_triple(self._sign,
2313 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002314
Facundo Batista353750c2007-09-13 18:13:15 +00002315 # too many digits; round and lose data. If self.adjusted() <
2316 # exp-1, replace self by 10**(exp-1) before rounding
2317 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002318 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002319 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002320 digits = 0
2321 this_function = getattr(self, self._pick_rounding_function[rounding])
2322 return this_function(digits)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002323
Facundo Batista353750c2007-09-13 18:13:15 +00002324 def to_integral_exact(self, rounding=None, context=None):
2325 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002326
Facundo Batista353750c2007-09-13 18:13:15 +00002327 If no rounding mode is specified, take the rounding mode from
2328 the context. This method raises the Rounded and Inexact flags
2329 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002330
Facundo Batista353750c2007-09-13 18:13:15 +00002331 See also: to_integral_value, which does exactly the same as
2332 this method except that it doesn't raise Inexact or Rounded.
2333 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002334 if self._is_special:
2335 ans = self._check_nans(context=context)
2336 if ans:
2337 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002338 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002339 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002340 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002341 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002342 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002343 if context is None:
2344 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002345 if rounding is None:
2346 rounding = context.rounding
2347 context._raise_error(Rounded)
2348 ans = self._rescale(0, rounding)
2349 if ans != self:
2350 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002351 return ans
2352
Facundo Batista353750c2007-09-13 18:13:15 +00002353 def to_integral_value(self, rounding=None, context=None):
2354 """Rounds to the nearest integer, without raising inexact, rounded."""
2355 if context is None:
2356 context = getcontext()
2357 if rounding is None:
2358 rounding = context.rounding
2359 if self._is_special:
2360 ans = self._check_nans(context=context)
2361 if ans:
2362 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002363 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002364 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002365 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002366 else:
2367 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002368
Facundo Batista353750c2007-09-13 18:13:15 +00002369 # the method name changed, but we provide also the old one, for compatibility
2370 to_integral = to_integral_value
2371
2372 def sqrt(self, context=None):
2373 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002374 if self._is_special:
2375 ans = self._check_nans(context=context)
2376 if ans:
2377 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002378
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002379 if self._isinfinity() and self._sign == 0:
2380 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002381
2382 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002383 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002384 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002385 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002386
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002387 if context is None:
2388 context = getcontext()
2389
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002390 if self._sign == 1:
2391 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2392
Facundo Batista353750c2007-09-13 18:13:15 +00002393 # At this point self represents a positive number. Let p be
2394 # the desired precision and express self in the form c*100**e
2395 # with c a positive real number and e an integer, c and e
2396 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2397 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2398 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2399 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2400 # the closest integer to sqrt(c) with the even integer chosen
2401 # in the case of a tie.
2402 #
2403 # To ensure correct rounding in all cases, we use the
2404 # following trick: we compute the square root to an extra
2405 # place (precision p+1 instead of precision p), rounding down.
2406 # Then, if the result is inexact and its last digit is 0 or 5,
2407 # we increase the last digit to 1 or 6 respectively; if it's
2408 # exact we leave the last digit alone. Now the final round to
2409 # p places (or fewer in the case of underflow) will round
2410 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002411
Facundo Batista353750c2007-09-13 18:13:15 +00002412 # use an extra digit of precision
2413 prec = context.prec+1
2414
2415 # write argument in the form c*100**e where e = self._exp//2
2416 # is the 'ideal' exponent, to be used if the square root is
2417 # exactly representable. l is the number of 'digits' of c in
2418 # base 100, so that 100**(l-1) <= c < 100**l.
2419 op = _WorkRep(self)
2420 e = op.exp >> 1
2421 if op.exp & 1:
2422 c = op.int * 10
2423 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002424 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002425 c = op.int
2426 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002427
Facundo Batista353750c2007-09-13 18:13:15 +00002428 # rescale so that c has exactly prec base 100 'digits'
2429 shift = prec-l
2430 if shift >= 0:
2431 c *= 100**shift
2432 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002433 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002434 c, remainder = divmod(c, 100**-shift)
2435 exact = not remainder
2436 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002437
Facundo Batista353750c2007-09-13 18:13:15 +00002438 # find n = floor(sqrt(c)) using Newton's method
2439 n = 10**prec
2440 while True:
2441 q = c//n
2442 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002443 break
Facundo Batista353750c2007-09-13 18:13:15 +00002444 else:
2445 n = n + q >> 1
2446 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002447
Facundo Batista353750c2007-09-13 18:13:15 +00002448 if exact:
2449 # result is exact; rescale to use ideal exponent e
2450 if shift >= 0:
2451 # assert n % 10**shift == 0
2452 n //= 10**shift
2453 else:
2454 n *= 10**-shift
2455 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002456 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002457 # result is not exact; fix last digit as described above
2458 if n % 5 == 0:
2459 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002460
Facundo Batista72bc54f2007-11-23 17:59:00 +00002461 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002462
Facundo Batista353750c2007-09-13 18:13:15 +00002463 # round, and fit to current context
2464 context = context._shallow_copy()
2465 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002466 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002467 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002468
Facundo Batista353750c2007-09-13 18:13:15 +00002469 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002470
2471 def max(self, other, context=None):
2472 """Returns the larger value.
2473
Facundo Batista353750c2007-09-13 18:13:15 +00002474 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002475 NaN (and signals if one is sNaN). Also rounds.
2476 """
Facundo Batista353750c2007-09-13 18:13:15 +00002477 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002478
Facundo Batista6c398da2007-09-17 17:30:13 +00002479 if context is None:
2480 context = getcontext()
2481
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002482 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002483 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002484 # number is always returned
2485 sn = self._isnan()
2486 on = other._isnan()
2487 if sn or on:
2488 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002489 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002490 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002491 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002492 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002493
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002494 c = self.__cmp__(other)
2495 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002496 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002497 # then an ordering is applied:
2498 #
Facundo Batista59c58842007-04-10 12:58:45 +00002499 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002500 # positive sign and min returns the operand with the negative sign
2501 #
Facundo Batista59c58842007-04-10 12:58:45 +00002502 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002503 # the result. This is exactly the ordering used in compare_total.
2504 c = self.compare_total(other)
2505
2506 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002507 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002508 else:
2509 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002510
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002511 if context._rounding_decision == ALWAYS_ROUND:
2512 return ans._fix(context)
2513 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002514
2515 def min(self, other, context=None):
2516 """Returns the smaller value.
2517
Facundo Batista59c58842007-04-10 12:58:45 +00002518 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002519 NaN (and signals if one is sNaN). Also rounds.
2520 """
Facundo Batista353750c2007-09-13 18:13:15 +00002521 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002522
Facundo Batista6c398da2007-09-17 17:30:13 +00002523 if context is None:
2524 context = getcontext()
2525
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002526 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002527 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002528 # number is always returned
2529 sn = self._isnan()
2530 on = other._isnan()
2531 if sn or on:
2532 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002533 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002534 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002535 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002536 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002537
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002538 c = self.__cmp__(other)
2539 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002540 c = self.compare_total(other)
2541
2542 if c == -1:
2543 ans = self
2544 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002545 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002546
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002547 if context._rounding_decision == ALWAYS_ROUND:
2548 return ans._fix(context)
2549 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002550
2551 def _isinteger(self):
2552 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002553 if self._is_special:
2554 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002555 if self._exp >= 0:
2556 return True
2557 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002558 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002559
2560 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002561 """Returns True if self is even. Assumes self is an integer."""
2562 if not self or self._exp > 0:
2563 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002564 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002565
2566 def adjusted(self):
2567 """Return the adjusted exponent of self"""
2568 try:
2569 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002570 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002571 except TypeError:
2572 return 0
2573
Facundo Batista353750c2007-09-13 18:13:15 +00002574 def canonical(self, context=None):
2575 """Returns the same Decimal object.
2576
2577 As we do not have different encodings for the same number, the
2578 received object already is in its canonical form.
2579 """
2580 return self
2581
2582 def compare_signal(self, other, context=None):
2583 """Compares self to the other operand numerically.
2584
2585 It's pretty much like compare(), but all NaNs signal, with signaling
2586 NaNs taking precedence over quiet NaNs.
2587 """
2588 if context is None:
2589 context = getcontext()
2590
2591 self_is_nan = self._isnan()
2592 other_is_nan = other._isnan()
2593 if self_is_nan == 2:
2594 return context._raise_error(InvalidOperation, 'sNaN',
2595 1, self)
2596 if other_is_nan == 2:
2597 return context._raise_error(InvalidOperation, 'sNaN',
2598 1, other)
2599 if self_is_nan:
2600 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2601 1, self)
2602 if other_is_nan:
2603 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2604 1, other)
2605 return self.compare(other, context=context)
2606
2607 def compare_total(self, other):
2608 """Compares self to other using the abstract representations.
2609
2610 This is not like the standard compare, which use their numerical
2611 value. Note that a total ordering is defined for all possible abstract
2612 representations.
2613 """
2614 # if one is negative and the other is positive, it's easy
2615 if self._sign and not other._sign:
2616 return Dec_n1
2617 if not self._sign and other._sign:
2618 return Dec_p1
2619 sign = self._sign
2620
2621 # let's handle both NaN types
2622 self_nan = self._isnan()
2623 other_nan = other._isnan()
2624 if self_nan or other_nan:
2625 if self_nan == other_nan:
2626 if self._int < other._int:
2627 if sign:
2628 return Dec_p1
2629 else:
2630 return Dec_n1
2631 if self._int > other._int:
2632 if sign:
2633 return Dec_n1
2634 else:
2635 return Dec_p1
2636 return Dec_0
2637
2638 if sign:
2639 if self_nan == 1:
2640 return Dec_n1
2641 if other_nan == 1:
2642 return Dec_p1
2643 if self_nan == 2:
2644 return Dec_n1
2645 if other_nan == 2:
2646 return Dec_p1
2647 else:
2648 if self_nan == 1:
2649 return Dec_p1
2650 if other_nan == 1:
2651 return Dec_n1
2652 if self_nan == 2:
2653 return Dec_p1
2654 if other_nan == 2:
2655 return Dec_n1
2656
2657 if self < other:
2658 return Dec_n1
2659 if self > other:
2660 return Dec_p1
2661
2662 if self._exp < other._exp:
2663 if sign:
2664 return Dec_p1
2665 else:
2666 return Dec_n1
2667 if self._exp > other._exp:
2668 if sign:
2669 return Dec_n1
2670 else:
2671 return Dec_p1
2672 return Dec_0
2673
2674
2675 def compare_total_mag(self, other):
2676 """Compares self to other using abstract repr., ignoring sign.
2677
2678 Like compare_total, but with operand's sign ignored and assumed to be 0.
2679 """
2680 s = self.copy_abs()
2681 o = other.copy_abs()
2682 return s.compare_total(o)
2683
2684 def copy_abs(self):
2685 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002686 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002687
2688 def copy_negate(self):
2689 """Returns a copy with the sign inverted."""
2690 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002691 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002692 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002693 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002694
2695 def copy_sign(self, other):
2696 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002697 return _dec_from_triple(other._sign, self._int,
2698 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002699
2700 def exp(self, context=None):
2701 """Returns e ** self."""
2702
2703 if context is None:
2704 context = getcontext()
2705
2706 # exp(NaN) = NaN
2707 ans = self._check_nans(context=context)
2708 if ans:
2709 return ans
2710
2711 # exp(-Infinity) = 0
2712 if self._isinfinity() == -1:
2713 return Dec_0
2714
2715 # exp(0) = 1
2716 if not self:
2717 return Dec_p1
2718
2719 # exp(Infinity) = Infinity
2720 if self._isinfinity() == 1:
2721 return Decimal(self)
2722
2723 # the result is now guaranteed to be inexact (the true
2724 # mathematical result is transcendental). There's no need to
2725 # raise Rounded and Inexact here---they'll always be raised as
2726 # a result of the call to _fix.
2727 p = context.prec
2728 adj = self.adjusted()
2729
2730 # we only need to do any computation for quite a small range
2731 # of adjusted exponents---for example, -29 <= adj <= 10 for
2732 # the default context. For smaller exponent the result is
2733 # indistinguishable from 1 at the given precision, while for
2734 # larger exponent the result either overflows or underflows.
2735 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2736 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002737 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002738 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2739 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002740 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002741 elif self._sign == 0 and adj < -p:
2742 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002743 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002744 elif self._sign == 1 and adj < -p-1:
2745 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002746 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002747 # general case
2748 else:
2749 op = _WorkRep(self)
2750 c, e = op.int, op.exp
2751 if op.sign == 1:
2752 c = -c
2753
2754 # compute correctly rounded result: increase precision by
2755 # 3 digits at a time until we get an unambiguously
2756 # roundable result
2757 extra = 3
2758 while True:
2759 coeff, exp = _dexp(c, e, p+extra)
2760 if coeff % (5*10**(len(str(coeff))-p-1)):
2761 break
2762 extra += 3
2763
Facundo Batista72bc54f2007-11-23 17:59:00 +00002764 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002765
2766 # at this stage, ans should round correctly with *any*
2767 # rounding mode, not just with ROUND_HALF_EVEN
2768 context = context._shallow_copy()
2769 rounding = context._set_rounding(ROUND_HALF_EVEN)
2770 ans = ans._fix(context)
2771 context.rounding = rounding
2772
2773 return ans
2774
2775 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002776 """Return True if self is canonical; otherwise return False.
2777
2778 Currently, the encoding of a Decimal instance is always
2779 canonical, so this method returns True for any Decimal.
2780 """
2781 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002782
2783 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002784 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002785
Facundo Batista1a191df2007-10-02 17:01:24 +00002786 A Decimal instance is considered finite if it is neither
2787 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002788 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002789 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002790
2791 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002792 """Return True if self is infinite; otherwise return False."""
2793 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002794
2795 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002796 """Return True if self is a qNaN or sNaN; otherwise return False."""
2797 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002798
2799 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002800 """Return True if self is a normal number; otherwise return False."""
2801 if self._is_special or not self:
2802 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002803 if context is None:
2804 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002805 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002806
2807 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002808 """Return True if self is a quiet NaN; otherwise return False."""
2809 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002810
2811 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002812 """Return True if self is negative; otherwise return False."""
2813 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002814
2815 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002816 """Return True if self is a signaling NaN; otherwise return False."""
2817 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002818
2819 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002820 """Return True if self is subnormal; otherwise return False."""
2821 if self._is_special or not self:
2822 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002823 if context is None:
2824 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002825 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002826
2827 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002828 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002829 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002830
2831 def _ln_exp_bound(self):
2832 """Compute a lower bound for the adjusted exponent of self.ln().
2833 In other words, compute r such that self.ln() >= 10**r. Assumes
2834 that self is finite and positive and that self != 1.
2835 """
2836
2837 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2838 adj = self._exp + len(self._int) - 1
2839 if adj >= 1:
2840 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2841 return len(str(adj*23//10)) - 1
2842 if adj <= -2:
2843 # argument <= 0.1
2844 return len(str((-1-adj)*23//10)) - 1
2845 op = _WorkRep(self)
2846 c, e = op.int, op.exp
2847 if adj == 0:
2848 # 1 < self < 10
2849 num = str(c-10**-e)
2850 den = str(c)
2851 return len(num) - len(den) - (num < den)
2852 # adj == -1, 0.1 <= self < 1
2853 return e + len(str(10**-e - c)) - 1
2854
2855
2856 def ln(self, context=None):
2857 """Returns the natural (base e) logarithm of self."""
2858
2859 if context is None:
2860 context = getcontext()
2861
2862 # ln(NaN) = NaN
2863 ans = self._check_nans(context=context)
2864 if ans:
2865 return ans
2866
2867 # ln(0.0) == -Infinity
2868 if not self:
2869 return negInf
2870
2871 # ln(Infinity) = Infinity
2872 if self._isinfinity() == 1:
2873 return Inf
2874
2875 # ln(1.0) == 0.0
2876 if self == Dec_p1:
2877 return Dec_0
2878
2879 # ln(negative) raises InvalidOperation
2880 if self._sign == 1:
2881 return context._raise_error(InvalidOperation,
2882 'ln of a negative value')
2883
2884 # result is irrational, so necessarily inexact
2885 op = _WorkRep(self)
2886 c, e = op.int, op.exp
2887 p = context.prec
2888
2889 # correctly rounded result: repeatedly increase precision by 3
2890 # until we get an unambiguously roundable result
2891 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2892 while True:
2893 coeff = _dlog(c, e, places)
2894 # assert len(str(abs(coeff)))-p >= 1
2895 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2896 break
2897 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002898 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002899
2900 context = context._shallow_copy()
2901 rounding = context._set_rounding(ROUND_HALF_EVEN)
2902 ans = ans._fix(context)
2903 context.rounding = rounding
2904 return ans
2905
2906 def _log10_exp_bound(self):
2907 """Compute a lower bound for the adjusted exponent of self.log10().
2908 In other words, find r such that self.log10() >= 10**r.
2909 Assumes that self is finite and positive and that self != 1.
2910 """
2911
2912 # For x >= 10 or x < 0.1 we only need a bound on the integer
2913 # part of log10(self), and this comes directly from the
2914 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2915 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2916 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2917
2918 adj = self._exp + len(self._int) - 1
2919 if adj >= 1:
2920 # self >= 10
2921 return len(str(adj))-1
2922 if adj <= -2:
2923 # self < 0.1
2924 return len(str(-1-adj))-1
2925 op = _WorkRep(self)
2926 c, e = op.int, op.exp
2927 if adj == 0:
2928 # 1 < self < 10
2929 num = str(c-10**-e)
2930 den = str(231*c)
2931 return len(num) - len(den) - (num < den) + 2
2932 # adj == -1, 0.1 <= self < 1
2933 num = str(10**-e-c)
2934 return len(num) + e - (num < "231") - 1
2935
2936 def log10(self, context=None):
2937 """Returns the base 10 logarithm of self."""
2938
2939 if context is None:
2940 context = getcontext()
2941
2942 # log10(NaN) = NaN
2943 ans = self._check_nans(context=context)
2944 if ans:
2945 return ans
2946
2947 # log10(0.0) == -Infinity
2948 if not self:
2949 return negInf
2950
2951 # log10(Infinity) = Infinity
2952 if self._isinfinity() == 1:
2953 return Inf
2954
2955 # log10(negative or -Infinity) raises InvalidOperation
2956 if self._sign == 1:
2957 return context._raise_error(InvalidOperation,
2958 'log10 of a negative value')
2959
2960 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00002961 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00002962 # answer may need rounding
2963 ans = Decimal(self._exp + len(self._int) - 1)
2964 else:
2965 # result is irrational, so necessarily inexact
2966 op = _WorkRep(self)
2967 c, e = op.int, op.exp
2968 p = context.prec
2969
2970 # correctly rounded result: repeatedly increase precision
2971 # until result is unambiguously roundable
2972 places = p-self._log10_exp_bound()+2
2973 while True:
2974 coeff = _dlog10(c, e, places)
2975 # assert len(str(abs(coeff)))-p >= 1
2976 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2977 break
2978 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002979 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002980
2981 context = context._shallow_copy()
2982 rounding = context._set_rounding(ROUND_HALF_EVEN)
2983 ans = ans._fix(context)
2984 context.rounding = rounding
2985 return ans
2986
2987 def logb(self, context=None):
2988 """ Returns the exponent of the magnitude of self's MSD.
2989
2990 The result is the integer which is the exponent of the magnitude
2991 of the most significant digit of self (as though it were truncated
2992 to a single digit while maintaining the value of that digit and
2993 without limiting the resulting exponent).
2994 """
2995 # logb(NaN) = NaN
2996 ans = self._check_nans(context=context)
2997 if ans:
2998 return ans
2999
3000 if context is None:
3001 context = getcontext()
3002
3003 # logb(+/-Inf) = +Inf
3004 if self._isinfinity():
3005 return Inf
3006
3007 # logb(0) = -Inf, DivisionByZero
3008 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00003009 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00003010
3011 # otherwise, simply return the adjusted exponent of self, as a
3012 # Decimal. Note that no attempt is made to fit the result
3013 # into the current context.
3014 return Decimal(self.adjusted())
3015
3016 def _islogical(self):
3017 """Return True if self is a logical operand.
3018
3019 For being logical, it must be a finite numbers with a sign of 0,
3020 an exponent of 0, and a coefficient whose digits must all be
3021 either 0 or 1.
3022 """
3023 if self._sign != 0 or self._exp != 0:
3024 return False
3025 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003026 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00003027 return False
3028 return True
3029
3030 def _fill_logical(self, context, opa, opb):
3031 dif = context.prec - len(opa)
3032 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003033 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00003034 elif dif < 0:
3035 opa = opa[-context.prec:]
3036 dif = context.prec - len(opb)
3037 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003038 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00003039 elif dif < 0:
3040 opb = opb[-context.prec:]
3041 return opa, opb
3042
3043 def logical_and(self, other, context=None):
3044 """Applies an 'and' operation between self and other's digits."""
3045 if context is None:
3046 context = getcontext()
3047 if not self._islogical() or not other._islogical():
3048 return context._raise_error(InvalidOperation)
3049
3050 # fill to context.prec
3051 (opa, opb) = self._fill_logical(context, self._int, other._int)
3052
3053 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003054 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3055 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003056
3057 def logical_invert(self, context=None):
3058 """Invert all its digits."""
3059 if context is None:
3060 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003061 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3062 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003063
3064 def logical_or(self, other, context=None):
3065 """Applies an 'or' operation between self and other's digits."""
3066 if context is None:
3067 context = getcontext()
3068 if not self._islogical() or not other._islogical():
3069 return context._raise_error(InvalidOperation)
3070
3071 # fill to context.prec
3072 (opa, opb) = self._fill_logical(context, self._int, other._int)
3073
3074 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003075 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3076 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003077
3078 def logical_xor(self, other, context=None):
3079 """Applies an 'xor' operation between self and other's digits."""
3080 if context is None:
3081 context = getcontext()
3082 if not self._islogical() or not other._islogical():
3083 return context._raise_error(InvalidOperation)
3084
3085 # fill to context.prec
3086 (opa, opb) = self._fill_logical(context, self._int, other._int)
3087
3088 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003089 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3090 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003091
3092 def max_mag(self, other, context=None):
3093 """Compares the values numerically with their sign ignored."""
3094 other = _convert_other(other, raiseit=True)
3095
Facundo Batista6c398da2007-09-17 17:30:13 +00003096 if context is None:
3097 context = getcontext()
3098
Facundo Batista353750c2007-09-13 18:13:15 +00003099 if self._is_special or other._is_special:
3100 # If one operand is a quiet NaN and the other is number, then the
3101 # number is always returned
3102 sn = self._isnan()
3103 on = other._isnan()
3104 if sn or on:
3105 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003106 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003107 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003108 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003109 return self._check_nans(other, context)
3110
3111 c = self.copy_abs().__cmp__(other.copy_abs())
3112 if c == 0:
3113 c = self.compare_total(other)
3114
3115 if c == -1:
3116 ans = other
3117 else:
3118 ans = self
3119
Facundo Batista353750c2007-09-13 18:13:15 +00003120 if context._rounding_decision == ALWAYS_ROUND:
3121 return ans._fix(context)
3122 return ans
3123
3124 def min_mag(self, other, context=None):
3125 """Compares the values numerically with their sign ignored."""
3126 other = _convert_other(other, raiseit=True)
3127
Facundo Batista6c398da2007-09-17 17:30:13 +00003128 if context is None:
3129 context = getcontext()
3130
Facundo Batista353750c2007-09-13 18:13:15 +00003131 if self._is_special or other._is_special:
3132 # If one operand is a quiet NaN and the other is number, then the
3133 # number is always returned
3134 sn = self._isnan()
3135 on = other._isnan()
3136 if sn or on:
3137 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003138 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003139 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003140 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003141 return self._check_nans(other, context)
3142
3143 c = self.copy_abs().__cmp__(other.copy_abs())
3144 if c == 0:
3145 c = self.compare_total(other)
3146
3147 if c == -1:
3148 ans = self
3149 else:
3150 ans = other
3151
Facundo Batista353750c2007-09-13 18:13:15 +00003152 if context._rounding_decision == ALWAYS_ROUND:
3153 return ans._fix(context)
3154 return ans
3155
3156 def next_minus(self, context=None):
3157 """Returns the largest representable number smaller than itself."""
3158 if context is None:
3159 context = getcontext()
3160
3161 ans = self._check_nans(context=context)
3162 if ans:
3163 return ans
3164
3165 if self._isinfinity() == -1:
3166 return negInf
3167 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003168 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003169
3170 context = context.copy()
3171 context._set_rounding(ROUND_FLOOR)
3172 context._ignore_all_flags()
3173 new_self = self._fix(context)
3174 if new_self != self:
3175 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003176 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3177 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003178
3179 def next_plus(self, context=None):
3180 """Returns the smallest representable number larger than itself."""
3181 if context is None:
3182 context = getcontext()
3183
3184 ans = self._check_nans(context=context)
3185 if ans:
3186 return ans
3187
3188 if self._isinfinity() == 1:
3189 return Inf
3190 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003191 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003192
3193 context = context.copy()
3194 context._set_rounding(ROUND_CEILING)
3195 context._ignore_all_flags()
3196 new_self = self._fix(context)
3197 if new_self != self:
3198 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003199 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3200 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003201
3202 def next_toward(self, other, context=None):
3203 """Returns the number closest to self, in the direction towards other.
3204
3205 The result is the closest representable number to self
3206 (excluding self) that is in the direction towards other,
3207 unless both have the same value. If the two operands are
3208 numerically equal, then the result is a copy of self with the
3209 sign set to be the same as the sign of other.
3210 """
3211 other = _convert_other(other, raiseit=True)
3212
3213 if context is None:
3214 context = getcontext()
3215
3216 ans = self._check_nans(other, context)
3217 if ans:
3218 return ans
3219
3220 comparison = self.__cmp__(other)
3221 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003222 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003223
3224 if comparison == -1:
3225 ans = self.next_plus(context)
3226 else: # comparison == 1
3227 ans = self.next_minus(context)
3228
3229 # decide which flags to raise using value of ans
3230 if ans._isinfinity():
3231 context._raise_error(Overflow,
3232 'Infinite result from next_toward',
3233 ans._sign)
3234 context._raise_error(Rounded)
3235 context._raise_error(Inexact)
3236 elif ans.adjusted() < context.Emin:
3237 context._raise_error(Underflow)
3238 context._raise_error(Subnormal)
3239 context._raise_error(Rounded)
3240 context._raise_error(Inexact)
3241 # if precision == 1 then we don't raise Clamped for a
3242 # result 0E-Etiny.
3243 if not ans:
3244 context._raise_error(Clamped)
3245
3246 return ans
3247
3248 def number_class(self, context=None):
3249 """Returns an indication of the class of self.
3250
3251 The class is one of the following strings:
3252 -sNaN
3253 -NaN
3254 -Infinity
3255 -Normal
3256 -Subnormal
3257 -Zero
3258 +Zero
3259 +Subnormal
3260 +Normal
3261 +Infinity
3262 """
3263 if self.is_snan():
3264 return "sNaN"
3265 if self.is_qnan():
3266 return "NaN"
3267 inf = self._isinfinity()
3268 if inf == 1:
3269 return "+Infinity"
3270 if inf == -1:
3271 return "-Infinity"
3272 if self.is_zero():
3273 if self._sign:
3274 return "-Zero"
3275 else:
3276 return "+Zero"
3277 if context is None:
3278 context = getcontext()
3279 if self.is_subnormal(context=context):
3280 if self._sign:
3281 return "-Subnormal"
3282 else:
3283 return "+Subnormal"
3284 # just a normal, regular, boring number, :)
3285 if self._sign:
3286 return "-Normal"
3287 else:
3288 return "+Normal"
3289
3290 def radix(self):
3291 """Just returns 10, as this is Decimal, :)"""
3292 return Decimal(10)
3293
3294 def rotate(self, other, context=None):
3295 """Returns a rotated copy of self, value-of-other times."""
3296 if context is None:
3297 context = getcontext()
3298
3299 ans = self._check_nans(other, context)
3300 if ans:
3301 return ans
3302
3303 if other._exp != 0:
3304 return context._raise_error(InvalidOperation)
3305 if not (-context.prec <= int(other) <= context.prec):
3306 return context._raise_error(InvalidOperation)
3307
3308 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003309 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003310
3311 # get values, pad if necessary
3312 torot = int(other)
3313 rotdig = self._int
3314 topad = context.prec - len(rotdig)
3315 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003316 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003317
3318 # let's rotate!
3319 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003320 return _dec_from_triple(self._sign,
3321 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003322
3323 def scaleb (self, other, context=None):
3324 """Returns self operand after adding the second value to its exp."""
3325 if context is None:
3326 context = getcontext()
3327
3328 ans = self._check_nans(other, context)
3329 if ans:
3330 return ans
3331
3332 if other._exp != 0:
3333 return context._raise_error(InvalidOperation)
3334 liminf = -2 * (context.Emax + context.prec)
3335 limsup = 2 * (context.Emax + context.prec)
3336 if not (liminf <= int(other) <= limsup):
3337 return context._raise_error(InvalidOperation)
3338
3339 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003340 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003341
Facundo Batista72bc54f2007-11-23 17:59:00 +00003342 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003343 d = d._fix(context)
3344 return d
3345
3346 def shift(self, other, context=None):
3347 """Returns a shifted copy of self, value-of-other times."""
3348 if context is None:
3349 context = getcontext()
3350
3351 ans = self._check_nans(other, context)
3352 if ans:
3353 return ans
3354
3355 if other._exp != 0:
3356 return context._raise_error(InvalidOperation)
3357 if not (-context.prec <= int(other) <= context.prec):
3358 return context._raise_error(InvalidOperation)
3359
3360 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003361 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003362
3363 # get values, pad if necessary
3364 torot = int(other)
3365 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003366 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003367 rotdig = self._int
3368 topad = context.prec - len(rotdig)
3369 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003370 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003371
3372 # let's shift!
3373 if torot < 0:
3374 rotated = rotdig[:torot]
3375 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003376 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003377 rotated = rotated[-context.prec:]
3378
Facundo Batista72bc54f2007-11-23 17:59:00 +00003379 return _dec_from_triple(self._sign,
3380 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003381
Facundo Batista59c58842007-04-10 12:58:45 +00003382 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003383 def __reduce__(self):
3384 return (self.__class__, (str(self),))
3385
3386 def __copy__(self):
3387 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003388 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003389 return self.__class__(str(self))
3390
3391 def __deepcopy__(self, memo):
3392 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003393 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003394 return self.__class__(str(self))
3395
Facundo Batista72bc54f2007-11-23 17:59:00 +00003396def _dec_from_triple(sign, coefficient, exponent, special=False):
3397 """Create a decimal instance directly, without any validation,
3398 normalization (e.g. removal of leading zeros) or argument
3399 conversion.
3400
3401 This function is for *internal use only*.
3402 """
3403
3404 self = object.__new__(Decimal)
3405 self._sign = sign
3406 self._int = coefficient
3407 self._exp = exponent
3408 self._is_special = special
3409
3410 return self
3411
Facundo Batista59c58842007-04-10 12:58:45 +00003412##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003413
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003414
3415# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003416rounding_functions = [name for name in Decimal.__dict__.keys()
3417 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003418for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003419 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003420 globalname = name[1:].upper()
3421 val = globals()[globalname]
3422 Decimal._pick_rounding_function[val] = name
3423
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003424del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003425
Nick Coghlanced12182006-09-02 03:54:17 +00003426class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003427 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003428
Nick Coghlanced12182006-09-02 03:54:17 +00003429 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003430 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003431 """
3432 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003433 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003434 def __enter__(self):
3435 self.saved_context = getcontext()
3436 setcontext(self.new_context)
3437 return self.new_context
3438 def __exit__(self, t, v, tb):
3439 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003440
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003441class Context(object):
3442 """Contains the context for a Decimal instance.
3443
3444 Contains:
3445 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003446 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003447 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003448 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003449 raised when it is caused. Otherwise, a value is
3450 substituted in.
3451 flags - When an exception is caused, flags[exception] is incremented.
3452 (Whether or not the trap_enabler is set)
3453 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003454 Emin - Minimum exponent
3455 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003456 capitals - If 1, 1*10^1 is printed as 1E+1.
3457 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003458 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003459 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003460
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003461 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003462 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003463 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003464 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003465 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003466 _ignored_flags=None):
3467 if flags is None:
3468 flags = []
3469 if _ignored_flags is None:
3470 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003471 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003472 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003473 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003474 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003475 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003476 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003477 for name, val in locals().items():
3478 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003479 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003480 else:
3481 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003482 del self.self
3483
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003484 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003485 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003486 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003487 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3488 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3489 % vars(self))
3490 names = [f.__name__ for f, v in self.flags.items() if v]
3491 s.append('flags=[' + ', '.join(names) + ']')
3492 names = [t.__name__ for t, v in self.traps.items() if v]
3493 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003494 return ', '.join(s) + ')'
3495
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003496 def clear_flags(self):
3497 """Reset all flags to zero"""
3498 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003499 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003500
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003501 def _shallow_copy(self):
3502 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003503 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003504 self._rounding_decision, self.Emin, self.Emax,
3505 self.capitals, self._clamp, self._ignored_flags)
3506 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003507
3508 def copy(self):
3509 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003510 nc = Context(self.prec, self.rounding, self.traps.copy(),
3511 self.flags.copy(), self._rounding_decision, self.Emin,
3512 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003513 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003514 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003515
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003516 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003517 """Handles an error
3518
3519 If the flag is in _ignored_flags, returns the default response.
3520 Otherwise, it increments the flag, then, if the corresponding
3521 trap_enabler is set, it reaises the exception. Otherwise, it returns
3522 the default value after incrementing the flag.
3523 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003524 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003525 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003526 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003527 return error().handle(self, *args)
3528
3529 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003530 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003531 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003532 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003533
3534 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003535 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003536 raise error, explanation
3537
3538 def _ignore_all_flags(self):
3539 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003540 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003541
3542 def _ignore_flags(self, *flags):
3543 """Ignore the flags, if they are raised"""
3544 # Do not mutate-- This way, copies of a context leave the original
3545 # alone.
3546 self._ignored_flags = (self._ignored_flags + list(flags))
3547 return list(flags)
3548
3549 def _regard_flags(self, *flags):
3550 """Stop ignoring the flags, if they are raised"""
3551 if flags and isinstance(flags[0], (tuple,list)):
3552 flags = flags[0]
3553 for flag in flags:
3554 self._ignored_flags.remove(flag)
3555
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003556 def __hash__(self):
3557 """A Context cannot be hashed."""
3558 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003559 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003560
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003561 def Etiny(self):
3562 """Returns Etiny (= Emin - prec + 1)"""
3563 return int(self.Emin - self.prec + 1)
3564
3565 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003566 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003567 return int(self.Emax - self.prec + 1)
3568
3569 def _set_rounding_decision(self, type):
3570 """Sets the rounding decision.
3571
3572 Sets the rounding decision, and returns the current (previous)
3573 rounding decision. Often used like:
3574
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003575 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003576 # That so you don't change the calling context
3577 # if an error occurs in the middle (say DivisionImpossible is raised).
3578
3579 rounding = context._set_rounding_decision(NEVER_ROUND)
3580 instance = instance / Decimal(2)
3581 context._set_rounding_decision(rounding)
3582
3583 This will make it not round for that operation.
3584 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003585
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003586 rounding = self._rounding_decision
3587 self._rounding_decision = type
3588 return rounding
3589
3590 def _set_rounding(self, type):
3591 """Sets the rounding type.
3592
3593 Sets the rounding type, and returns the current (previous)
3594 rounding type. Often used like:
3595
3596 context = context.copy()
3597 # so you don't change the calling context
3598 # if an error occurs in the middle.
3599 rounding = context._set_rounding(ROUND_UP)
3600 val = self.__sub__(other, context=context)
3601 context._set_rounding(rounding)
3602
3603 This will make it round up for that operation.
3604 """
3605 rounding = self.rounding
3606 self.rounding= type
3607 return rounding
3608
Raymond Hettingerfed52962004-07-14 15:41:57 +00003609 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003610 """Creates a new Decimal instance but using self as context."""
3611 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003612 if d._isnan() and len(d._int) > self.prec - self._clamp:
3613 return self._raise_error(ConversionSyntax,
3614 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003615 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003616
Facundo Batista59c58842007-04-10 12:58:45 +00003617 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003618 def abs(self, a):
3619 """Returns the absolute value of the operand.
3620
3621 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003622 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003623 the plus operation on the operand.
3624
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003625 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003626 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003627 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003628 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003629 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003630 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003631 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003632 Decimal("101.5")
3633 """
3634 return a.__abs__(context=self)
3635
3636 def add(self, a, b):
3637 """Return the sum of the two operands.
3638
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003639 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003640 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003641 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003642 Decimal("1.02E+4")
3643 """
3644 return a.__add__(b, context=self)
3645
3646 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003647 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003648
Facundo Batista353750c2007-09-13 18:13:15 +00003649 def canonical(self, a):
3650 """Returns the same Decimal object.
3651
3652 As we do not have different encodings for the same number, the
3653 received object already is in its canonical form.
3654
3655 >>> ExtendedContext.canonical(Decimal('2.50'))
3656 Decimal("2.50")
3657 """
3658 return a.canonical(context=self)
3659
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003660 def compare(self, a, b):
3661 """Compares values numerically.
3662
3663 If the signs of the operands differ, a value representing each operand
3664 ('-1' if the operand is less than zero, '0' if the operand is zero or
3665 negative zero, or '1' if the operand is greater than zero) is used in
3666 place of that operand for the comparison instead of the actual
3667 operand.
3668
3669 The comparison is then effected by subtracting the second operand from
3670 the first and then returning a value according to the result of the
3671 subtraction: '-1' if the result is less than zero, '0' if the result is
3672 zero or negative zero, or '1' if the result is greater than zero.
3673
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003674 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003675 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003676 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003677 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003678 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003679 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003680 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003681 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003682 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003683 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003684 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003685 Decimal("-1")
3686 """
3687 return a.compare(b, context=self)
3688
Facundo Batista353750c2007-09-13 18:13:15 +00003689 def compare_signal(self, a, b):
3690 """Compares the values of the two operands numerically.
3691
3692 It's pretty much like compare(), but all NaNs signal, with signaling
3693 NaNs taking precedence over quiet NaNs.
3694
3695 >>> c = ExtendedContext
3696 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3697 Decimal("-1")
3698 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3699 Decimal("0")
3700 >>> c.flags[InvalidOperation] = 0
3701 >>> print c.flags[InvalidOperation]
3702 0
3703 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3704 Decimal("NaN")
3705 >>> print c.flags[InvalidOperation]
3706 1
3707 >>> c.flags[InvalidOperation] = 0
3708 >>> print c.flags[InvalidOperation]
3709 0
3710 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3711 Decimal("NaN")
3712 >>> print c.flags[InvalidOperation]
3713 1
3714 """
3715 return a.compare_signal(b, context=self)
3716
3717 def compare_total(self, a, b):
3718 """Compares two operands using their abstract representation.
3719
3720 This is not like the standard compare, which use their numerical
3721 value. Note that a total ordering is defined for all possible abstract
3722 representations.
3723
3724 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3725 Decimal("-1")
3726 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3727 Decimal("-1")
3728 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3729 Decimal("-1")
3730 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3731 Decimal("0")
3732 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3733 Decimal("1")
3734 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3735 Decimal("-1")
3736 """
3737 return a.compare_total(b)
3738
3739 def compare_total_mag(self, a, b):
3740 """Compares two operands using their abstract representation ignoring sign.
3741
3742 Like compare_total, but with operand's sign ignored and assumed to be 0.
3743 """
3744 return a.compare_total_mag(b)
3745
3746 def copy_abs(self, a):
3747 """Returns a copy of the operand with the sign set to 0.
3748
3749 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3750 Decimal("2.1")
3751 >>> ExtendedContext.copy_abs(Decimal('-100'))
3752 Decimal("100")
3753 """
3754 return a.copy_abs()
3755
3756 def copy_decimal(self, a):
3757 """Returns a copy of the decimal objet.
3758
3759 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3760 Decimal("2.1")
3761 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3762 Decimal("-1.00")
3763 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003764 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003765
3766 def copy_negate(self, a):
3767 """Returns a copy of the operand with the sign inverted.
3768
3769 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3770 Decimal("-101.5")
3771 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3772 Decimal("101.5")
3773 """
3774 return a.copy_negate()
3775
3776 def copy_sign(self, a, b):
3777 """Copies the second operand's sign to the first one.
3778
3779 In detail, it returns a copy of the first operand with the sign
3780 equal to the sign of the second operand.
3781
3782 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3783 Decimal("1.50")
3784 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3785 Decimal("1.50")
3786 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3787 Decimal("-1.50")
3788 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3789 Decimal("-1.50")
3790 """
3791 return a.copy_sign(b)
3792
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003793 def divide(self, a, b):
3794 """Decimal division in a specified context.
3795
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003796 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003797 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003798 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003799 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003800 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003801 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003802 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003803 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003804 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003805 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003806 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003807 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003808 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003809 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003810 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003811 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003812 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003813 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003814 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003815 Decimal("1.20E+6")
3816 """
3817 return a.__div__(b, context=self)
3818
3819 def divide_int(self, a, b):
3820 """Divides two numbers and returns the integer part of the result.
3821
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003822 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003823 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003824 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003825 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003826 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003827 Decimal("3")
3828 """
3829 return a.__floordiv__(b, context=self)
3830
3831 def divmod(self, a, b):
3832 return a.__divmod__(b, context=self)
3833
Facundo Batista353750c2007-09-13 18:13:15 +00003834 def exp(self, a):
3835 """Returns e ** a.
3836
3837 >>> c = ExtendedContext.copy()
3838 >>> c.Emin = -999
3839 >>> c.Emax = 999
3840 >>> c.exp(Decimal('-Infinity'))
3841 Decimal("0")
3842 >>> c.exp(Decimal('-1'))
3843 Decimal("0.367879441")
3844 >>> c.exp(Decimal('0'))
3845 Decimal("1")
3846 >>> c.exp(Decimal('1'))
3847 Decimal("2.71828183")
3848 >>> c.exp(Decimal('0.693147181'))
3849 Decimal("2.00000000")
3850 >>> c.exp(Decimal('+Infinity'))
3851 Decimal("Infinity")
3852 """
3853 return a.exp(context=self)
3854
3855 def fma(self, a, b, c):
3856 """Returns a multiplied by b, plus c.
3857
3858 The first two operands are multiplied together, using multiply,
3859 the third operand is then added to the result of that
3860 multiplication, using add, all with only one final rounding.
3861
3862 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3863 Decimal("22")
3864 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3865 Decimal("-8")
3866 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3867 Decimal("1.38435736E+12")
3868 """
3869 return a.fma(b, c, context=self)
3870
3871 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003872 """Return True if the operand is canonical; otherwise return False.
3873
3874 Currently, the encoding of a Decimal instance is always
3875 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00003876
3877 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003878 True
Facundo Batista353750c2007-09-13 18:13:15 +00003879 """
Facundo Batista1a191df2007-10-02 17:01:24 +00003880 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00003881
3882 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003883 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003884
Facundo Batista1a191df2007-10-02 17:01:24 +00003885 A Decimal instance is considered finite if it is neither
3886 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00003887
3888 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003889 True
Facundo Batista353750c2007-09-13 18:13:15 +00003890 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003891 True
Facundo Batista353750c2007-09-13 18:13:15 +00003892 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003893 True
Facundo Batista353750c2007-09-13 18:13:15 +00003894 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003895 False
Facundo Batista353750c2007-09-13 18:13:15 +00003896 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003897 False
Facundo Batista353750c2007-09-13 18:13:15 +00003898 """
3899 return a.is_finite()
3900
3901 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003902 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003903
3904 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003905 False
Facundo Batista353750c2007-09-13 18:13:15 +00003906 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003907 True
Facundo Batista353750c2007-09-13 18:13:15 +00003908 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003909 False
Facundo Batista353750c2007-09-13 18:13:15 +00003910 """
3911 return a.is_infinite()
3912
3913 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003914 """Return True if the operand is a qNaN or sNaN;
3915 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003916
3917 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003918 False
Facundo Batista353750c2007-09-13 18:13:15 +00003919 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003920 True
Facundo Batista353750c2007-09-13 18:13:15 +00003921 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003922 True
Facundo Batista353750c2007-09-13 18:13:15 +00003923 """
3924 return a.is_nan()
3925
3926 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003927 """Return True if the operand is a normal number;
3928 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003929
3930 >>> c = ExtendedContext.copy()
3931 >>> c.Emin = -999
3932 >>> c.Emax = 999
3933 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003934 True
Facundo Batista353750c2007-09-13 18:13:15 +00003935 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003936 False
Facundo Batista353750c2007-09-13 18:13:15 +00003937 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003938 False
Facundo Batista353750c2007-09-13 18:13:15 +00003939 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003940 False
Facundo Batista353750c2007-09-13 18:13:15 +00003941 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003942 False
Facundo Batista353750c2007-09-13 18:13:15 +00003943 """
3944 return a.is_normal(context=self)
3945
3946 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003947 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003948
3949 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003950 False
Facundo Batista353750c2007-09-13 18:13:15 +00003951 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003952 True
Facundo Batista353750c2007-09-13 18:13:15 +00003953 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003954 False
Facundo Batista353750c2007-09-13 18:13:15 +00003955 """
3956 return a.is_qnan()
3957
3958 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003959 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003960
3961 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003962 False
Facundo Batista353750c2007-09-13 18:13:15 +00003963 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003964 True
Facundo Batista353750c2007-09-13 18:13:15 +00003965 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003966 True
Facundo Batista353750c2007-09-13 18:13:15 +00003967 """
3968 return a.is_signed()
3969
3970 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003971 """Return True if the operand is a signaling NaN;
3972 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003973
3974 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003975 False
Facundo Batista353750c2007-09-13 18:13:15 +00003976 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003977 False
Facundo Batista353750c2007-09-13 18:13:15 +00003978 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003979 True
Facundo Batista353750c2007-09-13 18:13:15 +00003980 """
3981 return a.is_snan()
3982
3983 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003984 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003985
3986 >>> c = ExtendedContext.copy()
3987 >>> c.Emin = -999
3988 >>> c.Emax = 999
3989 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003990 False
Facundo Batista353750c2007-09-13 18:13:15 +00003991 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003992 True
Facundo Batista353750c2007-09-13 18:13:15 +00003993 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003994 False
Facundo Batista353750c2007-09-13 18:13:15 +00003995 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003996 False
Facundo Batista353750c2007-09-13 18:13:15 +00003997 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003998 False
Facundo Batista353750c2007-09-13 18:13:15 +00003999 """
4000 return a.is_subnormal(context=self)
4001
4002 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004003 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004004
4005 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004006 True
Facundo Batista353750c2007-09-13 18:13:15 +00004007 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004008 False
Facundo Batista353750c2007-09-13 18:13:15 +00004009 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004010 True
Facundo Batista353750c2007-09-13 18:13:15 +00004011 """
4012 return a.is_zero()
4013
4014 def ln(self, a):
4015 """Returns the natural (base e) logarithm of the operand.
4016
4017 >>> c = ExtendedContext.copy()
4018 >>> c.Emin = -999
4019 >>> c.Emax = 999
4020 >>> c.ln(Decimal('0'))
4021 Decimal("-Infinity")
4022 >>> c.ln(Decimal('1.000'))
4023 Decimal("0")
4024 >>> c.ln(Decimal('2.71828183'))
4025 Decimal("1.00000000")
4026 >>> c.ln(Decimal('10'))
4027 Decimal("2.30258509")
4028 >>> c.ln(Decimal('+Infinity'))
4029 Decimal("Infinity")
4030 """
4031 return a.ln(context=self)
4032
4033 def log10(self, a):
4034 """Returns the base 10 logarithm of the operand.
4035
4036 >>> c = ExtendedContext.copy()
4037 >>> c.Emin = -999
4038 >>> c.Emax = 999
4039 >>> c.log10(Decimal('0'))
4040 Decimal("-Infinity")
4041 >>> c.log10(Decimal('0.001'))
4042 Decimal("-3")
4043 >>> c.log10(Decimal('1.000'))
4044 Decimal("0")
4045 >>> c.log10(Decimal('2'))
4046 Decimal("0.301029996")
4047 >>> c.log10(Decimal('10'))
4048 Decimal("1")
4049 >>> c.log10(Decimal('70'))
4050 Decimal("1.84509804")
4051 >>> c.log10(Decimal('+Infinity'))
4052 Decimal("Infinity")
4053 """
4054 return a.log10(context=self)
4055
4056 def logb(self, a):
4057 """ Returns the exponent of the magnitude of the operand's MSD.
4058
4059 The result is the integer which is the exponent of the magnitude
4060 of the most significant digit of the operand (as though the
4061 operand were truncated to a single digit while maintaining the
4062 value of that digit and without limiting the resulting exponent).
4063
4064 >>> ExtendedContext.logb(Decimal('250'))
4065 Decimal("2")
4066 >>> ExtendedContext.logb(Decimal('2.50'))
4067 Decimal("0")
4068 >>> ExtendedContext.logb(Decimal('0.03'))
4069 Decimal("-2")
4070 >>> ExtendedContext.logb(Decimal('0'))
4071 Decimal("-Infinity")
4072 """
4073 return a.logb(context=self)
4074
4075 def logical_and(self, a, b):
4076 """Applies the logical operation 'and' between each operand's digits.
4077
4078 The operands must be both logical numbers.
4079
4080 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4081 Decimal("0")
4082 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4083 Decimal("0")
4084 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4085 Decimal("0")
4086 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4087 Decimal("1")
4088 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4089 Decimal("1000")
4090 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4091 Decimal("10")
4092 """
4093 return a.logical_and(b, context=self)
4094
4095 def logical_invert(self, a):
4096 """Invert all the digits in the operand.
4097
4098 The operand must be a logical number.
4099
4100 >>> ExtendedContext.logical_invert(Decimal('0'))
4101 Decimal("111111111")
4102 >>> ExtendedContext.logical_invert(Decimal('1'))
4103 Decimal("111111110")
4104 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4105 Decimal("0")
4106 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4107 Decimal("10101010")
4108 """
4109 return a.logical_invert(context=self)
4110
4111 def logical_or(self, a, b):
4112 """Applies the logical operation 'or' between each operand's digits.
4113
4114 The operands must be both logical numbers.
4115
4116 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4117 Decimal("0")
4118 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4119 Decimal("1")
4120 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4121 Decimal("1")
4122 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4123 Decimal("1")
4124 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4125 Decimal("1110")
4126 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4127 Decimal("1110")
4128 """
4129 return a.logical_or(b, context=self)
4130
4131 def logical_xor(self, a, b):
4132 """Applies the logical operation 'xor' between each operand's digits.
4133
4134 The operands must be both logical numbers.
4135
4136 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4137 Decimal("0")
4138 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4139 Decimal("1")
4140 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4141 Decimal("1")
4142 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4143 Decimal("0")
4144 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4145 Decimal("110")
4146 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4147 Decimal("1101")
4148 """
4149 return a.logical_xor(b, context=self)
4150
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004151 def max(self, a,b):
4152 """max compares two values numerically and returns the maximum.
4153
4154 If either operand is a NaN then the general rules apply.
4155 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004156 operation. If they are numerically equal then the left-hand operand
4157 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004158 infinity) of the two operands is chosen as the result.
4159
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004160 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004161 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004162 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004163 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004164 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004165 Decimal("1")
4166 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4167 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004168 """
4169 return a.max(b, context=self)
4170
Facundo Batista353750c2007-09-13 18:13:15 +00004171 def max_mag(self, a, b):
4172 """Compares the values numerically with their sign ignored."""
4173 return a.max_mag(b, context=self)
4174
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004175 def min(self, a,b):
4176 """min compares two values numerically and returns the minimum.
4177
4178 If either operand is a NaN then the general rules apply.
4179 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004180 operation. If they are numerically equal then the left-hand operand
4181 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004182 infinity) of the two operands is chosen as the result.
4183
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004184 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004185 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004186 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004187 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004188 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004189 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004190 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4191 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004192 """
4193 return a.min(b, context=self)
4194
Facundo Batista353750c2007-09-13 18:13:15 +00004195 def min_mag(self, a, b):
4196 """Compares the values numerically with their sign ignored."""
4197 return a.min_mag(b, context=self)
4198
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004199 def minus(self, a):
4200 """Minus corresponds to unary prefix minus in Python.
4201
4202 The operation is evaluated using the same rules as subtract; the
4203 operation minus(a) is calculated as subtract('0', a) where the '0'
4204 has the same exponent as the operand.
4205
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004206 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004207 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004208 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004209 Decimal("1.3")
4210 """
4211 return a.__neg__(context=self)
4212
4213 def multiply(self, a, b):
4214 """multiply multiplies two operands.
4215
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004216 If either operand is a special value then the general rules apply.
4217 Otherwise, the operands are multiplied together ('long multiplication'),
4218 resulting in a number which may be as long as the sum of the lengths
4219 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004220
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004221 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004222 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004223 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004224 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004225 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004226 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004227 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004228 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004229 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004230 Decimal("4.28135971E+11")
4231 """
4232 return a.__mul__(b, context=self)
4233
Facundo Batista353750c2007-09-13 18:13:15 +00004234 def next_minus(self, a):
4235 """Returns the largest representable number smaller than a.
4236
4237 >>> c = ExtendedContext.copy()
4238 >>> c.Emin = -999
4239 >>> c.Emax = 999
4240 >>> ExtendedContext.next_minus(Decimal('1'))
4241 Decimal("0.999999999")
4242 >>> c.next_minus(Decimal('1E-1007'))
4243 Decimal("0E-1007")
4244 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4245 Decimal("-1.00000004")
4246 >>> c.next_minus(Decimal('Infinity'))
4247 Decimal("9.99999999E+999")
4248 """
4249 return a.next_minus(context=self)
4250
4251 def next_plus(self, a):
4252 """Returns the smallest representable number larger than a.
4253
4254 >>> c = ExtendedContext.copy()
4255 >>> c.Emin = -999
4256 >>> c.Emax = 999
4257 >>> ExtendedContext.next_plus(Decimal('1'))
4258 Decimal("1.00000001")
4259 >>> c.next_plus(Decimal('-1E-1007'))
4260 Decimal("-0E-1007")
4261 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4262 Decimal("-1.00000002")
4263 >>> c.next_plus(Decimal('-Infinity'))
4264 Decimal("-9.99999999E+999")
4265 """
4266 return a.next_plus(context=self)
4267
4268 def next_toward(self, a, b):
4269 """Returns the number closest to a, in direction towards b.
4270
4271 The result is the closest representable number from the first
4272 operand (but not the first operand) that is in the direction
4273 towards the second operand, unless the operands have the same
4274 value.
4275
4276 >>> c = ExtendedContext.copy()
4277 >>> c.Emin = -999
4278 >>> c.Emax = 999
4279 >>> c.next_toward(Decimal('1'), Decimal('2'))
4280 Decimal("1.00000001")
4281 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4282 Decimal("-0E-1007")
4283 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4284 Decimal("-1.00000002")
4285 >>> c.next_toward(Decimal('1'), Decimal('0'))
4286 Decimal("0.999999999")
4287 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4288 Decimal("0E-1007")
4289 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4290 Decimal("-1.00000004")
4291 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4292 Decimal("-0.00")
4293 """
4294 return a.next_toward(b, context=self)
4295
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004296 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004297 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004298
4299 Essentially a plus operation with all trailing zeros removed from the
4300 result.
4301
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004302 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004303 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004304 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004305 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004306 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004307 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004308 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004309 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004310 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004311 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004312 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004313 Decimal("0")
4314 """
4315 return a.normalize(context=self)
4316
Facundo Batista353750c2007-09-13 18:13:15 +00004317 def number_class(self, a):
4318 """Returns an indication of the class of the operand.
4319
4320 The class is one of the following strings:
4321 -sNaN
4322 -NaN
4323 -Infinity
4324 -Normal
4325 -Subnormal
4326 -Zero
4327 +Zero
4328 +Subnormal
4329 +Normal
4330 +Infinity
4331
4332 >>> c = Context(ExtendedContext)
4333 >>> c.Emin = -999
4334 >>> c.Emax = 999
4335 >>> c.number_class(Decimal('Infinity'))
4336 '+Infinity'
4337 >>> c.number_class(Decimal('1E-10'))
4338 '+Normal'
4339 >>> c.number_class(Decimal('2.50'))
4340 '+Normal'
4341 >>> c.number_class(Decimal('0.1E-999'))
4342 '+Subnormal'
4343 >>> c.number_class(Decimal('0'))
4344 '+Zero'
4345 >>> c.number_class(Decimal('-0'))
4346 '-Zero'
4347 >>> c.number_class(Decimal('-0.1E-999'))
4348 '-Subnormal'
4349 >>> c.number_class(Decimal('-1E-10'))
4350 '-Normal'
4351 >>> c.number_class(Decimal('-2.50'))
4352 '-Normal'
4353 >>> c.number_class(Decimal('-Infinity'))
4354 '-Infinity'
4355 >>> c.number_class(Decimal('NaN'))
4356 'NaN'
4357 >>> c.number_class(Decimal('-NaN'))
4358 'NaN'
4359 >>> c.number_class(Decimal('sNaN'))
4360 'sNaN'
4361 """
4362 return a.number_class(context=self)
4363
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004364 def plus(self, a):
4365 """Plus corresponds to unary prefix plus in Python.
4366
4367 The operation is evaluated using the same rules as add; the
4368 operation plus(a) is calculated as add('0', a) where the '0'
4369 has the same exponent as the operand.
4370
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004371 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004372 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004373 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004374 Decimal("-1.3")
4375 """
4376 return a.__pos__(context=self)
4377
4378 def power(self, a, b, modulo=None):
4379 """Raises a to the power of b, to modulo if given.
4380
Facundo Batista353750c2007-09-13 18:13:15 +00004381 With two arguments, compute a**b. If a is negative then b
4382 must be integral. The result will be inexact unless b is
4383 integral and the result is finite and can be expressed exactly
4384 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004385
Facundo Batista353750c2007-09-13 18:13:15 +00004386 With three arguments, compute (a**b) % modulo. For the
4387 three argument form, the following restrictions on the
4388 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004389
Facundo Batista353750c2007-09-13 18:13:15 +00004390 - all three arguments must be integral
4391 - b must be nonnegative
4392 - at least one of a or b must be nonzero
4393 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004394
Facundo Batista353750c2007-09-13 18:13:15 +00004395 The result of pow(a, b, modulo) is identical to the result
4396 that would be obtained by computing (a**b) % modulo with
4397 unbounded precision, but is computed more efficiently. It is
4398 always exact.
4399
4400 >>> c = ExtendedContext.copy()
4401 >>> c.Emin = -999
4402 >>> c.Emax = 999
4403 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004404 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004405 >>> c.power(Decimal('-2'), Decimal('3'))
4406 Decimal("-8")
4407 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004408 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004409 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004410 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004411 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4412 Decimal("2.00000000")
4413 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004414 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004415 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004416 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004417 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004418 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004419 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004420 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004421 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004422 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004423 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004424 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004425 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004426 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004427 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004428 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004429
4430 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4431 Decimal("11")
4432 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4433 Decimal("-11")
4434 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4435 Decimal("1")
4436 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4437 Decimal("11")
4438 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4439 Decimal("11729830")
4440 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4441 Decimal("-0")
4442 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4443 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004444 """
4445 return a.__pow__(b, modulo, context=self)
4446
4447 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004448 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004449
4450 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004451 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004452 exponent is being increased), multiplied by a positive power of ten (if
4453 the exponent is being decreased), or is unchanged (if the exponent is
4454 already equal to that of the right-hand operand).
4455
4456 Unlike other operations, if the length of the coefficient after the
4457 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004458 operation condition is raised. This guarantees that, unless there is
4459 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004460 equal to that of the right-hand operand.
4461
4462 Also unlike other operations, quantize will never raise Underflow, even
4463 if the result is subnormal and inexact.
4464
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004465 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004466 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004467 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004468 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004469 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004470 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004471 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004472 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004473 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004474 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004475 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004476 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004477 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004478 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004479 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004480 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004481 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004482 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004483 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004484 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004485 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004486 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004487 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004488 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004489 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004490 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004491 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004492 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004493 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004494 Decimal("2E+2")
4495 """
4496 return a.quantize(b, context=self)
4497
Facundo Batista353750c2007-09-13 18:13:15 +00004498 def radix(self):
4499 """Just returns 10, as this is Decimal, :)
4500
4501 >>> ExtendedContext.radix()
4502 Decimal("10")
4503 """
4504 return Decimal(10)
4505
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004506 def remainder(self, a, b):
4507 """Returns the remainder from integer division.
4508
4509 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004510 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004511 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004512 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004513
4514 This operation will fail under the same conditions as integer division
4515 (that is, if integer division on the same two operands would fail, the
4516 remainder cannot be calculated).
4517
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004518 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004519 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004520 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004521 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004522 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004523 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004524 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004525 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004526 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004527 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004528 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004529 Decimal("1.0")
4530 """
4531 return a.__mod__(b, context=self)
4532
4533 def remainder_near(self, a, b):
4534 """Returns to be "a - b * n", where n is the integer nearest the exact
4535 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004536 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004537 sign of a.
4538
4539 This operation will fail under the same conditions as integer division
4540 (that is, if integer division on the same two operands would fail, the
4541 remainder cannot be calculated).
4542
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004543 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004544 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004545 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004546 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004547 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004548 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004549 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004550 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004551 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004552 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004553 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004554 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004555 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004556 Decimal("-0.3")
4557 """
4558 return a.remainder_near(b, context=self)
4559
Facundo Batista353750c2007-09-13 18:13:15 +00004560 def rotate(self, a, b):
4561 """Returns a rotated copy of a, b times.
4562
4563 The coefficient of the result is a rotated copy of the digits in
4564 the coefficient of the first operand. The number of places of
4565 rotation is taken from the absolute value of the second operand,
4566 with the rotation being to the left if the second operand is
4567 positive or to the right otherwise.
4568
4569 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4570 Decimal("400000003")
4571 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4572 Decimal("12")
4573 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4574 Decimal("891234567")
4575 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4576 Decimal("123456789")
4577 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4578 Decimal("345678912")
4579 """
4580 return a.rotate(b, context=self)
4581
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004582 def same_quantum(self, a, b):
4583 """Returns True if the two operands have the same exponent.
4584
4585 The result is never affected by either the sign or the coefficient of
4586 either operand.
4587
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004588 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004589 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004590 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004591 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004592 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004593 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004594 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004595 True
4596 """
4597 return a.same_quantum(b)
4598
Facundo Batista353750c2007-09-13 18:13:15 +00004599 def scaleb (self, a, b):
4600 """Returns the first operand after adding the second value its exp.
4601
4602 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4603 Decimal("0.0750")
4604 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4605 Decimal("7.50")
4606 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4607 Decimal("7.50E+3")
4608 """
4609 return a.scaleb (b, context=self)
4610
4611 def shift(self, a, b):
4612 """Returns a shifted copy of a, b times.
4613
4614 The coefficient of the result is a shifted copy of the digits
4615 in the coefficient of the first operand. The number of places
4616 to shift is taken from the absolute value of the second operand,
4617 with the shift being to the left if the second operand is
4618 positive or to the right otherwise. Digits shifted into the
4619 coefficient are zeros.
4620
4621 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4622 Decimal("400000000")
4623 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4624 Decimal("0")
4625 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4626 Decimal("1234567")
4627 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4628 Decimal("123456789")
4629 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4630 Decimal("345678900")
4631 """
4632 return a.shift(b, context=self)
4633
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004634 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004635 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004636
4637 If the result must be inexact, it is rounded using the round-half-even
4638 algorithm.
4639
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004640 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004641 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004642 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004643 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004644 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004645 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004646 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004647 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004648 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004649 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004650 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004651 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004652 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004653 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004654 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004655 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004656 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004657 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004658 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004659 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004660 """
4661 return a.sqrt(context=self)
4662
4663 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004664 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004665
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004666 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004667 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004668 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004669 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004670 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004671 Decimal("-0.77")
4672 """
4673 return a.__sub__(b, context=self)
4674
4675 def to_eng_string(self, a):
4676 """Converts a number to a string, using scientific notation.
4677
4678 The operation is not affected by the context.
4679 """
4680 return a.to_eng_string(context=self)
4681
4682 def to_sci_string(self, a):
4683 """Converts a number to a string, using scientific notation.
4684
4685 The operation is not affected by the context.
4686 """
4687 return a.__str__(context=self)
4688
Facundo Batista353750c2007-09-13 18:13:15 +00004689 def to_integral_exact(self, a):
4690 """Rounds to an integer.
4691
4692 When the operand has a negative exponent, the result is the same
4693 as using the quantize() operation using the given operand as the
4694 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4695 of the operand as the precision setting; Inexact and Rounded flags
4696 are allowed in this operation. The rounding mode is taken from the
4697 context.
4698
4699 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4700 Decimal("2")
4701 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4702 Decimal("100")
4703 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4704 Decimal("100")
4705 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4706 Decimal("102")
4707 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4708 Decimal("-102")
4709 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4710 Decimal("1.0E+6")
4711 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4712 Decimal("7.89E+77")
4713 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4714 Decimal("-Infinity")
4715 """
4716 return a.to_integral_exact(context=self)
4717
4718 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004719 """Rounds to an integer.
4720
4721 When the operand has a negative exponent, the result is the same
4722 as using the quantize() operation using the given operand as the
4723 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4724 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004725 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004726
Facundo Batista353750c2007-09-13 18:13:15 +00004727 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004728 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004729 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004730 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004731 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004732 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004733 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004734 Decimal("102")
Facundo Batista353750c2007-09-13 18:13:15 +00004735 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004736 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004737 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004738 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004739 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004740 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004741 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004742 Decimal("-Infinity")
4743 """
Facundo Batista353750c2007-09-13 18:13:15 +00004744 return a.to_integral_value(context=self)
4745
4746 # the method name changed, but we provide also the old one, for compatibility
4747 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004748
4749class _WorkRep(object):
4750 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004751 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004752 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004753 # exp: None, int, or string
4754
4755 def __init__(self, value=None):
4756 if value is None:
4757 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004758 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004759 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004760 elif isinstance(value, Decimal):
4761 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004762 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004763 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004764 else:
4765 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004766 self.sign = value[0]
4767 self.int = value[1]
4768 self.exp = value[2]
4769
4770 def __repr__(self):
4771 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4772
4773 __str__ = __repr__
4774
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004775
4776
4777def _normalize(op1, op2, shouldround = 0, prec = 0):
4778 """Normalizes op1, op2 to have the same exp and length of coefficient.
4779
4780 Done during addition.
4781 """
Facundo Batista353750c2007-09-13 18:13:15 +00004782 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004783 tmp = op2
4784 other = op1
4785 else:
4786 tmp = op1
4787 other = op2
4788
Facundo Batista353750c2007-09-13 18:13:15 +00004789 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4790 # Then adding 10**exp to tmp has the same effect (after rounding)
4791 # as adding any positive quantity smaller than 10**exp; similarly
4792 # for subtraction. So if other is smaller than 10**exp we replace
4793 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4794 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004795 tmp_len = len(str(tmp.int))
4796 other_len = len(str(other.int))
Facundo Batista353750c2007-09-13 18:13:15 +00004797 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4798 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004799 other.int = 1
Facundo Batista353750c2007-09-13 18:13:15 +00004800 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004801
Facundo Batista353750c2007-09-13 18:13:15 +00004802 tmp.int *= 10 ** (tmp.exp - other.exp)
4803 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004804 return op1, op2
4805
Facundo Batista353750c2007-09-13 18:13:15 +00004806##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4807
4808# This function from Tim Peters was taken from here:
4809# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4810# The correction being in the function definition is for speed, and
4811# the whole function is not resolved with math.log because of avoiding
4812# the use of floats.
4813def _nbits(n, correction = {
4814 '0': 4, '1': 3, '2': 2, '3': 2,
4815 '4': 1, '5': 1, '6': 1, '7': 1,
4816 '8': 0, '9': 0, 'a': 0, 'b': 0,
4817 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4818 """Number of bits in binary representation of the positive integer n,
4819 or 0 if n == 0.
4820 """
4821 if n < 0:
4822 raise ValueError("The argument to _nbits should be nonnegative.")
4823 hex_n = "%x" % n
4824 return 4*len(hex_n) - correction[hex_n[0]]
4825
4826def _sqrt_nearest(n, a):
4827 """Closest integer to the square root of the positive integer n. a is
4828 an initial approximation to the square root. Any positive integer
4829 will do for a, but the closer a is to the square root of n the
4830 faster convergence will be.
4831
4832 """
4833 if n <= 0 or a <= 0:
4834 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4835
4836 b=0
4837 while a != b:
4838 b, a = a, a--n//a>>1
4839 return a
4840
4841def _rshift_nearest(x, shift):
4842 """Given an integer x and a nonnegative integer shift, return closest
4843 integer to x / 2**shift; use round-to-even in case of a tie.
4844
4845 """
4846 b, q = 1L << shift, x >> shift
4847 return q + (2*(x & (b-1)) + (q&1) > b)
4848
4849def _div_nearest(a, b):
4850 """Closest integer to a/b, a and b positive integers; rounds to even
4851 in the case of a tie.
4852
4853 """
4854 q, r = divmod(a, b)
4855 return q + (2*r + (q&1) > b)
4856
4857def _ilog(x, M, L = 8):
4858 """Integer approximation to M*log(x/M), with absolute error boundable
4859 in terms only of x/M.
4860
4861 Given positive integers x and M, return an integer approximation to
4862 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4863 between the approximation and the exact result is at most 22. For
4864 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4865 both cases these are upper bounds on the error; it will usually be
4866 much smaller."""
4867
4868 # The basic algorithm is the following: let log1p be the function
4869 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4870 # the reduction
4871 #
4872 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4873 #
4874 # repeatedly until the argument to log1p is small (< 2**-L in
4875 # absolute value). For small y we can use the Taylor series
4876 # expansion
4877 #
4878 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4879 #
4880 # truncating at T such that y**T is small enough. The whole
4881 # computation is carried out in a form of fixed-point arithmetic,
4882 # with a real number z being represented by an integer
4883 # approximation to z*M. To avoid loss of precision, the y below
4884 # is actually an integer approximation to 2**R*y*M, where R is the
4885 # number of reductions performed so far.
4886
4887 y = x-M
4888 # argument reduction; R = number of reductions performed
4889 R = 0
4890 while (R <= L and long(abs(y)) << L-R >= M or
4891 R > L and abs(y) >> R-L >= M):
4892 y = _div_nearest(long(M*y) << 1,
4893 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4894 R += 1
4895
4896 # Taylor series with T terms
4897 T = -int(-10*len(str(M))//(3*L))
4898 yshift = _rshift_nearest(y, R)
4899 w = _div_nearest(M, T)
4900 for k in xrange(T-1, 0, -1):
4901 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4902
4903 return _div_nearest(w*y, M)
4904
4905def _dlog10(c, e, p):
4906 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4907 approximation to 10**p * log10(c*10**e), with an absolute error of
4908 at most 1. Assumes that c*10**e is not exactly 1."""
4909
4910 # increase precision by 2; compensate for this by dividing
4911 # final result by 100
4912 p += 2
4913
4914 # write c*10**e as d*10**f with either:
4915 # f >= 0 and 1 <= d <= 10, or
4916 # f <= 0 and 0.1 <= d <= 1.
4917 # Thus for c*10**e close to 1, f = 0
4918 l = len(str(c))
4919 f = e+l - (e+l >= 1)
4920
4921 if p > 0:
4922 M = 10**p
4923 k = e+p-f
4924 if k >= 0:
4925 c *= 10**k
4926 else:
4927 c = _div_nearest(c, 10**-k)
4928
4929 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004930 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004931 log_d = _div_nearest(log_d*M, log_10)
4932 log_tenpower = f*M # exact
4933 else:
4934 log_d = 0 # error < 2.31
4935 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4936
4937 return _div_nearest(log_tenpower+log_d, 100)
4938
4939def _dlog(c, e, p):
4940 """Given integers c, e and p with c > 0, compute an integer
4941 approximation to 10**p * log(c*10**e), with an absolute error of
4942 at most 1. Assumes that c*10**e is not exactly 1."""
4943
4944 # Increase precision by 2. The precision increase is compensated
4945 # for at the end with a division by 100.
4946 p += 2
4947
4948 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4949 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4950 # as 10**p * log(d) + 10**p*f * log(10).
4951 l = len(str(c))
4952 f = e+l - (e+l >= 1)
4953
4954 # compute approximation to 10**p*log(d), with error < 27
4955 if p > 0:
4956 k = e+p-f
4957 if k >= 0:
4958 c *= 10**k
4959 else:
4960 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4961
4962 # _ilog magnifies existing error in c by a factor of at most 10
4963 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4964 else:
4965 # p <= 0: just approximate the whole thing by 0; error < 2.31
4966 log_d = 0
4967
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004968 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00004969 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004970 extra = len(str(abs(f)))-1
4971 if p + extra >= 0:
4972 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4973 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4974 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00004975 else:
4976 f_log_ten = 0
4977 else:
4978 f_log_ten = 0
4979
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004980 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004981 return _div_nearest(f_log_ten + log_d, 100)
4982
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004983class _Log10Memoize(object):
4984 """Class to compute, store, and allow retrieval of, digits of the
4985 constant log(10) = 2.302585.... This constant is needed by
4986 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4987 def __init__(self):
4988 self.digits = "23025850929940456840179914546843642076011014886"
4989
4990 def getdigits(self, p):
4991 """Given an integer p >= 0, return floor(10**p)*log(10).
4992
4993 For example, self.getdigits(3) returns 2302.
4994 """
4995 # digits are stored as a string, for quick conversion to
4996 # integer in the case that we've already computed enough
4997 # digits; the stored digits should always be correct
4998 # (truncated, not rounded to nearest).
4999 if p < 0:
5000 raise ValueError("p should be nonnegative")
5001
5002 if p >= len(self.digits):
5003 # compute p+3, p+6, p+9, ... digits; continue until at
5004 # least one of the extra digits is nonzero
5005 extra = 3
5006 while True:
5007 # compute p+extra digits, correct to within 1ulp
5008 M = 10**(p+extra+2)
5009 digits = str(_div_nearest(_ilog(10*M, M), 100))
5010 if digits[-extra:] != '0'*extra:
5011 break
5012 extra += 3
5013 # keep all reliable digits so far; remove trailing zeros
5014 # and next nonzero digit
5015 self.digits = digits.rstrip('0')[:-1]
5016 return int(self.digits[:p+1])
5017
5018_log10_digits = _Log10Memoize().getdigits
5019
Facundo Batista353750c2007-09-13 18:13:15 +00005020def _iexp(x, M, L=8):
5021 """Given integers x and M, M > 0, such that x/M is small in absolute
5022 value, compute an integer approximation to M*exp(x/M). For 0 <=
5023 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5024 is usually much smaller)."""
5025
5026 # Algorithm: to compute exp(z) for a real number z, first divide z
5027 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5028 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5029 # series
5030 #
5031 # expm1(x) = x + x**2/2! + x**3/3! + ...
5032 #
5033 # Now use the identity
5034 #
5035 # expm1(2x) = expm1(x)*(expm1(x)+2)
5036 #
5037 # R times to compute the sequence expm1(z/2**R),
5038 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5039
5040 # Find R such that x/2**R/M <= 2**-L
5041 R = _nbits((long(x)<<L)//M)
5042
5043 # Taylor series. (2**L)**T > M
5044 T = -int(-10*len(str(M))//(3*L))
5045 y = _div_nearest(x, T)
5046 Mshift = long(M)<<R
5047 for i in xrange(T-1, 0, -1):
5048 y = _div_nearest(x*(Mshift + y), Mshift * i)
5049
5050 # Expansion
5051 for k in xrange(R-1, -1, -1):
5052 Mshift = long(M)<<(k+2)
5053 y = _div_nearest(y*(y+Mshift), Mshift)
5054
5055 return M+y
5056
5057def _dexp(c, e, p):
5058 """Compute an approximation to exp(c*10**e), with p decimal places of
5059 precision.
5060
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005061 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005062
5063 10**(p-1) <= d <= 10**p, and
5064 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5065
5066 In other words, d*10**f is an approximation to exp(c*10**e) with p
5067 digits of precision, and with an error in d of at most 1. This is
5068 almost, but not quite, the same as the error being < 1ulp: when d
5069 = 10**(p-1) the error could be up to 10 ulp."""
5070
5071 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5072 p += 2
5073
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005074 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005075 extra = max(0, e + len(str(c)) - 1)
5076 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005077
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005078 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005079 # rounding down
5080 shift = e+q
5081 if shift >= 0:
5082 cshift = c*10**shift
5083 else:
5084 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005085 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005086
5087 # reduce remainder back to original precision
5088 rem = _div_nearest(rem, 10**extra)
5089
5090 # error in result of _iexp < 120; error after division < 0.62
5091 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5092
5093def _dpower(xc, xe, yc, ye, p):
5094 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5095 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5096
5097 10**(p-1) <= c <= 10**p, and
5098 (c-1)*10**e < x**y < (c+1)*10**e
5099
5100 in other words, c*10**e is an approximation to x**y with p digits
5101 of precision, and with an error in c of at most 1. (This is
5102 almost, but not quite, the same as the error being < 1ulp: when c
5103 == 10**(p-1) we can only guarantee error < 10ulp.)
5104
5105 We assume that: x is positive and not equal to 1, and y is nonzero.
5106 """
5107
5108 # Find b such that 10**(b-1) <= |y| <= 10**b
5109 b = len(str(abs(yc))) + ye
5110
5111 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5112 lxc = _dlog(xc, xe, p+b+1)
5113
5114 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5115 shift = ye-b
5116 if shift >= 0:
5117 pc = lxc*yc*10**shift
5118 else:
5119 pc = _div_nearest(lxc*yc, 10**-shift)
5120
5121 if pc == 0:
5122 # we prefer a result that isn't exactly 1; this makes it
5123 # easier to compute a correctly rounded result in __pow__
5124 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5125 coeff, exp = 10**(p-1)+1, 1-p
5126 else:
5127 coeff, exp = 10**p-1, -p
5128 else:
5129 coeff, exp = _dexp(pc, -(p+1), p+1)
5130 coeff = _div_nearest(coeff, 10)
5131 exp += 1
5132
5133 return coeff, exp
5134
5135def _log10_lb(c, correction = {
5136 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5137 '6': 23, '7': 16, '8': 10, '9': 5}):
5138 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5139 if c <= 0:
5140 raise ValueError("The argument to _log10_lb should be nonnegative.")
5141 str_c = str(c)
5142 return 100*len(str_c) - correction[str_c[0]]
5143
Facundo Batista59c58842007-04-10 12:58:45 +00005144##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005145
Facundo Batista353750c2007-09-13 18:13:15 +00005146def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005147 """Convert other to Decimal.
5148
5149 Verifies that it's ok to use in an implicit construction.
5150 """
5151 if isinstance(other, Decimal):
5152 return other
5153 if isinstance(other, (int, long)):
5154 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005155 if raiseit:
5156 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005157 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005158
Facundo Batista59c58842007-04-10 12:58:45 +00005159##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005160
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005161# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005162# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005163
5164DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005165 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005166 traps=[DivisionByZero, Overflow, InvalidOperation],
5167 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005168 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005169 Emax=999999999,
5170 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005171 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005172)
5173
5174# Pre-made alternate contexts offered by the specification
5175# Don't change these; the user should be able to select these
5176# contexts and be able to reproduce results from other implementations
5177# of the spec.
5178
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005179BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005180 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005181 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5182 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005183)
5184
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005185ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005186 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005187 traps=[],
5188 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005189)
5190
5191
Facundo Batista72bc54f2007-11-23 17:59:00 +00005192##### crud for parsing strings #############################################
5193import re
5194
5195# Regular expression used for parsing numeric strings. Additional
5196# comments:
5197#
5198# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5199# whitespace. But note that the specification disallows whitespace in
5200# a numeric string.
5201#
5202# 2. For finite numbers (not infinities and NaNs) the body of the
5203# number between the optional sign and the optional exponent must have
5204# at least one decimal digit, possibly after the decimal point. The
5205# lookahead expression '(?=\d|\.\d)' checks this.
5206#
5207# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5208# other meaning for \d than the numbers [0-9].
5209
5210import re
5211_parser = re.compile(r""" # A numeric string consists of:
5212# \s*
5213 (?P<sign>[-+])? # an optional sign, followed by either...
5214 (
5215 (?=\d|\.\d) # ...a number (with at least one digit)
5216 (?P<int>\d*) # consisting of a (possibly empty) integer part
5217 (\.(?P<frac>\d*))? # followed by an optional fractional part
5218 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5219 |
5220 Inf(inity)? # ...an infinity, or...
5221 |
5222 (?P<signal>s)? # ...an (optionally signaling)
5223 NaN # NaN
5224 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5225 )
5226# \s*
5227 $
5228""", re.VERBOSE | re.IGNORECASE).match
5229
5230del re
5231
5232
Facundo Batista59c58842007-04-10 12:58:45 +00005233##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005234
Facundo Batista59c58842007-04-10 12:58:45 +00005235# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005236Inf = Decimal('Inf')
5237negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005238NaN = Decimal('NaN')
5239Dec_0 = Decimal(0)
5240Dec_p1 = Decimal(1)
5241Dec_n1 = Decimal(-1)
5242Dec_p2 = Decimal(2)
5243Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005244
Facundo Batista59c58842007-04-10 12:58:45 +00005245# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005246Infsign = (Inf, negInf)
5247
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005248
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005249
5250if __name__ == '__main__':
5251 import doctest, sys
5252 doctest.testmod(sys.modules[__name__])