blob: c503d2fa0b3855564b04d4d02b840804af5935b7 [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)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000543
Facundo Batista0d157a02007-11-30 17:15:25 +0000544 # From a string
545 # REs insist on real strings, so we can too.
546 if isinstance(value, basestring):
547 m = _parser(value)
548 if m is None:
549 if context is None:
550 context = getcontext()
551 return context._raise_error(ConversionSyntax,
552 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000553
Facundo Batista0d157a02007-11-30 17:15:25 +0000554 if m.group('sign') == "-":
555 self._sign = 1
556 else:
557 self._sign = 0
558 intpart = m.group('int')
559 if intpart is not None:
560 # finite number
561 fracpart = m.group('frac')
562 exp = int(m.group('exp') or '0')
563 if fracpart is not None:
564 self._int = (intpart+fracpart).lstrip('0') or '0'
565 self._exp = exp - len(fracpart)
566 else:
567 self._int = intpart.lstrip('0') or '0'
568 self._exp = exp
569 self._is_special = False
570 else:
571 diag = m.group('diag')
572 if diag is not None:
573 # NaN
574 self._int = diag.lstrip('0')
575 if m.group('signal'):
576 self._exp = 'N'
577 else:
578 self._exp = 'n'
579 else:
580 # infinity
581 self._int = '0'
582 self._exp = 'F'
583 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000584 return self
585
586 # From an integer
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000587 if isinstance(value, (int,long)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000588 if value >= 0:
589 self._sign = 0
590 else:
591 self._sign = 1
592 self._exp = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +0000593 self._int = str(abs(value))
Facundo Batista0d157a02007-11-30 17:15:25 +0000594 self._is_special = False
595 return self
596
597 # From another decimal
598 if isinstance(value, Decimal):
599 self._exp = value._exp
600 self._sign = value._sign
601 self._int = value._int
602 self._is_special = value._is_special
603 return self
604
605 # From an internal working value
606 if isinstance(value, _WorkRep):
607 self._sign = value.sign
608 self._int = str(value.int)
609 self._exp = int(value.exp)
610 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000611 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000612
613 # tuple/list conversion (possibly from as_tuple())
614 if isinstance(value, (list,tuple)):
615 if len(value) != 3:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000616 raise ValueError('Invalid tuple size in creation of Decimal '
617 'from list or tuple. The list or tuple '
618 'should have exactly three elements.')
619 # process sign. The isinstance test rejects floats
620 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
621 raise ValueError("Invalid sign. The first value in the tuple "
622 "should be an integer; either 0 for a "
623 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000624 self._sign = value[0]
Facundo Batista9b5e2312007-10-19 19:25:57 +0000625 if value[2] == 'F':
626 # infinity: value[1] is ignored
Facundo Batista72bc54f2007-11-23 17:59:00 +0000627 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000628 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000629 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000630 else:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000631 # process and validate the digits in value[1]
632 digits = []
633 for digit in value[1]:
634 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
635 # skip leading zeros
636 if digits or digit != 0:
637 digits.append(digit)
638 else:
639 raise ValueError("The second value in the tuple must "
640 "be composed of integers in the range "
641 "0 through 9.")
642 if value[2] in ('n', 'N'):
643 # NaN: digits form the diagnostic
Facundo Batista72bc54f2007-11-23 17:59:00 +0000644 self._int = ''.join(map(str, digits))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000645 self._exp = value[2]
646 self._is_special = True
647 elif isinstance(value[2], (int, long)):
648 # finite number: digits give the coefficient
Facundo Batista72bc54f2007-11-23 17:59:00 +0000649 self._int = ''.join(map(str, digits or [0]))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000650 self._exp = value[2]
651 self._is_special = False
652 else:
653 raise ValueError("The third value in the tuple must "
654 "be an integer, or one of the "
655 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000656 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000657
Raymond Hettingerbf440692004-07-10 14:14:37 +0000658 if isinstance(value, float):
659 raise TypeError("Cannot convert float to Decimal. " +
660 "First convert the float to a string")
661
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000662 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000663
664 def _isnan(self):
665 """Returns whether the number is not actually one.
666
667 0 if a number
Facundo Batista353750c2007-09-13 18:13:15 +0000668 1 if NaN (it could be a normal quiet NaN or a phantom one)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000669 2 if sNaN
670 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000671 if self._is_special:
672 exp = self._exp
673 if exp == 'n':
674 return 1
675 elif exp == 'N':
676 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000677 return 0
678
679 def _isinfinity(self):
680 """Returns whether the number is infinite
681
682 0 if finite or not a number
683 1 if +INF
684 -1 if -INF
685 """
686 if self._exp == 'F':
687 if self._sign:
688 return -1
689 return 1
690 return 0
691
Facundo Batista353750c2007-09-13 18:13:15 +0000692 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000693 """Returns whether the number is not actually one.
694
695 if self, other are sNaN, signal
696 if self, other are NaN return nan
697 return 0
698
699 Done before operations.
700 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000701
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000702 self_is_nan = self._isnan()
703 if other is None:
704 other_is_nan = False
705 else:
706 other_is_nan = other._isnan()
707
708 if self_is_nan or other_is_nan:
709 if context is None:
710 context = getcontext()
711
712 if self_is_nan == 2:
713 return context._raise_error(InvalidOperation, 'sNaN',
714 1, self)
715 if other_is_nan == 2:
716 return context._raise_error(InvalidOperation, 'sNaN',
717 1, other)
718 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000719 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000720
Facundo Batista353750c2007-09-13 18:13:15 +0000721 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000722 return 0
723
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000724 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000725 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000726
Facundo Batista1a191df2007-10-02 17:01:24 +0000727 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000728 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000729 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000730
Facundo Batista353750c2007-09-13 18:13:15 +0000731 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000732 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000733 if other is NotImplemented:
Facundo Batista353750c2007-09-13 18:13:15 +0000734 # Never return NotImplemented
735 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000736
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000737 if self._is_special or other._is_special:
Facundo Batista353750c2007-09-13 18:13:15 +0000738 # check for nans, without raising on a signaling nan
739 if self._isnan() or other._isnan():
Facundo Batista59c58842007-04-10 12:58:45 +0000740 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000741
742 # INF = INF
743 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000744
Facundo Batista353750c2007-09-13 18:13:15 +0000745 # check for zeros; note that cmp(0, -0) should return 0
746 if not self:
747 if not other:
748 return 0
749 else:
750 return -((-1)**other._sign)
751 if not other:
752 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000753
Facundo Batista59c58842007-04-10 12:58:45 +0000754 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000755 if other._sign < self._sign:
756 return -1
757 if self._sign < other._sign:
758 return 1
759
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000760 self_adjusted = self.adjusted()
761 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000762 if self_adjusted == other_adjusted:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000763 self_padded = self._int + '0'*(self._exp - other._exp)
764 other_padded = other._int + '0'*(other._exp - self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +0000765 return cmp(self_padded, other_padded) * (-1)**self._sign
766 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000767 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000768 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000769 return -((-1)**self._sign)
770
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000771 def __eq__(self, other):
772 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000773 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000774 return self.__cmp__(other) == 0
775
776 def __ne__(self, other):
777 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000778 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000779 return self.__cmp__(other) != 0
780
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000781 def compare(self, other, context=None):
782 """Compares one to another.
783
784 -1 => a < b
785 0 => a = b
786 1 => a > b
787 NaN => one is NaN
788 Like __cmp__, but returns Decimal instances.
789 """
Facundo Batista353750c2007-09-13 18:13:15 +0000790 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000791
Facundo Batista59c58842007-04-10 12:58:45 +0000792 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000793 if (self._is_special or other and other._is_special):
794 ans = self._check_nans(other, context)
795 if ans:
796 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000797
Facundo Batista353750c2007-09-13 18:13:15 +0000798 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000799
800 def __hash__(self):
801 """x.__hash__() <==> hash(x)"""
802 # Decimal integers must hash the same as the ints
803 # Non-integer decimals are normalized and hashed as strings
Georg Brandl1fb9f522006-05-11 19:57:09 +0000804 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000805 if self._is_special:
806 if self._isnan():
807 raise TypeError('Cannot hash a NaN value.')
808 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000809 if not self:
810 return 0
811 if self._isinteger():
812 op = _WorkRep(self.to_integral_value())
813 # to make computation feasible for Decimals with large
814 # exponent, we use the fact that hash(n) == hash(m) for
815 # any two nonzero integers n and m such that (i) n and m
816 # have the same sign, and (ii) n is congruent to m modulo
817 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
818 # hash((-1)**s*c*pow(10, e, 2**64-1).
819 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000820 return hash(str(self.normalize()))
821
822 def as_tuple(self):
823 """Represents the number as a triple tuple.
824
825 To show the internals exactly as they are.
826 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000827 return (self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000828
829 def __repr__(self):
830 """Represents the number as an instance of Decimal."""
831 # Invariant: eval(repr(d)) == d
832 return 'Decimal("%s")' % str(self)
833
Facundo Batista353750c2007-09-13 18:13:15 +0000834 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000835 """Return string representation of the number in scientific notation.
836
837 Captures all of the information in the underlying representation.
838 """
839
Facundo Batista62edb712007-12-03 16:29:52 +0000840 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000841 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +0000842 if self._exp == 'F':
843 return sign + 'Infinity'
844 elif self._exp == 'n':
845 return sign + 'NaN' + self._int
846 else: # self._exp == 'N'
847 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000848
Facundo Batista62edb712007-12-03 16:29:52 +0000849 # number of digits of self._int to left of decimal point
850 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000851
Facundo Batista62edb712007-12-03 16:29:52 +0000852 # dotplace is number of digits of self._int to the left of the
853 # decimal point in the mantissa of the output string (that is,
854 # after adjusting the exponent)
855 if self._exp <= 0 and leftdigits > -6:
856 # no exponent required
857 dotplace = leftdigits
858 elif not eng:
859 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000860 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +0000861 elif self._int == '0':
862 # engineering notation, zero
863 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000864 else:
Facundo Batista62edb712007-12-03 16:29:52 +0000865 # engineering notation, nonzero
866 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000867
Facundo Batista62edb712007-12-03 16:29:52 +0000868 if dotplace <= 0:
869 intpart = '0'
870 fracpart = '.' + '0'*(-dotplace) + self._int
871 elif dotplace >= len(self._int):
872 intpart = self._int+'0'*(dotplace-len(self._int))
873 fracpart = ''
874 else:
875 intpart = self._int[:dotplace]
876 fracpart = '.' + self._int[dotplace:]
877 if leftdigits == dotplace:
878 exp = ''
879 else:
880 if context is None:
881 context = getcontext()
882 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
883
884 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000885
886 def to_eng_string(self, context=None):
887 """Convert to engineering-type string.
888
889 Engineering notation has an exponent which is a multiple of 3, so there
890 are up to 3 digits left of the decimal place.
891
892 Same rules for when in exponential and when as a value as in __str__.
893 """
Facundo Batista353750c2007-09-13 18:13:15 +0000894 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000895
896 def __neg__(self, context=None):
897 """Returns a copy with the sign switched.
898
899 Rounds, if it has reason.
900 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000901 if self._is_special:
902 ans = self._check_nans(context=context)
903 if ans:
904 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000905
906 if not self:
907 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +0000908 ans = self.copy_sign(Dec_0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000909 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000910 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000911
912 if context is None:
913 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000914 if context._rounding_decision == ALWAYS_ROUND:
Facundo Batista353750c2007-09-13 18:13:15 +0000915 return ans._fix(context)
916 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000917
918 def __pos__(self, context=None):
919 """Returns a copy, unless it is a sNaN.
920
921 Rounds the number (if more then precision digits)
922 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000923 if self._is_special:
924 ans = self._check_nans(context=context)
925 if ans:
926 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000927
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000928 if not self:
929 # + (-0) = 0
Facundo Batista353750c2007-09-13 18:13:15 +0000930 ans = self.copy_sign(Dec_0)
931 else:
932 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000933
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000934 if context is None:
935 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000936 if context._rounding_decision == ALWAYS_ROUND:
Facundo Batista353750c2007-09-13 18:13:15 +0000937 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000938 return ans
939
940 def __abs__(self, round=1, context=None):
941 """Returns the absolute value of self.
942
943 If the second argument is 0, do not round.
944 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000945 if self._is_special:
946 ans = self._check_nans(context=context)
947 if ans:
948 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000949
950 if not round:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000951 if context is None:
952 context = getcontext()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000953 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000954 context._set_rounding_decision(NEVER_ROUND)
955
956 if self._sign:
957 ans = self.__neg__(context=context)
958 else:
959 ans = self.__pos__(context=context)
960
961 return ans
962
963 def __add__(self, other, context=None):
964 """Returns self + other.
965
966 -INF + INF (or the reverse) cause InvalidOperation errors.
967 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000968 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000969 if other is NotImplemented:
970 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000971
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000972 if context is None:
973 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000974
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000975 if self._is_special or other._is_special:
976 ans = self._check_nans(other, context)
977 if ans:
978 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000979
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000980 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000981 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000982 if self._sign != other._sign and other._isinfinity():
983 return context._raise_error(InvalidOperation, '-INF + INF')
984 return Decimal(self)
985 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000986 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000987
988 shouldround = context._rounding_decision == ALWAYS_ROUND
989
990 exp = min(self._exp, other._exp)
991 negativezero = 0
992 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +0000993 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000994 negativezero = 1
995
996 if not self and not other:
997 sign = min(self._sign, other._sign)
998 if negativezero:
999 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001000 ans = _dec_from_triple(sign, '0', exp)
Facundo Batista353750c2007-09-13 18:13:15 +00001001 if shouldround:
1002 ans = ans._fix(context)
1003 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001004 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001005 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001006 ans = other._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001007 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001008 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009 return ans
1010 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001011 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001012 ans = self._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001013 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001014 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001015 return ans
1016
1017 op1 = _WorkRep(self)
1018 op2 = _WorkRep(other)
1019 op1, op2 = _normalize(op1, op2, shouldround, context.prec)
1020
1021 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001022 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001023 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001024 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001025 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batista353750c2007-09-13 18:13:15 +00001026 if shouldround:
1027 ans = ans._fix(context)
1028 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001029 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001030 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001031 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001032 if op1.sign == 1:
1033 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001034 op1.sign, op2.sign = op2.sign, op1.sign
1035 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001036 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001037 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001038 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001039 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001040 op1.sign, op2.sign = (0, 0)
1041 else:
1042 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001043 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001044
Raymond Hettinger17931de2004-10-27 06:21:46 +00001045 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001046 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001047 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001048 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001049
1050 result.exp = op1.exp
1051 ans = Decimal(result)
1052 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001053 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001054 return ans
1055
1056 __radd__ = __add__
1057
1058 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001059 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001060 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001061 if other is NotImplemented:
1062 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001063
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001064 if self._is_special or other._is_special:
1065 ans = self._check_nans(other, context=context)
1066 if ans:
1067 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001068
Facundo Batista353750c2007-09-13 18:13:15 +00001069 # self - other is computed as self + other.copy_negate()
1070 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001071
1072 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001073 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001074 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001075 if other is NotImplemented:
1076 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001077
Facundo Batista353750c2007-09-13 18:13:15 +00001078 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001079
Facundo Batista353750c2007-09-13 18:13:15 +00001080 def _increment(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081 """Special case of add, adding 1eExponent
1082
1083 Since it is common, (rounding, for example) this adds
1084 (sign)*one E self._exp to the number more efficiently than add.
1085
Facundo Batista353750c2007-09-13 18:13:15 +00001086 Assumes that self is nonspecial.
1087
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001088 For example:
1089 Decimal('5.624e10')._increment() == Decimal('5.625e10')
1090 """
Facundo Batista72bc54f2007-11-23 17:59:00 +00001091 L = map(int, self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001092 L[-1] += 1
1093 spot = len(L)-1
1094 while L[spot] == 10:
1095 L[spot] = 0
1096 if spot == 0:
1097 L[0:0] = [1]
1098 break
1099 L[spot-1] += 1
1100 spot -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001101 return _dec_from_triple(self._sign, "".join(map(str, L)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001102
1103 def __mul__(self, other, context=None):
1104 """Return self * other.
1105
1106 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1107 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001108 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001109 if other is NotImplemented:
1110 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001111
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001112 if context is None:
1113 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001114
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001115 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001116
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001117 if self._is_special or other._is_special:
1118 ans = self._check_nans(other, context)
1119 if ans:
1120 return ans
1121
1122 if self._isinfinity():
1123 if not other:
1124 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1125 return Infsign[resultsign]
1126
1127 if other._isinfinity():
1128 if not self:
1129 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1130 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001131
1132 resultexp = self._exp + other._exp
1133 shouldround = context._rounding_decision == ALWAYS_ROUND
1134
1135 # Special case for multiplying by zero
1136 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001137 ans = _dec_from_triple(resultsign, '0', resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001138 if shouldround:
Facundo Batista59c58842007-04-10 12:58:45 +00001139 # Fixing in case the exponent is out of bounds
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001140 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141 return ans
1142
1143 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001144 if self._int == '1':
1145 ans = _dec_from_triple(resultsign, other._int, resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001146 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001147 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001148 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001149 if other._int == '1':
1150 ans = _dec_from_triple(resultsign, self._int, resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001151 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001152 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001153 return ans
1154
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001155 op1 = _WorkRep(self)
1156 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001157
Facundo Batista72bc54f2007-11-23 17:59:00 +00001158 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001159 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001160 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001161
1162 return ans
1163 __rmul__ = __mul__
1164
1165 def __div__(self, other, context=None):
1166 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001167 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001168 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001169 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001170
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001171 if context is None:
1172 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001173
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001174 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001175
1176 if self._is_special or other._is_special:
1177 ans = self._check_nans(other, context)
1178 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001179 return ans
1180
1181 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001182 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001183
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001184 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001185 return Infsign[sign]
1186
1187 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001188 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001189 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001190
1191 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001192 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001193 if not self:
1194 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001195 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001196
Facundo Batistacce8df22007-09-18 16:53:18 +00001197 if not self:
1198 exp = self._exp - other._exp
1199 coeff = 0
1200 else:
1201 # OK, so neither = 0, INF or NaN
1202 shift = len(other._int) - len(self._int) + context.prec + 1
1203 exp = self._exp - other._exp - shift
1204 op1 = _WorkRep(self)
1205 op2 = _WorkRep(other)
1206 if shift >= 0:
1207 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1208 else:
1209 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1210 if remainder:
1211 # result is not exact; adjust to ensure correct rounding
1212 if coeff % 5 == 0:
1213 coeff += 1
1214 else:
1215 # result is exact; get as close to ideal exponent as possible
1216 ideal_exp = self._exp - other._exp
1217 while exp < ideal_exp and coeff % 10 == 0:
1218 coeff //= 10
1219 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001220
Facundo Batista72bc54f2007-11-23 17:59:00 +00001221 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001222 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001223
Facundo Batistacce8df22007-09-18 16:53:18 +00001224 __truediv__ = __div__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001225
Facundo Batistacce8df22007-09-18 16:53:18 +00001226 def _divide(self, other, context):
1227 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001228
Facundo Batistacce8df22007-09-18 16:53:18 +00001229 Assumes that neither self nor other is a NaN, that self is not
1230 infinite and that other is nonzero.
1231 """
1232 sign = self._sign ^ other._sign
1233 if other._isinfinity():
1234 ideal_exp = self._exp
1235 else:
1236 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001237
Facundo Batistacce8df22007-09-18 16:53:18 +00001238 expdiff = self.adjusted() - other.adjusted()
1239 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001240 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001241 self._rescale(ideal_exp, context.rounding))
1242 if expdiff <= context.prec:
1243 op1 = _WorkRep(self)
1244 op2 = _WorkRep(other)
1245 if op1.exp >= op2.exp:
1246 op1.int *= 10**(op1.exp - op2.exp)
1247 else:
1248 op2.int *= 10**(op2.exp - op1.exp)
1249 q, r = divmod(op1.int, op2.int)
1250 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001251 return (_dec_from_triple(sign, str(q), 0),
1252 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001253
Facundo Batistacce8df22007-09-18 16:53:18 +00001254 # Here the quotient is too large to be representable
1255 ans = context._raise_error(DivisionImpossible,
1256 'quotient too large in //, % or divmod')
1257 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001258
1259 def __rdiv__(self, other, context=None):
1260 """Swaps self/other and returns __div__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001261 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001262 if other is NotImplemented:
1263 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001264 return other.__div__(self, context=context)
1265 __rtruediv__ = __rdiv__
1266
1267 def __divmod__(self, other, context=None):
1268 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001269 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001270 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001271 other = _convert_other(other)
1272 if other is NotImplemented:
1273 return other
1274
1275 if context is None:
1276 context = getcontext()
1277
1278 ans = self._check_nans(other, context)
1279 if ans:
1280 return (ans, ans)
1281
1282 sign = self._sign ^ other._sign
1283 if self._isinfinity():
1284 if other._isinfinity():
1285 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1286 return ans, ans
1287 else:
1288 return (Infsign[sign],
1289 context._raise_error(InvalidOperation, 'INF % x'))
1290
1291 if not other:
1292 if not self:
1293 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1294 return ans, ans
1295 else:
1296 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1297 context._raise_error(InvalidOperation, 'x % 0'))
1298
1299 quotient, remainder = self._divide(other, context)
1300 if context._rounding_decision == ALWAYS_ROUND:
1301 remainder = remainder._fix(context)
1302 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001303
1304 def __rdivmod__(self, other, context=None):
1305 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001306 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001307 if other is NotImplemented:
1308 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001309 return other.__divmod__(self, context=context)
1310
1311 def __mod__(self, other, context=None):
1312 """
1313 self % other
1314 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001315 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001316 if other is NotImplemented:
1317 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001318
Facundo Batistacce8df22007-09-18 16:53:18 +00001319 if context is None:
1320 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001321
Facundo Batistacce8df22007-09-18 16:53:18 +00001322 ans = self._check_nans(other, context)
1323 if ans:
1324 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001325
Facundo Batistacce8df22007-09-18 16:53:18 +00001326 if self._isinfinity():
1327 return context._raise_error(InvalidOperation, 'INF % x')
1328 elif not other:
1329 if self:
1330 return context._raise_error(InvalidOperation, 'x % 0')
1331 else:
1332 return context._raise_error(DivisionUndefined, '0 % 0')
1333
1334 remainder = self._divide(other, context)[1]
1335 if context._rounding_decision == ALWAYS_ROUND:
1336 remainder = remainder._fix(context)
1337 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001338
1339 def __rmod__(self, other, context=None):
1340 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001341 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001342 if other is NotImplemented:
1343 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001344 return other.__mod__(self, context=context)
1345
1346 def remainder_near(self, other, context=None):
1347 """
1348 Remainder nearest to 0- abs(remainder-near) <= other/2
1349 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001350 if context is None:
1351 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001352
Facundo Batista353750c2007-09-13 18:13:15 +00001353 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001354
Facundo Batista353750c2007-09-13 18:13:15 +00001355 ans = self._check_nans(other, context)
1356 if ans:
1357 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001358
Facundo Batista353750c2007-09-13 18:13:15 +00001359 # self == +/-infinity -> InvalidOperation
1360 if self._isinfinity():
1361 return context._raise_error(InvalidOperation,
1362 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001363
Facundo Batista353750c2007-09-13 18:13:15 +00001364 # other == 0 -> either InvalidOperation or DivisionUndefined
1365 if not other:
1366 if self:
1367 return context._raise_error(InvalidOperation,
1368 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001369 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001370 return context._raise_error(DivisionUndefined,
1371 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001372
Facundo Batista353750c2007-09-13 18:13:15 +00001373 # other = +/-infinity -> remainder = self
1374 if other._isinfinity():
1375 ans = Decimal(self)
1376 return ans._fix(context)
1377
1378 # self = 0 -> remainder = self, with ideal exponent
1379 ideal_exponent = min(self._exp, other._exp)
1380 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001381 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001382 return ans._fix(context)
1383
1384 # catch most cases of large or small quotient
1385 expdiff = self.adjusted() - other.adjusted()
1386 if expdiff >= context.prec + 1:
1387 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001388 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001389 if expdiff <= -2:
1390 # expdiff <= -2 => abs(self/other) < 0.1
1391 ans = self._rescale(ideal_exponent, context.rounding)
1392 return ans._fix(context)
1393
1394 # adjust both arguments to have the same exponent, then divide
1395 op1 = _WorkRep(self)
1396 op2 = _WorkRep(other)
1397 if op1.exp >= op2.exp:
1398 op1.int *= 10**(op1.exp - op2.exp)
1399 else:
1400 op2.int *= 10**(op2.exp - op1.exp)
1401 q, r = divmod(op1.int, op2.int)
1402 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1403 # 10**ideal_exponent. Apply correction to ensure that
1404 # abs(remainder) <= abs(other)/2
1405 if 2*r + (q&1) > op2.int:
1406 r -= op2.int
1407 q += 1
1408
1409 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001410 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001411
1412 # result has same sign as self unless r is negative
1413 sign = self._sign
1414 if r < 0:
1415 sign = 1-sign
1416 r = -r
1417
Facundo Batista72bc54f2007-11-23 17:59:00 +00001418 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001419 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001420
1421 def __floordiv__(self, other, context=None):
1422 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001423 other = _convert_other(other)
1424 if other is NotImplemented:
1425 return other
1426
1427 if context is None:
1428 context = getcontext()
1429
1430 ans = self._check_nans(other, context)
1431 if ans:
1432 return ans
1433
1434 if self._isinfinity():
1435 if other._isinfinity():
1436 return context._raise_error(InvalidOperation, 'INF // INF')
1437 else:
1438 return Infsign[self._sign ^ other._sign]
1439
1440 if not other:
1441 if self:
1442 return context._raise_error(DivisionByZero, 'x // 0',
1443 self._sign ^ other._sign)
1444 else:
1445 return context._raise_error(DivisionUndefined, '0 // 0')
1446
1447 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001448
1449 def __rfloordiv__(self, other, context=None):
1450 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001451 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001452 if other is NotImplemented:
1453 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001454 return other.__floordiv__(self, context=context)
1455
1456 def __float__(self):
1457 """Float representation."""
1458 return float(str(self))
1459
1460 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001461 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001462 if self._is_special:
1463 if self._isnan():
1464 context = getcontext()
1465 return context._raise_error(InvalidContext)
1466 elif self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001467 raise OverflowError("Cannot convert infinity to long")
Facundo Batista353750c2007-09-13 18:13:15 +00001468 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001469 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001470 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001471 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001472 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001473
1474 def __long__(self):
1475 """Converts to a long.
1476
1477 Equivalent to long(int(self))
1478 """
1479 return long(self.__int__())
1480
Facundo Batista353750c2007-09-13 18:13:15 +00001481 def _fix_nan(self, context):
1482 """Decapitate the payload of a NaN to fit the context"""
1483 payload = self._int
1484
1485 # maximum length of payload is precision if _clamp=0,
1486 # precision-1 if _clamp=1.
1487 max_payload_len = context.prec - context._clamp
1488 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001489 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1490 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001491 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001492
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001493 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001494 """Round if it is necessary to keep self within prec precision.
1495
1496 Rounds and fixes the exponent. Does not raise on a sNaN.
1497
1498 Arguments:
1499 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001500 context - context used.
1501 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001502
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001503 if context is None:
1504 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001505
Facundo Batista353750c2007-09-13 18:13:15 +00001506 if self._is_special:
1507 if self._isnan():
1508 # decapitate payload if necessary
1509 return self._fix_nan(context)
1510 else:
1511 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001512 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001513
Facundo Batista353750c2007-09-13 18:13:15 +00001514 # if self is zero then exponent should be between Etiny and
1515 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1516 Etiny = context.Etiny()
1517 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001518 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001519 exp_max = [context.Emax, Etop][context._clamp]
1520 new_exp = min(max(self._exp, Etiny), exp_max)
1521 if new_exp != self._exp:
1522 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001523 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001524 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001525 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001526
1527 # exp_min is the smallest allowable exponent of the result,
1528 # equal to max(self.adjusted()-context.prec+1, Etiny)
1529 exp_min = len(self._int) + self._exp - context.prec
1530 if exp_min > Etop:
1531 # overflow: exp_min > Etop iff self.adjusted() > Emax
1532 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001533 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001534 return context._raise_error(Overflow, 'above Emax', self._sign)
1535 self_is_subnormal = exp_min < Etiny
1536 if self_is_subnormal:
1537 context._raise_error(Subnormal)
1538 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001539
Facundo Batista353750c2007-09-13 18:13:15 +00001540 # round if self has too many digits
1541 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001542 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001543 ans = self._rescale(exp_min, context.rounding)
1544 if ans != self:
1545 context._raise_error(Inexact)
1546 if self_is_subnormal:
1547 context._raise_error(Underflow)
1548 if not ans:
1549 # raise Clamped on underflow to 0
1550 context._raise_error(Clamped)
1551 elif len(ans._int) == context.prec+1:
1552 # we get here only if rescaling rounds the
1553 # cofficient up to exactly 10**context.prec
1554 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001555 ans = _dec_from_triple(ans._sign,
1556 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001557 else:
1558 # Inexact and Rounded have already been raised
1559 ans = context._raise_error(Overflow, 'above Emax',
1560 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001561 return ans
1562
Facundo Batista353750c2007-09-13 18:13:15 +00001563 # fold down if _clamp == 1 and self has too few digits
1564 if context._clamp == 1 and self._exp > Etop:
1565 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001566 self_padded = self._int + '0'*(self._exp - Etop)
1567 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001568
Facundo Batista353750c2007-09-13 18:13:15 +00001569 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001570 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001571
1572 _pick_rounding_function = {}
1573
Facundo Batista353750c2007-09-13 18:13:15 +00001574 # for each of the rounding functions below:
1575 # self is a finite, nonzero Decimal
1576 # prec is an integer satisfying 0 <= prec < len(self._int)
1577 # the rounded result will have exponent self._exp + len(self._int) - prec;
1578
1579 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001580 """Also known as round-towards-0, truncate."""
Facundo Batista353750c2007-09-13 18:13:15 +00001581 newexp = self._exp + len(self._int) - prec
Facundo Batista72bc54f2007-11-23 17:59:00 +00001582 return _dec_from_triple(self._sign, self._int[:prec] or '0', newexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001583
Facundo Batista353750c2007-09-13 18:13:15 +00001584 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001585 """Rounds away from 0."""
Facundo Batista353750c2007-09-13 18:13:15 +00001586 newexp = self._exp + len(self._int) - prec
Facundo Batista72bc54f2007-11-23 17:59:00 +00001587 tmp = _dec_from_triple(self._sign, self._int[:prec] or '0', newexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001588 for digit in self._int[prec:]:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001589 if digit != '0':
Facundo Batista353750c2007-09-13 18:13:15 +00001590 return tmp._increment()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001591 return tmp
1592
Facundo Batista353750c2007-09-13 18:13:15 +00001593 def _round_half_up(self, prec):
1594 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001595 if self._int[prec] in '56789':
Facundo Batista353750c2007-09-13 18:13:15 +00001596 return self._round_up(prec)
1597 else:
1598 return self._round_down(prec)
1599
1600 def _round_half_down(self, prec):
1601 """Round 5 down"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001602 if self._int[prec] == '5':
Facundo Batista353750c2007-09-13 18:13:15 +00001603 for digit in self._int[prec+1:]:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001604 if digit != '0':
Facundo Batista353750c2007-09-13 18:13:15 +00001605 break
1606 else:
1607 return self._round_down(prec)
1608 return self._round_half_up(prec)
1609
1610 def _round_half_even(self, prec):
1611 """Round 5 to even, rest to nearest."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001612 if prec and self._int[prec-1] in '13579':
Facundo Batista353750c2007-09-13 18:13:15 +00001613 return self._round_half_up(prec)
1614 else:
1615 return self._round_half_down(prec)
1616
1617 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001618 """Rounds up (not away from 0 if negative.)"""
1619 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001620 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001621 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001622 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001623
Facundo Batista353750c2007-09-13 18:13:15 +00001624 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001625 """Rounds down (not towards 0 if negative)"""
1626 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001627 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001628 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001629 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001630
Facundo Batista353750c2007-09-13 18:13:15 +00001631 def _round_05up(self, prec):
1632 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001633 if prec == 0 or self._int[prec-1] in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001634 return self._round_up(prec)
1635 else:
1636 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001637
Facundo Batista353750c2007-09-13 18:13:15 +00001638 def fma(self, other, third, context=None):
1639 """Fused multiply-add.
1640
1641 Returns self*other+third with no rounding of the intermediate
1642 product self*other.
1643
1644 self and other are multiplied together, with no rounding of
1645 the result. The third operand is then added to the result,
1646 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001647 """
Facundo Batista353750c2007-09-13 18:13:15 +00001648
1649 other = _convert_other(other, raiseit=True)
1650 third = _convert_other(third, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001651
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001652 if context is None:
1653 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001654
Facundo Batista353750c2007-09-13 18:13:15 +00001655 # do self*other in fresh context with no traps and no rounding
1656 mul_context = Context(traps=[], flags=[],
1657 _rounding_decision=NEVER_ROUND)
1658 product = self.__mul__(other, mul_context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001659
Facundo Batista353750c2007-09-13 18:13:15 +00001660 if mul_context.flags[InvalidOperation]:
1661 # reraise in current context
1662 return context._raise_error(InvalidOperation,
1663 'invalid multiplication in fma',
1664 1, product)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001665
Facundo Batista353750c2007-09-13 18:13:15 +00001666 ans = product.__add__(third, context)
1667 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001668
Facundo Batista353750c2007-09-13 18:13:15 +00001669 def _power_modulo(self, other, modulo, context=None):
1670 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001671
Facundo Batista353750c2007-09-13 18:13:15 +00001672 # if can't convert other and modulo to Decimal, raise
1673 # TypeError; there's no point returning NotImplemented (no
1674 # equivalent of __rpow__ for three argument pow)
1675 other = _convert_other(other, raiseit=True)
1676 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001677
Facundo Batista353750c2007-09-13 18:13:15 +00001678 if context is None:
1679 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001680
Facundo Batista353750c2007-09-13 18:13:15 +00001681 # deal with NaNs: if there are any sNaNs then first one wins,
1682 # (i.e. behaviour for NaNs is identical to that of fma)
1683 self_is_nan = self._isnan()
1684 other_is_nan = other._isnan()
1685 modulo_is_nan = modulo._isnan()
1686 if self_is_nan or other_is_nan or modulo_is_nan:
1687 if self_is_nan == 2:
1688 return context._raise_error(InvalidOperation, 'sNaN',
1689 1, self)
1690 if other_is_nan == 2:
1691 return context._raise_error(InvalidOperation, 'sNaN',
1692 1, other)
1693 if modulo_is_nan == 2:
1694 return context._raise_error(InvalidOperation, 'sNaN',
1695 1, modulo)
1696 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001697 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001698 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001699 return other._fix_nan(context)
1700 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001701
Facundo Batista353750c2007-09-13 18:13:15 +00001702 # check inputs: we apply same restrictions as Python's pow()
1703 if not (self._isinteger() and
1704 other._isinteger() and
1705 modulo._isinteger()):
1706 return context._raise_error(InvalidOperation,
1707 'pow() 3rd argument not allowed '
1708 'unless all arguments are integers')
1709 if other < 0:
1710 return context._raise_error(InvalidOperation,
1711 'pow() 2nd argument cannot be '
1712 'negative when 3rd argument specified')
1713 if not modulo:
1714 return context._raise_error(InvalidOperation,
1715 'pow() 3rd argument cannot be 0')
1716
1717 # additional restriction for decimal: the modulus must be less
1718 # than 10**prec in absolute value
1719 if modulo.adjusted() >= context.prec:
1720 return context._raise_error(InvalidOperation,
1721 'insufficient precision: pow() 3rd '
1722 'argument must not have more than '
1723 'precision digits')
1724
1725 # define 0**0 == NaN, for consistency with two-argument pow
1726 # (even though it hurts!)
1727 if not other and not self:
1728 return context._raise_error(InvalidOperation,
1729 'at least one of pow() 1st argument '
1730 'and 2nd argument must be nonzero ;'
1731 '0**0 is not defined')
1732
1733 # compute sign of result
1734 if other._iseven():
1735 sign = 0
1736 else:
1737 sign = self._sign
1738
1739 # convert modulo to a Python integer, and self and other to
1740 # Decimal integers (i.e. force their exponents to be >= 0)
1741 modulo = abs(int(modulo))
1742 base = _WorkRep(self.to_integral_value())
1743 exponent = _WorkRep(other.to_integral_value())
1744
1745 # compute result using integer pow()
1746 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1747 for i in xrange(exponent.exp):
1748 base = pow(base, 10, modulo)
1749 base = pow(base, exponent.int, modulo)
1750
Facundo Batista72bc54f2007-11-23 17:59:00 +00001751 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001752
1753 def _power_exact(self, other, p):
1754 """Attempt to compute self**other exactly.
1755
1756 Given Decimals self and other and an integer p, attempt to
1757 compute an exact result for the power self**other, with p
1758 digits of precision. Return None if self**other is not
1759 exactly representable in p digits.
1760
1761 Assumes that elimination of special cases has already been
1762 performed: self and other must both be nonspecial; self must
1763 be positive and not numerically equal to 1; other must be
1764 nonzero. For efficiency, other._exp should not be too large,
1765 so that 10**abs(other._exp) is a feasible calculation."""
1766
1767 # In the comments below, we write x for the value of self and
1768 # y for the value of other. Write x = xc*10**xe and y =
1769 # yc*10**ye.
1770
1771 # The main purpose of this method is to identify the *failure*
1772 # of x**y to be exactly representable with as little effort as
1773 # possible. So we look for cheap and easy tests that
1774 # eliminate the possibility of x**y being exact. Only if all
1775 # these tests are passed do we go on to actually compute x**y.
1776
1777 # Here's the main idea. First normalize both x and y. We
1778 # express y as a rational m/n, with m and n relatively prime
1779 # and n>0. Then for x**y to be exactly representable (at
1780 # *any* precision), xc must be the nth power of a positive
1781 # integer and xe must be divisible by n. If m is negative
1782 # then additionally xc must be a power of either 2 or 5, hence
1783 # a power of 2**n or 5**n.
1784 #
1785 # There's a limit to how small |y| can be: if y=m/n as above
1786 # then:
1787 #
1788 # (1) if xc != 1 then for the result to be representable we
1789 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1790 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1791 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1792 # representable.
1793 #
1794 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1795 # |y| < 1/|xe| then the result is not representable.
1796 #
1797 # Note that since x is not equal to 1, at least one of (1) and
1798 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1799 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1800 #
1801 # There's also a limit to how large y can be, at least if it's
1802 # positive: the normalized result will have coefficient xc**y,
1803 # so if it's representable then xc**y < 10**p, and y <
1804 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1805 # not exactly representable.
1806
1807 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1808 # so |y| < 1/xe and the result is not representable.
1809 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1810 # < 1/nbits(xc).
1811
1812 x = _WorkRep(self)
1813 xc, xe = x.int, x.exp
1814 while xc % 10 == 0:
1815 xc //= 10
1816 xe += 1
1817
1818 y = _WorkRep(other)
1819 yc, ye = y.int, y.exp
1820 while yc % 10 == 0:
1821 yc //= 10
1822 ye += 1
1823
1824 # case where xc == 1: result is 10**(xe*y), with xe*y
1825 # required to be an integer
1826 if xc == 1:
1827 if ye >= 0:
1828 exponent = xe*yc*10**ye
1829 else:
1830 exponent, remainder = divmod(xe*yc, 10**-ye)
1831 if remainder:
1832 return None
1833 if y.sign == 1:
1834 exponent = -exponent
1835 # if other is a nonnegative integer, use ideal exponent
1836 if other._isinteger() and other._sign == 0:
1837 ideal_exponent = self._exp*int(other)
1838 zeros = min(exponent-ideal_exponent, p-1)
1839 else:
1840 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001841 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001842
1843 # case where y is negative: xc must be either a power
1844 # of 2 or a power of 5.
1845 if y.sign == 1:
1846 last_digit = xc % 10
1847 if last_digit in (2,4,6,8):
1848 # quick test for power of 2
1849 if xc & -xc != xc:
1850 return None
1851 # now xc is a power of 2; e is its exponent
1852 e = _nbits(xc)-1
1853 # find e*y and xe*y; both must be integers
1854 if ye >= 0:
1855 y_as_int = yc*10**ye
1856 e = e*y_as_int
1857 xe = xe*y_as_int
1858 else:
1859 ten_pow = 10**-ye
1860 e, remainder = divmod(e*yc, ten_pow)
1861 if remainder:
1862 return None
1863 xe, remainder = divmod(xe*yc, ten_pow)
1864 if remainder:
1865 return None
1866
1867 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1868 return None
1869 xc = 5**e
1870
1871 elif last_digit == 5:
1872 # e >= log_5(xc) if xc is a power of 5; we have
1873 # equality all the way up to xc=5**2658
1874 e = _nbits(xc)*28//65
1875 xc, remainder = divmod(5**e, xc)
1876 if remainder:
1877 return None
1878 while xc % 5 == 0:
1879 xc //= 5
1880 e -= 1
1881 if ye >= 0:
1882 y_as_integer = yc*10**ye
1883 e = e*y_as_integer
1884 xe = xe*y_as_integer
1885 else:
1886 ten_pow = 10**-ye
1887 e, remainder = divmod(e*yc, ten_pow)
1888 if remainder:
1889 return None
1890 xe, remainder = divmod(xe*yc, ten_pow)
1891 if remainder:
1892 return None
1893 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1894 return None
1895 xc = 2**e
1896 else:
1897 return None
1898
1899 if xc >= 10**p:
1900 return None
1901 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00001902 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00001903
1904 # now y is positive; find m and n such that y = m/n
1905 if ye >= 0:
1906 m, n = yc*10**ye, 1
1907 else:
1908 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1909 return None
1910 xc_bits = _nbits(xc)
1911 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1912 return None
1913 m, n = yc, 10**(-ye)
1914 while m % 2 == n % 2 == 0:
1915 m //= 2
1916 n //= 2
1917 while m % 5 == n % 5 == 0:
1918 m //= 5
1919 n //= 5
1920
1921 # compute nth root of xc*10**xe
1922 if n > 1:
1923 # if 1 < xc < 2**n then xc isn't an nth power
1924 if xc != 1 and xc_bits <= n:
1925 return None
1926
1927 xe, rem = divmod(xe, n)
1928 if rem != 0:
1929 return None
1930
1931 # compute nth root of xc using Newton's method
1932 a = 1L << -(-_nbits(xc)//n) # initial estimate
1933 while True:
1934 q, r = divmod(xc, a**(n-1))
1935 if a <= q:
1936 break
1937 else:
1938 a = (a*(n-1) + q)//n
1939 if not (a == q and r == 0):
1940 return None
1941 xc = a
1942
1943 # now xc*10**xe is the nth root of the original xc*10**xe
1944 # compute mth power of xc*10**xe
1945
1946 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1947 # 10**p and the result is not representable.
1948 if xc > 1 and m > p*100//_log10_lb(xc):
1949 return None
1950 xc = xc**m
1951 xe *= m
1952 if xc > 10**p:
1953 return None
1954
1955 # by this point the result *is* exactly representable
1956 # adjust the exponent to get as close as possible to the ideal
1957 # exponent, if necessary
1958 str_xc = str(xc)
1959 if other._isinteger() and other._sign == 0:
1960 ideal_exponent = self._exp*int(other)
1961 zeros = min(xe-ideal_exponent, p-len(str_xc))
1962 else:
1963 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001964 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001965
1966 def __pow__(self, other, modulo=None, context=None):
1967 """Return self ** other [ % modulo].
1968
1969 With two arguments, compute self**other.
1970
1971 With three arguments, compute (self**other) % modulo. For the
1972 three argument form, the following restrictions on the
1973 arguments hold:
1974
1975 - all three arguments must be integral
1976 - other must be nonnegative
1977 - either self or other (or both) must be nonzero
1978 - modulo must be nonzero and must have at most p digits,
1979 where p is the context precision.
1980
1981 If any of these restrictions is violated the InvalidOperation
1982 flag is raised.
1983
1984 The result of pow(self, other, modulo) is identical to the
1985 result that would be obtained by computing (self**other) %
1986 modulo with unbounded precision, but is computed more
1987 efficiently. It is always exact.
1988 """
1989
1990 if modulo is not None:
1991 return self._power_modulo(other, modulo, context)
1992
1993 other = _convert_other(other)
1994 if other is NotImplemented:
1995 return other
1996
1997 if context is None:
1998 context = getcontext()
1999
2000 # either argument is a NaN => result is NaN
2001 ans = self._check_nans(other, context)
2002 if ans:
2003 return ans
2004
2005 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2006 if not other:
2007 if not self:
2008 return context._raise_error(InvalidOperation, '0 ** 0')
2009 else:
2010 return Dec_p1
2011
2012 # result has sign 1 iff self._sign is 1 and other is an odd integer
2013 result_sign = 0
2014 if self._sign == 1:
2015 if other._isinteger():
2016 if not other._iseven():
2017 result_sign = 1
2018 else:
2019 # -ve**noninteger = NaN
2020 # (-0)**noninteger = 0**noninteger
2021 if self:
2022 return context._raise_error(InvalidOperation,
2023 'x ** y with x negative and y not an integer')
2024 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002025 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002026
2027 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2028 if not self:
2029 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002030 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002031 else:
2032 return Infsign[result_sign]
2033
2034 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002035 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002036 if other._sign == 0:
2037 return Infsign[result_sign]
2038 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002039 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002040
Facundo Batista353750c2007-09-13 18:13:15 +00002041 # 1**other = 1, but the choice of exponent and the flags
2042 # depend on the exponent of self, and on whether other is a
2043 # positive integer, a negative integer, or neither
2044 if self == Dec_p1:
2045 if other._isinteger():
2046 # exp = max(self._exp*max(int(other), 0),
2047 # 1-context.prec) but evaluating int(other) directly
2048 # is dangerous until we know other is small (other
2049 # could be 1e999999999)
2050 if other._sign == 1:
2051 multiplier = 0
2052 elif other > context.prec:
2053 multiplier = context.prec
2054 else:
2055 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002056
Facundo Batista353750c2007-09-13 18:13:15 +00002057 exp = self._exp * multiplier
2058 if exp < 1-context.prec:
2059 exp = 1-context.prec
2060 context._raise_error(Rounded)
2061 else:
2062 context._raise_error(Inexact)
2063 context._raise_error(Rounded)
2064 exp = 1-context.prec
2065
Facundo Batista72bc54f2007-11-23 17:59:00 +00002066 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002067
2068 # compute adjusted exponent of self
2069 self_adj = self.adjusted()
2070
2071 # self ** infinity is infinity if self > 1, 0 if self < 1
2072 # self ** -infinity is infinity if self < 1, 0 if self > 1
2073 if other._isinfinity():
2074 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002075 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002076 else:
2077 return Infsign[result_sign]
2078
2079 # from here on, the result always goes through the call
2080 # to _fix at the end of this function.
2081 ans = None
2082
2083 # crude test to catch cases of extreme overflow/underflow. If
2084 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2085 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2086 # self**other >= 10**(Emax+1), so overflow occurs. The test
2087 # for underflow is similar.
2088 bound = self._log10_exp_bound() + other.adjusted()
2089 if (self_adj >= 0) == (other._sign == 0):
2090 # self > 1 and other +ve, or self < 1 and other -ve
2091 # possibility of overflow
2092 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002093 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002094 else:
2095 # self > 1 and other -ve, or self < 1 and other +ve
2096 # possibility of underflow to 0
2097 Etiny = context.Etiny()
2098 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002099 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002100
2101 # try for an exact result with precision +1
2102 if ans is None:
2103 ans = self._power_exact(other, context.prec + 1)
2104 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002105 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002106
2107 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2108 if ans is None:
2109 p = context.prec
2110 x = _WorkRep(self)
2111 xc, xe = x.int, x.exp
2112 y = _WorkRep(other)
2113 yc, ye = y.int, y.exp
2114 if y.sign == 1:
2115 yc = -yc
2116
2117 # compute correctly rounded result: start with precision +3,
2118 # then increase precision until result is unambiguously roundable
2119 extra = 3
2120 while True:
2121 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2122 if coeff % (5*10**(len(str(coeff))-p-1)):
2123 break
2124 extra += 3
2125
Facundo Batista72bc54f2007-11-23 17:59:00 +00002126 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002127
2128 # the specification says that for non-integer other we need to
2129 # raise Inexact, even when the result is actually exact. In
2130 # the same way, we need to raise Underflow here if the result
2131 # is subnormal. (The call to _fix will take care of raising
2132 # Rounded and Subnormal, as usual.)
2133 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002134 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002135 # pad with zeros up to length context.prec+1 if necessary
2136 if len(ans._int) <= context.prec:
2137 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002138 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2139 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002140 if ans.adjusted() < context.Emin:
2141 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002142
Facundo Batista353750c2007-09-13 18:13:15 +00002143 # unlike exp, ln and log10, the power function respects the
2144 # rounding mode; no need to use ROUND_HALF_EVEN here
2145 ans = ans._fix(context)
2146 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002147
2148 def __rpow__(self, other, context=None):
2149 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002150 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002151 if other is NotImplemented:
2152 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002153 return other.__pow__(self, context=context)
2154
2155 def normalize(self, context=None):
2156 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002157
Facundo Batista353750c2007-09-13 18:13:15 +00002158 if context is None:
2159 context = getcontext()
2160
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002161 if self._is_special:
2162 ans = self._check_nans(context=context)
2163 if ans:
2164 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002165
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002166 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002167 if dup._isinfinity():
2168 return dup
2169
2170 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002171 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002172 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002173 end = len(dup._int)
2174 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002175 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002176 exp += 1
2177 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002178 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002179
Facundo Batistabd2fe832007-09-13 18:42:09 +00002180 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002181 """Quantize self so its exponent is the same as that of exp.
2182
2183 Similar to self._rescale(exp._exp) but with error checking.
2184 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002185 exp = _convert_other(exp, raiseit=True)
2186
Facundo Batista353750c2007-09-13 18:13:15 +00002187 if context is None:
2188 context = getcontext()
2189 if rounding is None:
2190 rounding = context.rounding
2191
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002192 if self._is_special or exp._is_special:
2193 ans = self._check_nans(exp, context)
2194 if ans:
2195 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002196
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002197 if exp._isinfinity() or self._isinfinity():
2198 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002199 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002200 return context._raise_error(InvalidOperation,
2201 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002202
Facundo Batistabd2fe832007-09-13 18:42:09 +00002203 # if we're not watching exponents, do a simple rescale
2204 if not watchexp:
2205 ans = self._rescale(exp._exp, rounding)
2206 # raise Inexact and Rounded where appropriate
2207 if ans._exp > self._exp:
2208 context._raise_error(Rounded)
2209 if ans != self:
2210 context._raise_error(Inexact)
2211 return ans
2212
Facundo Batista353750c2007-09-13 18:13:15 +00002213 # exp._exp should be between Etiny and Emax
2214 if not (context.Etiny() <= exp._exp <= context.Emax):
2215 return context._raise_error(InvalidOperation,
2216 'target exponent out of bounds in quantize')
2217
2218 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002219 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002220 return ans._fix(context)
2221
2222 self_adjusted = self.adjusted()
2223 if self_adjusted > context.Emax:
2224 return context._raise_error(InvalidOperation,
2225 'exponent of quantize result too large for current context')
2226 if self_adjusted - exp._exp + 1 > context.prec:
2227 return context._raise_error(InvalidOperation,
2228 'quantize result has too many digits for current context')
2229
2230 ans = self._rescale(exp._exp, rounding)
2231 if ans.adjusted() > context.Emax:
2232 return context._raise_error(InvalidOperation,
2233 'exponent of quantize result too large for current context')
2234 if len(ans._int) > context.prec:
2235 return context._raise_error(InvalidOperation,
2236 'quantize result has too many digits for current context')
2237
2238 # raise appropriate flags
2239 if ans._exp > self._exp:
2240 context._raise_error(Rounded)
2241 if ans != self:
2242 context._raise_error(Inexact)
2243 if ans and ans.adjusted() < context.Emin:
2244 context._raise_error(Subnormal)
2245
2246 # call to fix takes care of any necessary folddown
2247 ans = ans._fix(context)
2248 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002249
2250 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002251 """Return True if self and other have the same exponent; otherwise
2252 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002253
Facundo Batista1a191df2007-10-02 17:01:24 +00002254 If either operand is a special value, the following rules are used:
2255 * return True if both operands are infinities
2256 * return True if both operands are NaNs
2257 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002258 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002259 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002260 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002261 return (self.is_nan() and other.is_nan() or
2262 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002263 return self._exp == other._exp
2264
Facundo Batista353750c2007-09-13 18:13:15 +00002265 def _rescale(self, exp, rounding):
2266 """Rescale self so that the exponent is exp, either by padding with zeros
2267 or by truncating digits, using the given rounding mode.
2268
2269 Specials are returned without change. This operation is
2270 quiet: it raises no flags, and uses no information from the
2271 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002272
2273 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002274 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002275 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002276 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002277 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002278 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002279 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002280
Facundo Batista353750c2007-09-13 18:13:15 +00002281 if self._exp >= exp:
2282 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002283 return _dec_from_triple(self._sign,
2284 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002285
Facundo Batista353750c2007-09-13 18:13:15 +00002286 # too many digits; round and lose data. If self.adjusted() <
2287 # exp-1, replace self by 10**(exp-1) before rounding
2288 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002289 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002290 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002291 digits = 0
2292 this_function = getattr(self, self._pick_rounding_function[rounding])
2293 return this_function(digits)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002294
Facundo Batista353750c2007-09-13 18:13:15 +00002295 def to_integral_exact(self, rounding=None, context=None):
2296 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002297
Facundo Batista353750c2007-09-13 18:13:15 +00002298 If no rounding mode is specified, take the rounding mode from
2299 the context. This method raises the Rounded and Inexact flags
2300 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002301
Facundo Batista353750c2007-09-13 18:13:15 +00002302 See also: to_integral_value, which does exactly the same as
2303 this method except that it doesn't raise Inexact or Rounded.
2304 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002305 if self._is_special:
2306 ans = self._check_nans(context=context)
2307 if ans:
2308 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002309 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002310 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002311 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002312 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002313 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002314 if context is None:
2315 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002316 if rounding is None:
2317 rounding = context.rounding
2318 context._raise_error(Rounded)
2319 ans = self._rescale(0, rounding)
2320 if ans != self:
2321 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002322 return ans
2323
Facundo Batista353750c2007-09-13 18:13:15 +00002324 def to_integral_value(self, rounding=None, context=None):
2325 """Rounds to the nearest integer, without raising inexact, rounded."""
2326 if context is None:
2327 context = getcontext()
2328 if rounding is None:
2329 rounding = context.rounding
2330 if self._is_special:
2331 ans = self._check_nans(context=context)
2332 if ans:
2333 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002334 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002335 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002336 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002337 else:
2338 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002339
Facundo Batista353750c2007-09-13 18:13:15 +00002340 # the method name changed, but we provide also the old one, for compatibility
2341 to_integral = to_integral_value
2342
2343 def sqrt(self, context=None):
2344 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002345 if self._is_special:
2346 ans = self._check_nans(context=context)
2347 if ans:
2348 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002349
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002350 if self._isinfinity() and self._sign == 0:
2351 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002352
2353 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002354 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002355 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002356 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002357
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002358 if context is None:
2359 context = getcontext()
2360
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002361 if self._sign == 1:
2362 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2363
Facundo Batista353750c2007-09-13 18:13:15 +00002364 # At this point self represents a positive number. Let p be
2365 # the desired precision and express self in the form c*100**e
2366 # with c a positive real number and e an integer, c and e
2367 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2368 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2369 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2370 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2371 # the closest integer to sqrt(c) with the even integer chosen
2372 # in the case of a tie.
2373 #
2374 # To ensure correct rounding in all cases, we use the
2375 # following trick: we compute the square root to an extra
2376 # place (precision p+1 instead of precision p), rounding down.
2377 # Then, if the result is inexact and its last digit is 0 or 5,
2378 # we increase the last digit to 1 or 6 respectively; if it's
2379 # exact we leave the last digit alone. Now the final round to
2380 # p places (or fewer in the case of underflow) will round
2381 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002382
Facundo Batista353750c2007-09-13 18:13:15 +00002383 # use an extra digit of precision
2384 prec = context.prec+1
2385
2386 # write argument in the form c*100**e where e = self._exp//2
2387 # is the 'ideal' exponent, to be used if the square root is
2388 # exactly representable. l is the number of 'digits' of c in
2389 # base 100, so that 100**(l-1) <= c < 100**l.
2390 op = _WorkRep(self)
2391 e = op.exp >> 1
2392 if op.exp & 1:
2393 c = op.int * 10
2394 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002395 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002396 c = op.int
2397 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002398
Facundo Batista353750c2007-09-13 18:13:15 +00002399 # rescale so that c has exactly prec base 100 'digits'
2400 shift = prec-l
2401 if shift >= 0:
2402 c *= 100**shift
2403 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002404 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002405 c, remainder = divmod(c, 100**-shift)
2406 exact = not remainder
2407 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002408
Facundo Batista353750c2007-09-13 18:13:15 +00002409 # find n = floor(sqrt(c)) using Newton's method
2410 n = 10**prec
2411 while True:
2412 q = c//n
2413 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002414 break
Facundo Batista353750c2007-09-13 18:13:15 +00002415 else:
2416 n = n + q >> 1
2417 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002418
Facundo Batista353750c2007-09-13 18:13:15 +00002419 if exact:
2420 # result is exact; rescale to use ideal exponent e
2421 if shift >= 0:
2422 # assert n % 10**shift == 0
2423 n //= 10**shift
2424 else:
2425 n *= 10**-shift
2426 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002427 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002428 # result is not exact; fix last digit as described above
2429 if n % 5 == 0:
2430 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002431
Facundo Batista72bc54f2007-11-23 17:59:00 +00002432 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002433
Facundo Batista353750c2007-09-13 18:13:15 +00002434 # round, and fit to current context
2435 context = context._shallow_copy()
2436 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002437 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002438 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002439
Facundo Batista353750c2007-09-13 18:13:15 +00002440 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002441
2442 def max(self, other, context=None):
2443 """Returns the larger value.
2444
Facundo Batista353750c2007-09-13 18:13:15 +00002445 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002446 NaN (and signals if one is sNaN). Also rounds.
2447 """
Facundo Batista353750c2007-09-13 18:13:15 +00002448 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002449
Facundo Batista6c398da2007-09-17 17:30:13 +00002450 if context is None:
2451 context = getcontext()
2452
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002453 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002454 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002455 # number is always returned
2456 sn = self._isnan()
2457 on = other._isnan()
2458 if sn or on:
2459 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002460 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002461 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002462 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002463 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002464
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002465 c = self.__cmp__(other)
2466 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002467 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002468 # then an ordering is applied:
2469 #
Facundo Batista59c58842007-04-10 12:58:45 +00002470 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002471 # positive sign and min returns the operand with the negative sign
2472 #
Facundo Batista59c58842007-04-10 12:58:45 +00002473 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002474 # the result. This is exactly the ordering used in compare_total.
2475 c = self.compare_total(other)
2476
2477 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002478 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002479 else:
2480 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002481
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002482 if context._rounding_decision == ALWAYS_ROUND:
2483 return ans._fix(context)
2484 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002485
2486 def min(self, other, context=None):
2487 """Returns the smaller value.
2488
Facundo Batista59c58842007-04-10 12:58:45 +00002489 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002490 NaN (and signals if one is sNaN). Also rounds.
2491 """
Facundo Batista353750c2007-09-13 18:13:15 +00002492 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002493
Facundo Batista6c398da2007-09-17 17:30:13 +00002494 if context is None:
2495 context = getcontext()
2496
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002497 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002498 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002499 # number is always returned
2500 sn = self._isnan()
2501 on = other._isnan()
2502 if sn or on:
2503 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002504 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002505 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002506 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002507 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002508
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002509 c = self.__cmp__(other)
2510 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002511 c = self.compare_total(other)
2512
2513 if c == -1:
2514 ans = self
2515 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002516 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002517
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002518 if context._rounding_decision == ALWAYS_ROUND:
2519 return ans._fix(context)
2520 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002521
2522 def _isinteger(self):
2523 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002524 if self._is_special:
2525 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002526 if self._exp >= 0:
2527 return True
2528 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002529 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002530
2531 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002532 """Returns True if self is even. Assumes self is an integer."""
2533 if not self or self._exp > 0:
2534 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002535 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002536
2537 def adjusted(self):
2538 """Return the adjusted exponent of self"""
2539 try:
2540 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002541 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002542 except TypeError:
2543 return 0
2544
Facundo Batista353750c2007-09-13 18:13:15 +00002545 def canonical(self, context=None):
2546 """Returns the same Decimal object.
2547
2548 As we do not have different encodings for the same number, the
2549 received object already is in its canonical form.
2550 """
2551 return self
2552
2553 def compare_signal(self, other, context=None):
2554 """Compares self to the other operand numerically.
2555
2556 It's pretty much like compare(), but all NaNs signal, with signaling
2557 NaNs taking precedence over quiet NaNs.
2558 """
2559 if context is None:
2560 context = getcontext()
2561
2562 self_is_nan = self._isnan()
2563 other_is_nan = other._isnan()
2564 if self_is_nan == 2:
2565 return context._raise_error(InvalidOperation, 'sNaN',
2566 1, self)
2567 if other_is_nan == 2:
2568 return context._raise_error(InvalidOperation, 'sNaN',
2569 1, other)
2570 if self_is_nan:
2571 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2572 1, self)
2573 if other_is_nan:
2574 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2575 1, other)
2576 return self.compare(other, context=context)
2577
2578 def compare_total(self, other):
2579 """Compares self to other using the abstract representations.
2580
2581 This is not like the standard compare, which use their numerical
2582 value. Note that a total ordering is defined for all possible abstract
2583 representations.
2584 """
2585 # if one is negative and the other is positive, it's easy
2586 if self._sign and not other._sign:
2587 return Dec_n1
2588 if not self._sign and other._sign:
2589 return Dec_p1
2590 sign = self._sign
2591
2592 # let's handle both NaN types
2593 self_nan = self._isnan()
2594 other_nan = other._isnan()
2595 if self_nan or other_nan:
2596 if self_nan == other_nan:
2597 if self._int < other._int:
2598 if sign:
2599 return Dec_p1
2600 else:
2601 return Dec_n1
2602 if self._int > other._int:
2603 if sign:
2604 return Dec_n1
2605 else:
2606 return Dec_p1
2607 return Dec_0
2608
2609 if sign:
2610 if self_nan == 1:
2611 return Dec_n1
2612 if other_nan == 1:
2613 return Dec_p1
2614 if self_nan == 2:
2615 return Dec_n1
2616 if other_nan == 2:
2617 return Dec_p1
2618 else:
2619 if self_nan == 1:
2620 return Dec_p1
2621 if other_nan == 1:
2622 return Dec_n1
2623 if self_nan == 2:
2624 return Dec_p1
2625 if other_nan == 2:
2626 return Dec_n1
2627
2628 if self < other:
2629 return Dec_n1
2630 if self > other:
2631 return Dec_p1
2632
2633 if self._exp < other._exp:
2634 if sign:
2635 return Dec_p1
2636 else:
2637 return Dec_n1
2638 if self._exp > other._exp:
2639 if sign:
2640 return Dec_n1
2641 else:
2642 return Dec_p1
2643 return Dec_0
2644
2645
2646 def compare_total_mag(self, other):
2647 """Compares self to other using abstract repr., ignoring sign.
2648
2649 Like compare_total, but with operand's sign ignored and assumed to be 0.
2650 """
2651 s = self.copy_abs()
2652 o = other.copy_abs()
2653 return s.compare_total(o)
2654
2655 def copy_abs(self):
2656 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002657 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002658
2659 def copy_negate(self):
2660 """Returns a copy with the sign inverted."""
2661 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002662 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002663 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002664 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002665
2666 def copy_sign(self, other):
2667 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002668 return _dec_from_triple(other._sign, self._int,
2669 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002670
2671 def exp(self, context=None):
2672 """Returns e ** self."""
2673
2674 if context is None:
2675 context = getcontext()
2676
2677 # exp(NaN) = NaN
2678 ans = self._check_nans(context=context)
2679 if ans:
2680 return ans
2681
2682 # exp(-Infinity) = 0
2683 if self._isinfinity() == -1:
2684 return Dec_0
2685
2686 # exp(0) = 1
2687 if not self:
2688 return Dec_p1
2689
2690 # exp(Infinity) = Infinity
2691 if self._isinfinity() == 1:
2692 return Decimal(self)
2693
2694 # the result is now guaranteed to be inexact (the true
2695 # mathematical result is transcendental). There's no need to
2696 # raise Rounded and Inexact here---they'll always be raised as
2697 # a result of the call to _fix.
2698 p = context.prec
2699 adj = self.adjusted()
2700
2701 # we only need to do any computation for quite a small range
2702 # of adjusted exponents---for example, -29 <= adj <= 10 for
2703 # the default context. For smaller exponent the result is
2704 # indistinguishable from 1 at the given precision, while for
2705 # larger exponent the result either overflows or underflows.
2706 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2707 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002708 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002709 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2710 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002711 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002712 elif self._sign == 0 and adj < -p:
2713 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002714 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002715 elif self._sign == 1 and adj < -p-1:
2716 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002717 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002718 # general case
2719 else:
2720 op = _WorkRep(self)
2721 c, e = op.int, op.exp
2722 if op.sign == 1:
2723 c = -c
2724
2725 # compute correctly rounded result: increase precision by
2726 # 3 digits at a time until we get an unambiguously
2727 # roundable result
2728 extra = 3
2729 while True:
2730 coeff, exp = _dexp(c, e, p+extra)
2731 if coeff % (5*10**(len(str(coeff))-p-1)):
2732 break
2733 extra += 3
2734
Facundo Batista72bc54f2007-11-23 17:59:00 +00002735 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002736
2737 # at this stage, ans should round correctly with *any*
2738 # rounding mode, not just with ROUND_HALF_EVEN
2739 context = context._shallow_copy()
2740 rounding = context._set_rounding(ROUND_HALF_EVEN)
2741 ans = ans._fix(context)
2742 context.rounding = rounding
2743
2744 return ans
2745
2746 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002747 """Return True if self is canonical; otherwise return False.
2748
2749 Currently, the encoding of a Decimal instance is always
2750 canonical, so this method returns True for any Decimal.
2751 """
2752 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002753
2754 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002755 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002756
Facundo Batista1a191df2007-10-02 17:01:24 +00002757 A Decimal instance is considered finite if it is neither
2758 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002759 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002760 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002761
2762 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002763 """Return True if self is infinite; otherwise return False."""
2764 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002765
2766 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002767 """Return True if self is a qNaN or sNaN; otherwise return False."""
2768 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002769
2770 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002771 """Return True if self is a normal number; otherwise return False."""
2772 if self._is_special or not self:
2773 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002774 if context is None:
2775 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002776 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002777
2778 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002779 """Return True if self is a quiet NaN; otherwise return False."""
2780 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002781
2782 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002783 """Return True if self is negative; otherwise return False."""
2784 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002785
2786 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002787 """Return True if self is a signaling NaN; otherwise return False."""
2788 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002789
2790 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002791 """Return True if self is subnormal; otherwise return False."""
2792 if self._is_special or not self:
2793 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002794 if context is None:
2795 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002796 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002797
2798 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002799 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002800 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002801
2802 def _ln_exp_bound(self):
2803 """Compute a lower bound for the adjusted exponent of self.ln().
2804 In other words, compute r such that self.ln() >= 10**r. Assumes
2805 that self is finite and positive and that self != 1.
2806 """
2807
2808 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2809 adj = self._exp + len(self._int) - 1
2810 if adj >= 1:
2811 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2812 return len(str(adj*23//10)) - 1
2813 if adj <= -2:
2814 # argument <= 0.1
2815 return len(str((-1-adj)*23//10)) - 1
2816 op = _WorkRep(self)
2817 c, e = op.int, op.exp
2818 if adj == 0:
2819 # 1 < self < 10
2820 num = str(c-10**-e)
2821 den = str(c)
2822 return len(num) - len(den) - (num < den)
2823 # adj == -1, 0.1 <= self < 1
2824 return e + len(str(10**-e - c)) - 1
2825
2826
2827 def ln(self, context=None):
2828 """Returns the natural (base e) logarithm of self."""
2829
2830 if context is None:
2831 context = getcontext()
2832
2833 # ln(NaN) = NaN
2834 ans = self._check_nans(context=context)
2835 if ans:
2836 return ans
2837
2838 # ln(0.0) == -Infinity
2839 if not self:
2840 return negInf
2841
2842 # ln(Infinity) = Infinity
2843 if self._isinfinity() == 1:
2844 return Inf
2845
2846 # ln(1.0) == 0.0
2847 if self == Dec_p1:
2848 return Dec_0
2849
2850 # ln(negative) raises InvalidOperation
2851 if self._sign == 1:
2852 return context._raise_error(InvalidOperation,
2853 'ln of a negative value')
2854
2855 # result is irrational, so necessarily inexact
2856 op = _WorkRep(self)
2857 c, e = op.int, op.exp
2858 p = context.prec
2859
2860 # correctly rounded result: repeatedly increase precision by 3
2861 # until we get an unambiguously roundable result
2862 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2863 while True:
2864 coeff = _dlog(c, e, places)
2865 # assert len(str(abs(coeff)))-p >= 1
2866 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2867 break
2868 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002869 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002870
2871 context = context._shallow_copy()
2872 rounding = context._set_rounding(ROUND_HALF_EVEN)
2873 ans = ans._fix(context)
2874 context.rounding = rounding
2875 return ans
2876
2877 def _log10_exp_bound(self):
2878 """Compute a lower bound for the adjusted exponent of self.log10().
2879 In other words, find r such that self.log10() >= 10**r.
2880 Assumes that self is finite and positive and that self != 1.
2881 """
2882
2883 # For x >= 10 or x < 0.1 we only need a bound on the integer
2884 # part of log10(self), and this comes directly from the
2885 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2886 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2887 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2888
2889 adj = self._exp + len(self._int) - 1
2890 if adj >= 1:
2891 # self >= 10
2892 return len(str(adj))-1
2893 if adj <= -2:
2894 # self < 0.1
2895 return len(str(-1-adj))-1
2896 op = _WorkRep(self)
2897 c, e = op.int, op.exp
2898 if adj == 0:
2899 # 1 < self < 10
2900 num = str(c-10**-e)
2901 den = str(231*c)
2902 return len(num) - len(den) - (num < den) + 2
2903 # adj == -1, 0.1 <= self < 1
2904 num = str(10**-e-c)
2905 return len(num) + e - (num < "231") - 1
2906
2907 def log10(self, context=None):
2908 """Returns the base 10 logarithm of self."""
2909
2910 if context is None:
2911 context = getcontext()
2912
2913 # log10(NaN) = NaN
2914 ans = self._check_nans(context=context)
2915 if ans:
2916 return ans
2917
2918 # log10(0.0) == -Infinity
2919 if not self:
2920 return negInf
2921
2922 # log10(Infinity) = Infinity
2923 if self._isinfinity() == 1:
2924 return Inf
2925
2926 # log10(negative or -Infinity) raises InvalidOperation
2927 if self._sign == 1:
2928 return context._raise_error(InvalidOperation,
2929 'log10 of a negative value')
2930
2931 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00002932 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00002933 # answer may need rounding
2934 ans = Decimal(self._exp + len(self._int) - 1)
2935 else:
2936 # result is irrational, so necessarily inexact
2937 op = _WorkRep(self)
2938 c, e = op.int, op.exp
2939 p = context.prec
2940
2941 # correctly rounded result: repeatedly increase precision
2942 # until result is unambiguously roundable
2943 places = p-self._log10_exp_bound()+2
2944 while True:
2945 coeff = _dlog10(c, e, places)
2946 # assert len(str(abs(coeff)))-p >= 1
2947 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2948 break
2949 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002950 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002951
2952 context = context._shallow_copy()
2953 rounding = context._set_rounding(ROUND_HALF_EVEN)
2954 ans = ans._fix(context)
2955 context.rounding = rounding
2956 return ans
2957
2958 def logb(self, context=None):
2959 """ Returns the exponent of the magnitude of self's MSD.
2960
2961 The result is the integer which is the exponent of the magnitude
2962 of the most significant digit of self (as though it were truncated
2963 to a single digit while maintaining the value of that digit and
2964 without limiting the resulting exponent).
2965 """
2966 # logb(NaN) = NaN
2967 ans = self._check_nans(context=context)
2968 if ans:
2969 return ans
2970
2971 if context is None:
2972 context = getcontext()
2973
2974 # logb(+/-Inf) = +Inf
2975 if self._isinfinity():
2976 return Inf
2977
2978 # logb(0) = -Inf, DivisionByZero
2979 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00002980 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00002981
2982 # otherwise, simply return the adjusted exponent of self, as a
2983 # Decimal. Note that no attempt is made to fit the result
2984 # into the current context.
2985 return Decimal(self.adjusted())
2986
2987 def _islogical(self):
2988 """Return True if self is a logical operand.
2989
2990 For being logical, it must be a finite numbers with a sign of 0,
2991 an exponent of 0, and a coefficient whose digits must all be
2992 either 0 or 1.
2993 """
2994 if self._sign != 0 or self._exp != 0:
2995 return False
2996 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002997 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00002998 return False
2999 return True
3000
3001 def _fill_logical(self, context, opa, opb):
3002 dif = context.prec - len(opa)
3003 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003004 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00003005 elif dif < 0:
3006 opa = opa[-context.prec:]
3007 dif = context.prec - len(opb)
3008 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003009 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00003010 elif dif < 0:
3011 opb = opb[-context.prec:]
3012 return opa, opb
3013
3014 def logical_and(self, other, context=None):
3015 """Applies an 'and' operation between self and other's digits."""
3016 if context is None:
3017 context = getcontext()
3018 if not self._islogical() or not other._islogical():
3019 return context._raise_error(InvalidOperation)
3020
3021 # fill to context.prec
3022 (opa, opb) = self._fill_logical(context, self._int, other._int)
3023
3024 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003025 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3026 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003027
3028 def logical_invert(self, context=None):
3029 """Invert all its digits."""
3030 if context is None:
3031 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003032 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3033 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003034
3035 def logical_or(self, other, context=None):
3036 """Applies an 'or' operation between self and other's digits."""
3037 if context is None:
3038 context = getcontext()
3039 if not self._islogical() or not other._islogical():
3040 return context._raise_error(InvalidOperation)
3041
3042 # fill to context.prec
3043 (opa, opb) = self._fill_logical(context, self._int, other._int)
3044
3045 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003046 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3047 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003048
3049 def logical_xor(self, other, context=None):
3050 """Applies an 'xor' operation between self and other's digits."""
3051 if context is None:
3052 context = getcontext()
3053 if not self._islogical() or not other._islogical():
3054 return context._raise_error(InvalidOperation)
3055
3056 # fill to context.prec
3057 (opa, opb) = self._fill_logical(context, self._int, other._int)
3058
3059 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003060 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3061 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003062
3063 def max_mag(self, other, context=None):
3064 """Compares the values numerically with their sign ignored."""
3065 other = _convert_other(other, raiseit=True)
3066
Facundo Batista6c398da2007-09-17 17:30:13 +00003067 if context is None:
3068 context = getcontext()
3069
Facundo Batista353750c2007-09-13 18:13:15 +00003070 if self._is_special or other._is_special:
3071 # If one operand is a quiet NaN and the other is number, then the
3072 # number is always returned
3073 sn = self._isnan()
3074 on = other._isnan()
3075 if sn or on:
3076 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003077 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003078 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003079 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003080 return self._check_nans(other, context)
3081
3082 c = self.copy_abs().__cmp__(other.copy_abs())
3083 if c == 0:
3084 c = self.compare_total(other)
3085
3086 if c == -1:
3087 ans = other
3088 else:
3089 ans = self
3090
Facundo Batista353750c2007-09-13 18:13:15 +00003091 if context._rounding_decision == ALWAYS_ROUND:
3092 return ans._fix(context)
3093 return ans
3094
3095 def min_mag(self, other, context=None):
3096 """Compares the values numerically with their sign ignored."""
3097 other = _convert_other(other, raiseit=True)
3098
Facundo Batista6c398da2007-09-17 17:30:13 +00003099 if context is None:
3100 context = getcontext()
3101
Facundo Batista353750c2007-09-13 18:13:15 +00003102 if self._is_special or other._is_special:
3103 # If one operand is a quiet NaN and the other is number, then the
3104 # number is always returned
3105 sn = self._isnan()
3106 on = other._isnan()
3107 if sn or on:
3108 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003109 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003110 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003111 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003112 return self._check_nans(other, context)
3113
3114 c = self.copy_abs().__cmp__(other.copy_abs())
3115 if c == 0:
3116 c = self.compare_total(other)
3117
3118 if c == -1:
3119 ans = self
3120 else:
3121 ans = other
3122
Facundo Batista353750c2007-09-13 18:13:15 +00003123 if context._rounding_decision == ALWAYS_ROUND:
3124 return ans._fix(context)
3125 return ans
3126
3127 def next_minus(self, context=None):
3128 """Returns the largest representable number smaller than itself."""
3129 if context is None:
3130 context = getcontext()
3131
3132 ans = self._check_nans(context=context)
3133 if ans:
3134 return ans
3135
3136 if self._isinfinity() == -1:
3137 return negInf
3138 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003139 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003140
3141 context = context.copy()
3142 context._set_rounding(ROUND_FLOOR)
3143 context._ignore_all_flags()
3144 new_self = self._fix(context)
3145 if new_self != self:
3146 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003147 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3148 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003149
3150 def next_plus(self, context=None):
3151 """Returns the smallest representable number larger than itself."""
3152 if context is None:
3153 context = getcontext()
3154
3155 ans = self._check_nans(context=context)
3156 if ans:
3157 return ans
3158
3159 if self._isinfinity() == 1:
3160 return Inf
3161 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003162 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003163
3164 context = context.copy()
3165 context._set_rounding(ROUND_CEILING)
3166 context._ignore_all_flags()
3167 new_self = self._fix(context)
3168 if new_self != self:
3169 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003170 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3171 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003172
3173 def next_toward(self, other, context=None):
3174 """Returns the number closest to self, in the direction towards other.
3175
3176 The result is the closest representable number to self
3177 (excluding self) that is in the direction towards other,
3178 unless both have the same value. If the two operands are
3179 numerically equal, then the result is a copy of self with the
3180 sign set to be the same as the sign of other.
3181 """
3182 other = _convert_other(other, raiseit=True)
3183
3184 if context is None:
3185 context = getcontext()
3186
3187 ans = self._check_nans(other, context)
3188 if ans:
3189 return ans
3190
3191 comparison = self.__cmp__(other)
3192 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003193 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003194
3195 if comparison == -1:
3196 ans = self.next_plus(context)
3197 else: # comparison == 1
3198 ans = self.next_minus(context)
3199
3200 # decide which flags to raise using value of ans
3201 if ans._isinfinity():
3202 context._raise_error(Overflow,
3203 'Infinite result from next_toward',
3204 ans._sign)
3205 context._raise_error(Rounded)
3206 context._raise_error(Inexact)
3207 elif ans.adjusted() < context.Emin:
3208 context._raise_error(Underflow)
3209 context._raise_error(Subnormal)
3210 context._raise_error(Rounded)
3211 context._raise_error(Inexact)
3212 # if precision == 1 then we don't raise Clamped for a
3213 # result 0E-Etiny.
3214 if not ans:
3215 context._raise_error(Clamped)
3216
3217 return ans
3218
3219 def number_class(self, context=None):
3220 """Returns an indication of the class of self.
3221
3222 The class is one of the following strings:
3223 -sNaN
3224 -NaN
3225 -Infinity
3226 -Normal
3227 -Subnormal
3228 -Zero
3229 +Zero
3230 +Subnormal
3231 +Normal
3232 +Infinity
3233 """
3234 if self.is_snan():
3235 return "sNaN"
3236 if self.is_qnan():
3237 return "NaN"
3238 inf = self._isinfinity()
3239 if inf == 1:
3240 return "+Infinity"
3241 if inf == -1:
3242 return "-Infinity"
3243 if self.is_zero():
3244 if self._sign:
3245 return "-Zero"
3246 else:
3247 return "+Zero"
3248 if context is None:
3249 context = getcontext()
3250 if self.is_subnormal(context=context):
3251 if self._sign:
3252 return "-Subnormal"
3253 else:
3254 return "+Subnormal"
3255 # just a normal, regular, boring number, :)
3256 if self._sign:
3257 return "-Normal"
3258 else:
3259 return "+Normal"
3260
3261 def radix(self):
3262 """Just returns 10, as this is Decimal, :)"""
3263 return Decimal(10)
3264
3265 def rotate(self, other, context=None):
3266 """Returns a rotated copy of self, value-of-other times."""
3267 if context is None:
3268 context = getcontext()
3269
3270 ans = self._check_nans(other, context)
3271 if ans:
3272 return ans
3273
3274 if other._exp != 0:
3275 return context._raise_error(InvalidOperation)
3276 if not (-context.prec <= int(other) <= context.prec):
3277 return context._raise_error(InvalidOperation)
3278
3279 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003280 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003281
3282 # get values, pad if necessary
3283 torot = int(other)
3284 rotdig = self._int
3285 topad = context.prec - len(rotdig)
3286 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003287 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003288
3289 # let's rotate!
3290 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003291 return _dec_from_triple(self._sign,
3292 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003293
3294 def scaleb (self, other, context=None):
3295 """Returns self operand after adding the second value to its exp."""
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 liminf = -2 * (context.Emax + context.prec)
3306 limsup = 2 * (context.Emax + context.prec)
3307 if not (liminf <= int(other) <= limsup):
3308 return context._raise_error(InvalidOperation)
3309
3310 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003311 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003312
Facundo Batista72bc54f2007-11-23 17:59:00 +00003313 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003314 d = d._fix(context)
3315 return d
3316
3317 def shift(self, other, context=None):
3318 """Returns a shifted copy of self, value-of-other times."""
3319 if context is None:
3320 context = getcontext()
3321
3322 ans = self._check_nans(other, context)
3323 if ans:
3324 return ans
3325
3326 if other._exp != 0:
3327 return context._raise_error(InvalidOperation)
3328 if not (-context.prec <= int(other) <= context.prec):
3329 return context._raise_error(InvalidOperation)
3330
3331 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003332 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003333
3334 # get values, pad if necessary
3335 torot = int(other)
3336 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003337 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003338 rotdig = self._int
3339 topad = context.prec - len(rotdig)
3340 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003341 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003342
3343 # let's shift!
3344 if torot < 0:
3345 rotated = rotdig[:torot]
3346 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003347 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003348 rotated = rotated[-context.prec:]
3349
Facundo Batista72bc54f2007-11-23 17:59:00 +00003350 return _dec_from_triple(self._sign,
3351 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003352
Facundo Batista59c58842007-04-10 12:58:45 +00003353 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003354 def __reduce__(self):
3355 return (self.__class__, (str(self),))
3356
3357 def __copy__(self):
3358 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003359 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003360 return self.__class__(str(self))
3361
3362 def __deepcopy__(self, memo):
3363 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003364 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003365 return self.__class__(str(self))
3366
Facundo Batista72bc54f2007-11-23 17:59:00 +00003367def _dec_from_triple(sign, coefficient, exponent, special=False):
3368 """Create a decimal instance directly, without any validation,
3369 normalization (e.g. removal of leading zeros) or argument
3370 conversion.
3371
3372 This function is for *internal use only*.
3373 """
3374
3375 self = object.__new__(Decimal)
3376 self._sign = sign
3377 self._int = coefficient
3378 self._exp = exponent
3379 self._is_special = special
3380
3381 return self
3382
Facundo Batista59c58842007-04-10 12:58:45 +00003383##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003384
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003385
3386# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003387rounding_functions = [name for name in Decimal.__dict__.keys()
3388 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003389for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003390 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003391 globalname = name[1:].upper()
3392 val = globals()[globalname]
3393 Decimal._pick_rounding_function[val] = name
3394
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003395del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003396
Nick Coghlanced12182006-09-02 03:54:17 +00003397class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003398 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003399
Nick Coghlanced12182006-09-02 03:54:17 +00003400 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003401 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003402 """
3403 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003404 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003405 def __enter__(self):
3406 self.saved_context = getcontext()
3407 setcontext(self.new_context)
3408 return self.new_context
3409 def __exit__(self, t, v, tb):
3410 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003411
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003412class Context(object):
3413 """Contains the context for a Decimal instance.
3414
3415 Contains:
3416 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003417 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003418 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003419 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003420 raised when it is caused. Otherwise, a value is
3421 substituted in.
3422 flags - When an exception is caused, flags[exception] is incremented.
3423 (Whether or not the trap_enabler is set)
3424 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003425 Emin - Minimum exponent
3426 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003427 capitals - If 1, 1*10^1 is printed as 1E+1.
3428 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003429 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003430 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003431
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003432 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003433 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003434 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003435 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003436 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003437 _ignored_flags=None):
3438 if flags is None:
3439 flags = []
3440 if _ignored_flags is None:
3441 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003442 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003443 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003444 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003445 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003446 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003447 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003448 for name, val in locals().items():
3449 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003450 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003451 else:
3452 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003453 del self.self
3454
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003455 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003456 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003457 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003458 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3459 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3460 % vars(self))
3461 names = [f.__name__ for f, v in self.flags.items() if v]
3462 s.append('flags=[' + ', '.join(names) + ']')
3463 names = [t.__name__ for t, v in self.traps.items() if v]
3464 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003465 return ', '.join(s) + ')'
3466
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003467 def clear_flags(self):
3468 """Reset all flags to zero"""
3469 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003470 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003471
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003472 def _shallow_copy(self):
3473 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003474 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003475 self._rounding_decision, self.Emin, self.Emax,
3476 self.capitals, self._clamp, self._ignored_flags)
3477 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003478
3479 def copy(self):
3480 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003481 nc = Context(self.prec, self.rounding, self.traps.copy(),
3482 self.flags.copy(), self._rounding_decision, self.Emin,
3483 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003484 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003485 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003486
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003487 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003488 """Handles an error
3489
3490 If the flag is in _ignored_flags, returns the default response.
3491 Otherwise, it increments the flag, then, if the corresponding
3492 trap_enabler is set, it reaises the exception. Otherwise, it returns
3493 the default value after incrementing the flag.
3494 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003495 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003496 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003497 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003498 return error().handle(self, *args)
3499
3500 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003501 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003502 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003503 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003504
3505 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003506 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003507 raise error, explanation
3508
3509 def _ignore_all_flags(self):
3510 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003511 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003512
3513 def _ignore_flags(self, *flags):
3514 """Ignore the flags, if they are raised"""
3515 # Do not mutate-- This way, copies of a context leave the original
3516 # alone.
3517 self._ignored_flags = (self._ignored_flags + list(flags))
3518 return list(flags)
3519
3520 def _regard_flags(self, *flags):
3521 """Stop ignoring the flags, if they are raised"""
3522 if flags and isinstance(flags[0], (tuple,list)):
3523 flags = flags[0]
3524 for flag in flags:
3525 self._ignored_flags.remove(flag)
3526
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003527 def __hash__(self):
3528 """A Context cannot be hashed."""
3529 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003530 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003531
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003532 def Etiny(self):
3533 """Returns Etiny (= Emin - prec + 1)"""
3534 return int(self.Emin - self.prec + 1)
3535
3536 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003537 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003538 return int(self.Emax - self.prec + 1)
3539
3540 def _set_rounding_decision(self, type):
3541 """Sets the rounding decision.
3542
3543 Sets the rounding decision, and returns the current (previous)
3544 rounding decision. Often used like:
3545
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003546 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003547 # That so you don't change the calling context
3548 # if an error occurs in the middle (say DivisionImpossible is raised).
3549
3550 rounding = context._set_rounding_decision(NEVER_ROUND)
3551 instance = instance / Decimal(2)
3552 context._set_rounding_decision(rounding)
3553
3554 This will make it not round for that operation.
3555 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003556
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003557 rounding = self._rounding_decision
3558 self._rounding_decision = type
3559 return rounding
3560
3561 def _set_rounding(self, type):
3562 """Sets the rounding type.
3563
3564 Sets the rounding type, and returns the current (previous)
3565 rounding type. Often used like:
3566
3567 context = context.copy()
3568 # so you don't change the calling context
3569 # if an error occurs in the middle.
3570 rounding = context._set_rounding(ROUND_UP)
3571 val = self.__sub__(other, context=context)
3572 context._set_rounding(rounding)
3573
3574 This will make it round up for that operation.
3575 """
3576 rounding = self.rounding
3577 self.rounding= type
3578 return rounding
3579
Raymond Hettingerfed52962004-07-14 15:41:57 +00003580 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003581 """Creates a new Decimal instance but using self as context."""
3582 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003583 if d._isnan() and len(d._int) > self.prec - self._clamp:
3584 return self._raise_error(ConversionSyntax,
3585 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003586 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003587
Facundo Batista59c58842007-04-10 12:58:45 +00003588 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003589 def abs(self, a):
3590 """Returns the absolute value of the operand.
3591
3592 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003593 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003594 the plus operation on the operand.
3595
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003596 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003597 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003598 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003599 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003600 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003601 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003602 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003603 Decimal("101.5")
3604 """
3605 return a.__abs__(context=self)
3606
3607 def add(self, a, b):
3608 """Return the sum of the two operands.
3609
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003610 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003611 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003612 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003613 Decimal("1.02E+4")
3614 """
3615 return a.__add__(b, context=self)
3616
3617 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003618 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003619
Facundo Batista353750c2007-09-13 18:13:15 +00003620 def canonical(self, a):
3621 """Returns the same Decimal object.
3622
3623 As we do not have different encodings for the same number, the
3624 received object already is in its canonical form.
3625
3626 >>> ExtendedContext.canonical(Decimal('2.50'))
3627 Decimal("2.50")
3628 """
3629 return a.canonical(context=self)
3630
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003631 def compare(self, a, b):
3632 """Compares values numerically.
3633
3634 If the signs of the operands differ, a value representing each operand
3635 ('-1' if the operand is less than zero, '0' if the operand is zero or
3636 negative zero, or '1' if the operand is greater than zero) is used in
3637 place of that operand for the comparison instead of the actual
3638 operand.
3639
3640 The comparison is then effected by subtracting the second operand from
3641 the first and then returning a value according to the result of the
3642 subtraction: '-1' if the result is less than zero, '0' if the result is
3643 zero or negative zero, or '1' if the result is greater than zero.
3644
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003645 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003646 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003647 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003648 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003649 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003650 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003651 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003652 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003653 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003654 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003655 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003656 Decimal("-1")
3657 """
3658 return a.compare(b, context=self)
3659
Facundo Batista353750c2007-09-13 18:13:15 +00003660 def compare_signal(self, a, b):
3661 """Compares the values of the two operands numerically.
3662
3663 It's pretty much like compare(), but all NaNs signal, with signaling
3664 NaNs taking precedence over quiet NaNs.
3665
3666 >>> c = ExtendedContext
3667 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3668 Decimal("-1")
3669 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3670 Decimal("0")
3671 >>> c.flags[InvalidOperation] = 0
3672 >>> print c.flags[InvalidOperation]
3673 0
3674 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3675 Decimal("NaN")
3676 >>> print c.flags[InvalidOperation]
3677 1
3678 >>> c.flags[InvalidOperation] = 0
3679 >>> print c.flags[InvalidOperation]
3680 0
3681 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3682 Decimal("NaN")
3683 >>> print c.flags[InvalidOperation]
3684 1
3685 """
3686 return a.compare_signal(b, context=self)
3687
3688 def compare_total(self, a, b):
3689 """Compares two operands using their abstract representation.
3690
3691 This is not like the standard compare, which use their numerical
3692 value. Note that a total ordering is defined for all possible abstract
3693 representations.
3694
3695 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3696 Decimal("-1")
3697 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3698 Decimal("-1")
3699 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3700 Decimal("-1")
3701 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3702 Decimal("0")
3703 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3704 Decimal("1")
3705 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3706 Decimal("-1")
3707 """
3708 return a.compare_total(b)
3709
3710 def compare_total_mag(self, a, b):
3711 """Compares two operands using their abstract representation ignoring sign.
3712
3713 Like compare_total, but with operand's sign ignored and assumed to be 0.
3714 """
3715 return a.compare_total_mag(b)
3716
3717 def copy_abs(self, a):
3718 """Returns a copy of the operand with the sign set to 0.
3719
3720 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3721 Decimal("2.1")
3722 >>> ExtendedContext.copy_abs(Decimal('-100'))
3723 Decimal("100")
3724 """
3725 return a.copy_abs()
3726
3727 def copy_decimal(self, a):
3728 """Returns a copy of the decimal objet.
3729
3730 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3731 Decimal("2.1")
3732 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3733 Decimal("-1.00")
3734 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003735 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003736
3737 def copy_negate(self, a):
3738 """Returns a copy of the operand with the sign inverted.
3739
3740 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3741 Decimal("-101.5")
3742 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3743 Decimal("101.5")
3744 """
3745 return a.copy_negate()
3746
3747 def copy_sign(self, a, b):
3748 """Copies the second operand's sign to the first one.
3749
3750 In detail, it returns a copy of the first operand with the sign
3751 equal to the sign of the second operand.
3752
3753 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3754 Decimal("1.50")
3755 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3756 Decimal("1.50")
3757 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3758 Decimal("-1.50")
3759 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3760 Decimal("-1.50")
3761 """
3762 return a.copy_sign(b)
3763
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003764 def divide(self, a, b):
3765 """Decimal division in a specified context.
3766
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003767 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003768 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003769 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003770 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003771 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003772 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003773 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003774 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003775 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003776 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003777 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003778 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003779 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003780 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003781 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003782 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003783 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003784 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003785 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003786 Decimal("1.20E+6")
3787 """
3788 return a.__div__(b, context=self)
3789
3790 def divide_int(self, a, b):
3791 """Divides two numbers and returns the integer part of the result.
3792
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003793 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003794 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003795 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003796 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003797 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003798 Decimal("3")
3799 """
3800 return a.__floordiv__(b, context=self)
3801
3802 def divmod(self, a, b):
3803 return a.__divmod__(b, context=self)
3804
Facundo Batista353750c2007-09-13 18:13:15 +00003805 def exp(self, a):
3806 """Returns e ** a.
3807
3808 >>> c = ExtendedContext.copy()
3809 >>> c.Emin = -999
3810 >>> c.Emax = 999
3811 >>> c.exp(Decimal('-Infinity'))
3812 Decimal("0")
3813 >>> c.exp(Decimal('-1'))
3814 Decimal("0.367879441")
3815 >>> c.exp(Decimal('0'))
3816 Decimal("1")
3817 >>> c.exp(Decimal('1'))
3818 Decimal("2.71828183")
3819 >>> c.exp(Decimal('0.693147181'))
3820 Decimal("2.00000000")
3821 >>> c.exp(Decimal('+Infinity'))
3822 Decimal("Infinity")
3823 """
3824 return a.exp(context=self)
3825
3826 def fma(self, a, b, c):
3827 """Returns a multiplied by b, plus c.
3828
3829 The first two operands are multiplied together, using multiply,
3830 the third operand is then added to the result of that
3831 multiplication, using add, all with only one final rounding.
3832
3833 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3834 Decimal("22")
3835 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3836 Decimal("-8")
3837 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3838 Decimal("1.38435736E+12")
3839 """
3840 return a.fma(b, c, context=self)
3841
3842 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003843 """Return True if the operand is canonical; otherwise return False.
3844
3845 Currently, the encoding of a Decimal instance is always
3846 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00003847
3848 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003849 True
Facundo Batista353750c2007-09-13 18:13:15 +00003850 """
Facundo Batista1a191df2007-10-02 17:01:24 +00003851 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00003852
3853 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003854 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003855
Facundo Batista1a191df2007-10-02 17:01:24 +00003856 A Decimal instance is considered finite if it is neither
3857 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00003858
3859 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003860 True
Facundo Batista353750c2007-09-13 18:13:15 +00003861 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003862 True
Facundo Batista353750c2007-09-13 18:13:15 +00003863 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003864 True
Facundo Batista353750c2007-09-13 18:13:15 +00003865 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003866 False
Facundo Batista353750c2007-09-13 18:13:15 +00003867 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003868 False
Facundo Batista353750c2007-09-13 18:13:15 +00003869 """
3870 return a.is_finite()
3871
3872 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003873 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003874
3875 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003876 False
Facundo Batista353750c2007-09-13 18:13:15 +00003877 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003878 True
Facundo Batista353750c2007-09-13 18:13:15 +00003879 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003880 False
Facundo Batista353750c2007-09-13 18:13:15 +00003881 """
3882 return a.is_infinite()
3883
3884 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003885 """Return True if the operand is a qNaN or sNaN;
3886 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003887
3888 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003889 False
Facundo Batista353750c2007-09-13 18:13:15 +00003890 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003891 True
Facundo Batista353750c2007-09-13 18:13:15 +00003892 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003893 True
Facundo Batista353750c2007-09-13 18:13:15 +00003894 """
3895 return a.is_nan()
3896
3897 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003898 """Return True if the operand is a normal number;
3899 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003900
3901 >>> c = ExtendedContext.copy()
3902 >>> c.Emin = -999
3903 >>> c.Emax = 999
3904 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003905 True
Facundo Batista353750c2007-09-13 18:13:15 +00003906 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003907 False
Facundo Batista353750c2007-09-13 18:13:15 +00003908 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003909 False
Facundo Batista353750c2007-09-13 18:13:15 +00003910 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003911 False
Facundo Batista353750c2007-09-13 18:13:15 +00003912 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003913 False
Facundo Batista353750c2007-09-13 18:13:15 +00003914 """
3915 return a.is_normal(context=self)
3916
3917 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003918 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003919
3920 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003921 False
Facundo Batista353750c2007-09-13 18:13:15 +00003922 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003923 True
Facundo Batista353750c2007-09-13 18:13:15 +00003924 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003925 False
Facundo Batista353750c2007-09-13 18:13:15 +00003926 """
3927 return a.is_qnan()
3928
3929 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003930 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003931
3932 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003933 False
Facundo Batista353750c2007-09-13 18:13:15 +00003934 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003935 True
Facundo Batista353750c2007-09-13 18:13:15 +00003936 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003937 True
Facundo Batista353750c2007-09-13 18:13:15 +00003938 """
3939 return a.is_signed()
3940
3941 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003942 """Return True if the operand is a signaling NaN;
3943 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003944
3945 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003946 False
Facundo Batista353750c2007-09-13 18:13:15 +00003947 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003948 False
Facundo Batista353750c2007-09-13 18:13:15 +00003949 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003950 True
Facundo Batista353750c2007-09-13 18:13:15 +00003951 """
3952 return a.is_snan()
3953
3954 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003955 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003956
3957 >>> c = ExtendedContext.copy()
3958 >>> c.Emin = -999
3959 >>> c.Emax = 999
3960 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003961 False
Facundo Batista353750c2007-09-13 18:13:15 +00003962 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003963 True
Facundo Batista353750c2007-09-13 18:13:15 +00003964 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003965 False
Facundo Batista353750c2007-09-13 18:13:15 +00003966 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003967 False
Facundo Batista353750c2007-09-13 18:13:15 +00003968 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003969 False
Facundo Batista353750c2007-09-13 18:13:15 +00003970 """
3971 return a.is_subnormal(context=self)
3972
3973 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003974 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003975
3976 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003977 True
Facundo Batista353750c2007-09-13 18:13:15 +00003978 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003979 False
Facundo Batista353750c2007-09-13 18:13:15 +00003980 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003981 True
Facundo Batista353750c2007-09-13 18:13:15 +00003982 """
3983 return a.is_zero()
3984
3985 def ln(self, a):
3986 """Returns the natural (base e) logarithm of the operand.
3987
3988 >>> c = ExtendedContext.copy()
3989 >>> c.Emin = -999
3990 >>> c.Emax = 999
3991 >>> c.ln(Decimal('0'))
3992 Decimal("-Infinity")
3993 >>> c.ln(Decimal('1.000'))
3994 Decimal("0")
3995 >>> c.ln(Decimal('2.71828183'))
3996 Decimal("1.00000000")
3997 >>> c.ln(Decimal('10'))
3998 Decimal("2.30258509")
3999 >>> c.ln(Decimal('+Infinity'))
4000 Decimal("Infinity")
4001 """
4002 return a.ln(context=self)
4003
4004 def log10(self, a):
4005 """Returns the base 10 logarithm of the operand.
4006
4007 >>> c = ExtendedContext.copy()
4008 >>> c.Emin = -999
4009 >>> c.Emax = 999
4010 >>> c.log10(Decimal('0'))
4011 Decimal("-Infinity")
4012 >>> c.log10(Decimal('0.001'))
4013 Decimal("-3")
4014 >>> c.log10(Decimal('1.000'))
4015 Decimal("0")
4016 >>> c.log10(Decimal('2'))
4017 Decimal("0.301029996")
4018 >>> c.log10(Decimal('10'))
4019 Decimal("1")
4020 >>> c.log10(Decimal('70'))
4021 Decimal("1.84509804")
4022 >>> c.log10(Decimal('+Infinity'))
4023 Decimal("Infinity")
4024 """
4025 return a.log10(context=self)
4026
4027 def logb(self, a):
4028 """ Returns the exponent of the magnitude of the operand's MSD.
4029
4030 The result is the integer which is the exponent of the magnitude
4031 of the most significant digit of the operand (as though the
4032 operand were truncated to a single digit while maintaining the
4033 value of that digit and without limiting the resulting exponent).
4034
4035 >>> ExtendedContext.logb(Decimal('250'))
4036 Decimal("2")
4037 >>> ExtendedContext.logb(Decimal('2.50'))
4038 Decimal("0")
4039 >>> ExtendedContext.logb(Decimal('0.03'))
4040 Decimal("-2")
4041 >>> ExtendedContext.logb(Decimal('0'))
4042 Decimal("-Infinity")
4043 """
4044 return a.logb(context=self)
4045
4046 def logical_and(self, a, b):
4047 """Applies the logical operation 'and' between each operand's digits.
4048
4049 The operands must be both logical numbers.
4050
4051 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4052 Decimal("0")
4053 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4054 Decimal("0")
4055 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4056 Decimal("0")
4057 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4058 Decimal("1")
4059 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4060 Decimal("1000")
4061 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4062 Decimal("10")
4063 """
4064 return a.logical_and(b, context=self)
4065
4066 def logical_invert(self, a):
4067 """Invert all the digits in the operand.
4068
4069 The operand must be a logical number.
4070
4071 >>> ExtendedContext.logical_invert(Decimal('0'))
4072 Decimal("111111111")
4073 >>> ExtendedContext.logical_invert(Decimal('1'))
4074 Decimal("111111110")
4075 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4076 Decimal("0")
4077 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4078 Decimal("10101010")
4079 """
4080 return a.logical_invert(context=self)
4081
4082 def logical_or(self, a, b):
4083 """Applies the logical operation 'or' between each operand's digits.
4084
4085 The operands must be both logical numbers.
4086
4087 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4088 Decimal("0")
4089 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4090 Decimal("1")
4091 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4092 Decimal("1")
4093 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4094 Decimal("1")
4095 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4096 Decimal("1110")
4097 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4098 Decimal("1110")
4099 """
4100 return a.logical_or(b, context=self)
4101
4102 def logical_xor(self, a, b):
4103 """Applies the logical operation 'xor' between each operand's digits.
4104
4105 The operands must be both logical numbers.
4106
4107 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4108 Decimal("0")
4109 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4110 Decimal("1")
4111 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4112 Decimal("1")
4113 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4114 Decimal("0")
4115 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4116 Decimal("110")
4117 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4118 Decimal("1101")
4119 """
4120 return a.logical_xor(b, context=self)
4121
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004122 def max(self, a,b):
4123 """max compares two values numerically and returns the maximum.
4124
4125 If either operand is a NaN then the general rules apply.
4126 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004127 operation. If they are numerically equal then the left-hand operand
4128 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004129 infinity) of the two operands is chosen as the result.
4130
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004131 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004132 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004133 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004134 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004135 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004136 Decimal("1")
4137 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4138 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004139 """
4140 return a.max(b, context=self)
4141
Facundo Batista353750c2007-09-13 18:13:15 +00004142 def max_mag(self, a, b):
4143 """Compares the values numerically with their sign ignored."""
4144 return a.max_mag(b, context=self)
4145
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004146 def min(self, a,b):
4147 """min compares two values numerically and returns the minimum.
4148
4149 If either operand is a NaN then the general rules apply.
4150 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004151 operation. If they are numerically equal then the left-hand operand
4152 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004153 infinity) of the two operands is chosen as the result.
4154
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004155 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004156 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004157 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004158 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004159 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004160 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004161 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4162 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004163 """
4164 return a.min(b, context=self)
4165
Facundo Batista353750c2007-09-13 18:13:15 +00004166 def min_mag(self, a, b):
4167 """Compares the values numerically with their sign ignored."""
4168 return a.min_mag(b, context=self)
4169
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004170 def minus(self, a):
4171 """Minus corresponds to unary prefix minus in Python.
4172
4173 The operation is evaluated using the same rules as subtract; the
4174 operation minus(a) is calculated as subtract('0', a) where the '0'
4175 has the same exponent as the operand.
4176
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004177 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004178 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004179 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004180 Decimal("1.3")
4181 """
4182 return a.__neg__(context=self)
4183
4184 def multiply(self, a, b):
4185 """multiply multiplies two operands.
4186
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004187 If either operand is a special value then the general rules apply.
4188 Otherwise, the operands are multiplied together ('long multiplication'),
4189 resulting in a number which may be as long as the sum of the lengths
4190 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004191
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004192 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004193 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004194 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004195 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004196 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004197 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004198 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004199 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004200 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004201 Decimal("4.28135971E+11")
4202 """
4203 return a.__mul__(b, context=self)
4204
Facundo Batista353750c2007-09-13 18:13:15 +00004205 def next_minus(self, a):
4206 """Returns the largest representable number smaller than a.
4207
4208 >>> c = ExtendedContext.copy()
4209 >>> c.Emin = -999
4210 >>> c.Emax = 999
4211 >>> ExtendedContext.next_minus(Decimal('1'))
4212 Decimal("0.999999999")
4213 >>> c.next_minus(Decimal('1E-1007'))
4214 Decimal("0E-1007")
4215 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4216 Decimal("-1.00000004")
4217 >>> c.next_minus(Decimal('Infinity'))
4218 Decimal("9.99999999E+999")
4219 """
4220 return a.next_minus(context=self)
4221
4222 def next_plus(self, a):
4223 """Returns the smallest representable number larger than a.
4224
4225 >>> c = ExtendedContext.copy()
4226 >>> c.Emin = -999
4227 >>> c.Emax = 999
4228 >>> ExtendedContext.next_plus(Decimal('1'))
4229 Decimal("1.00000001")
4230 >>> c.next_plus(Decimal('-1E-1007'))
4231 Decimal("-0E-1007")
4232 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4233 Decimal("-1.00000002")
4234 >>> c.next_plus(Decimal('-Infinity'))
4235 Decimal("-9.99999999E+999")
4236 """
4237 return a.next_plus(context=self)
4238
4239 def next_toward(self, a, b):
4240 """Returns the number closest to a, in direction towards b.
4241
4242 The result is the closest representable number from the first
4243 operand (but not the first operand) that is in the direction
4244 towards the second operand, unless the operands have the same
4245 value.
4246
4247 >>> c = ExtendedContext.copy()
4248 >>> c.Emin = -999
4249 >>> c.Emax = 999
4250 >>> c.next_toward(Decimal('1'), Decimal('2'))
4251 Decimal("1.00000001")
4252 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4253 Decimal("-0E-1007")
4254 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4255 Decimal("-1.00000002")
4256 >>> c.next_toward(Decimal('1'), Decimal('0'))
4257 Decimal("0.999999999")
4258 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4259 Decimal("0E-1007")
4260 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4261 Decimal("-1.00000004")
4262 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4263 Decimal("-0.00")
4264 """
4265 return a.next_toward(b, context=self)
4266
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004267 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004268 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004269
4270 Essentially a plus operation with all trailing zeros removed from the
4271 result.
4272
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004273 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004274 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004275 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004276 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004277 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004278 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004279 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004280 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004281 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004282 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004283 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004284 Decimal("0")
4285 """
4286 return a.normalize(context=self)
4287
Facundo Batista353750c2007-09-13 18:13:15 +00004288 def number_class(self, a):
4289 """Returns an indication of the class of the operand.
4290
4291 The class is one of the following strings:
4292 -sNaN
4293 -NaN
4294 -Infinity
4295 -Normal
4296 -Subnormal
4297 -Zero
4298 +Zero
4299 +Subnormal
4300 +Normal
4301 +Infinity
4302
4303 >>> c = Context(ExtendedContext)
4304 >>> c.Emin = -999
4305 >>> c.Emax = 999
4306 >>> c.number_class(Decimal('Infinity'))
4307 '+Infinity'
4308 >>> c.number_class(Decimal('1E-10'))
4309 '+Normal'
4310 >>> c.number_class(Decimal('2.50'))
4311 '+Normal'
4312 >>> c.number_class(Decimal('0.1E-999'))
4313 '+Subnormal'
4314 >>> c.number_class(Decimal('0'))
4315 '+Zero'
4316 >>> c.number_class(Decimal('-0'))
4317 '-Zero'
4318 >>> c.number_class(Decimal('-0.1E-999'))
4319 '-Subnormal'
4320 >>> c.number_class(Decimal('-1E-10'))
4321 '-Normal'
4322 >>> c.number_class(Decimal('-2.50'))
4323 '-Normal'
4324 >>> c.number_class(Decimal('-Infinity'))
4325 '-Infinity'
4326 >>> c.number_class(Decimal('NaN'))
4327 'NaN'
4328 >>> c.number_class(Decimal('-NaN'))
4329 'NaN'
4330 >>> c.number_class(Decimal('sNaN'))
4331 'sNaN'
4332 """
4333 return a.number_class(context=self)
4334
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004335 def plus(self, a):
4336 """Plus corresponds to unary prefix plus in Python.
4337
4338 The operation is evaluated using the same rules as add; the
4339 operation plus(a) is calculated as add('0', a) where the '0'
4340 has the same exponent as the operand.
4341
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004342 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004343 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004344 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004345 Decimal("-1.3")
4346 """
4347 return a.__pos__(context=self)
4348
4349 def power(self, a, b, modulo=None):
4350 """Raises a to the power of b, to modulo if given.
4351
Facundo Batista353750c2007-09-13 18:13:15 +00004352 With two arguments, compute a**b. If a is negative then b
4353 must be integral. The result will be inexact unless b is
4354 integral and the result is finite and can be expressed exactly
4355 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004356
Facundo Batista353750c2007-09-13 18:13:15 +00004357 With three arguments, compute (a**b) % modulo. For the
4358 three argument form, the following restrictions on the
4359 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004360
Facundo Batista353750c2007-09-13 18:13:15 +00004361 - all three arguments must be integral
4362 - b must be nonnegative
4363 - at least one of a or b must be nonzero
4364 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004365
Facundo Batista353750c2007-09-13 18:13:15 +00004366 The result of pow(a, b, modulo) is identical to the result
4367 that would be obtained by computing (a**b) % modulo with
4368 unbounded precision, but is computed more efficiently. It is
4369 always exact.
4370
4371 >>> c = ExtendedContext.copy()
4372 >>> c.Emin = -999
4373 >>> c.Emax = 999
4374 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004375 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004376 >>> c.power(Decimal('-2'), Decimal('3'))
4377 Decimal("-8")
4378 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004379 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004380 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004381 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004382 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4383 Decimal("2.00000000")
4384 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004385 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004386 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004387 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004388 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004389 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004390 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004391 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004392 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004393 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004394 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004395 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004396 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004397 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004398 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004399 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004400
4401 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4402 Decimal("11")
4403 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4404 Decimal("-11")
4405 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4406 Decimal("1")
4407 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4408 Decimal("11")
4409 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4410 Decimal("11729830")
4411 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4412 Decimal("-0")
4413 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4414 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004415 """
4416 return a.__pow__(b, modulo, context=self)
4417
4418 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004419 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004420
4421 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004422 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004423 exponent is being increased), multiplied by a positive power of ten (if
4424 the exponent is being decreased), or is unchanged (if the exponent is
4425 already equal to that of the right-hand operand).
4426
4427 Unlike other operations, if the length of the coefficient after the
4428 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004429 operation condition is raised. This guarantees that, unless there is
4430 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004431 equal to that of the right-hand operand.
4432
4433 Also unlike other operations, quantize will never raise Underflow, even
4434 if the result is subnormal and inexact.
4435
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004436 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004437 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004438 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004439 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004440 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004441 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004442 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004443 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004444 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004445 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004446 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004447 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004448 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004449 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004450 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004451 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004452 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004453 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004454 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004455 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004456 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004457 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004458 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004459 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004460 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004461 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004462 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004463 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004464 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004465 Decimal("2E+2")
4466 """
4467 return a.quantize(b, context=self)
4468
Facundo Batista353750c2007-09-13 18:13:15 +00004469 def radix(self):
4470 """Just returns 10, as this is Decimal, :)
4471
4472 >>> ExtendedContext.radix()
4473 Decimal("10")
4474 """
4475 return Decimal(10)
4476
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004477 def remainder(self, a, b):
4478 """Returns the remainder from integer division.
4479
4480 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004481 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004482 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004483 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004484
4485 This operation will fail under the same conditions as integer division
4486 (that is, if integer division on the same two operands would fail, the
4487 remainder cannot be calculated).
4488
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004489 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004490 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004491 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004492 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004493 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004494 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004495 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004496 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004497 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004498 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004499 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004500 Decimal("1.0")
4501 """
4502 return a.__mod__(b, context=self)
4503
4504 def remainder_near(self, a, b):
4505 """Returns to be "a - b * n", where n is the integer nearest the exact
4506 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004507 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004508 sign of a.
4509
4510 This operation will fail under the same conditions as integer division
4511 (that is, if integer division on the same two operands would fail, the
4512 remainder cannot be calculated).
4513
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004514 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004515 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004516 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004517 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004518 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004519 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004520 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004521 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004522 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004523 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004524 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004525 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004526 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004527 Decimal("-0.3")
4528 """
4529 return a.remainder_near(b, context=self)
4530
Facundo Batista353750c2007-09-13 18:13:15 +00004531 def rotate(self, a, b):
4532 """Returns a rotated copy of a, b times.
4533
4534 The coefficient of the result is a rotated copy of the digits in
4535 the coefficient of the first operand. The number of places of
4536 rotation is taken from the absolute value of the second operand,
4537 with the rotation being to the left if the second operand is
4538 positive or to the right otherwise.
4539
4540 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4541 Decimal("400000003")
4542 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4543 Decimal("12")
4544 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4545 Decimal("891234567")
4546 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4547 Decimal("123456789")
4548 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4549 Decimal("345678912")
4550 """
4551 return a.rotate(b, context=self)
4552
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004553 def same_quantum(self, a, b):
4554 """Returns True if the two operands have the same exponent.
4555
4556 The result is never affected by either the sign or the coefficient of
4557 either operand.
4558
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004559 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004560 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004561 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004562 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004563 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004564 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004565 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004566 True
4567 """
4568 return a.same_quantum(b)
4569
Facundo Batista353750c2007-09-13 18:13:15 +00004570 def scaleb (self, a, b):
4571 """Returns the first operand after adding the second value its exp.
4572
4573 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4574 Decimal("0.0750")
4575 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4576 Decimal("7.50")
4577 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4578 Decimal("7.50E+3")
4579 """
4580 return a.scaleb (b, context=self)
4581
4582 def shift(self, a, b):
4583 """Returns a shifted copy of a, b times.
4584
4585 The coefficient of the result is a shifted copy of the digits
4586 in the coefficient of the first operand. The number of places
4587 to shift is taken from the absolute value of the second operand,
4588 with the shift being to the left if the second operand is
4589 positive or to the right otherwise. Digits shifted into the
4590 coefficient are zeros.
4591
4592 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4593 Decimal("400000000")
4594 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4595 Decimal("0")
4596 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4597 Decimal("1234567")
4598 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4599 Decimal("123456789")
4600 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4601 Decimal("345678900")
4602 """
4603 return a.shift(b, context=self)
4604
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004605 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004606 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004607
4608 If the result must be inexact, it is rounded using the round-half-even
4609 algorithm.
4610
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004611 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004612 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004613 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004614 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004615 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004616 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004617 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004618 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004619 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004620 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004621 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004622 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004623 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004624 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004625 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004626 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004627 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004628 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004629 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004630 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004631 """
4632 return a.sqrt(context=self)
4633
4634 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004635 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004636
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004637 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004638 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004639 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004640 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004641 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004642 Decimal("-0.77")
4643 """
4644 return a.__sub__(b, context=self)
4645
4646 def to_eng_string(self, a):
4647 """Converts a number to a string, using scientific notation.
4648
4649 The operation is not affected by the context.
4650 """
4651 return a.to_eng_string(context=self)
4652
4653 def to_sci_string(self, a):
4654 """Converts a number to a string, using scientific notation.
4655
4656 The operation is not affected by the context.
4657 """
4658 return a.__str__(context=self)
4659
Facundo Batista353750c2007-09-13 18:13:15 +00004660 def to_integral_exact(self, a):
4661 """Rounds to an integer.
4662
4663 When the operand has a negative exponent, the result is the same
4664 as using the quantize() operation using the given operand as the
4665 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4666 of the operand as the precision setting; Inexact and Rounded flags
4667 are allowed in this operation. The rounding mode is taken from the
4668 context.
4669
4670 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4671 Decimal("2")
4672 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4673 Decimal("100")
4674 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4675 Decimal("100")
4676 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4677 Decimal("102")
4678 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4679 Decimal("-102")
4680 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4681 Decimal("1.0E+6")
4682 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4683 Decimal("7.89E+77")
4684 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4685 Decimal("-Infinity")
4686 """
4687 return a.to_integral_exact(context=self)
4688
4689 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004690 """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, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004696 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004697
Facundo Batista353750c2007-09-13 18:13:15 +00004698 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004699 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004700 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004701 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004702 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004703 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004704 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004705 Decimal("102")
Facundo Batista353750c2007-09-13 18:13:15 +00004706 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004707 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004708 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004709 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004710 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004711 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004712 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004713 Decimal("-Infinity")
4714 """
Facundo Batista353750c2007-09-13 18:13:15 +00004715 return a.to_integral_value(context=self)
4716
4717 # the method name changed, but we provide also the old one, for compatibility
4718 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004719
4720class _WorkRep(object):
4721 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004722 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004723 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004724 # exp: None, int, or string
4725
4726 def __init__(self, value=None):
4727 if value is None:
4728 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004729 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004730 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004731 elif isinstance(value, Decimal):
4732 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004733 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004734 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004735 else:
4736 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004737 self.sign = value[0]
4738 self.int = value[1]
4739 self.exp = value[2]
4740
4741 def __repr__(self):
4742 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4743
4744 __str__ = __repr__
4745
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004746
4747
4748def _normalize(op1, op2, shouldround = 0, prec = 0):
4749 """Normalizes op1, op2 to have the same exp and length of coefficient.
4750
4751 Done during addition.
4752 """
Facundo Batista353750c2007-09-13 18:13:15 +00004753 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004754 tmp = op2
4755 other = op1
4756 else:
4757 tmp = op1
4758 other = op2
4759
Facundo Batista353750c2007-09-13 18:13:15 +00004760 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4761 # Then adding 10**exp to tmp has the same effect (after rounding)
4762 # as adding any positive quantity smaller than 10**exp; similarly
4763 # for subtraction. So if other is smaller than 10**exp we replace
4764 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4765 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004766 tmp_len = len(str(tmp.int))
4767 other_len = len(str(other.int))
Facundo Batista353750c2007-09-13 18:13:15 +00004768 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4769 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004770 other.int = 1
Facundo Batista353750c2007-09-13 18:13:15 +00004771 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004772
Facundo Batista353750c2007-09-13 18:13:15 +00004773 tmp.int *= 10 ** (tmp.exp - other.exp)
4774 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004775 return op1, op2
4776
Facundo Batista353750c2007-09-13 18:13:15 +00004777##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4778
4779# This function from Tim Peters was taken from here:
4780# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4781# The correction being in the function definition is for speed, and
4782# the whole function is not resolved with math.log because of avoiding
4783# the use of floats.
4784def _nbits(n, correction = {
4785 '0': 4, '1': 3, '2': 2, '3': 2,
4786 '4': 1, '5': 1, '6': 1, '7': 1,
4787 '8': 0, '9': 0, 'a': 0, 'b': 0,
4788 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4789 """Number of bits in binary representation of the positive integer n,
4790 or 0 if n == 0.
4791 """
4792 if n < 0:
4793 raise ValueError("The argument to _nbits should be nonnegative.")
4794 hex_n = "%x" % n
4795 return 4*len(hex_n) - correction[hex_n[0]]
4796
4797def _sqrt_nearest(n, a):
4798 """Closest integer to the square root of the positive integer n. a is
4799 an initial approximation to the square root. Any positive integer
4800 will do for a, but the closer a is to the square root of n the
4801 faster convergence will be.
4802
4803 """
4804 if n <= 0 or a <= 0:
4805 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4806
4807 b=0
4808 while a != b:
4809 b, a = a, a--n//a>>1
4810 return a
4811
4812def _rshift_nearest(x, shift):
4813 """Given an integer x and a nonnegative integer shift, return closest
4814 integer to x / 2**shift; use round-to-even in case of a tie.
4815
4816 """
4817 b, q = 1L << shift, x >> shift
4818 return q + (2*(x & (b-1)) + (q&1) > b)
4819
4820def _div_nearest(a, b):
4821 """Closest integer to a/b, a and b positive integers; rounds to even
4822 in the case of a tie.
4823
4824 """
4825 q, r = divmod(a, b)
4826 return q + (2*r + (q&1) > b)
4827
4828def _ilog(x, M, L = 8):
4829 """Integer approximation to M*log(x/M), with absolute error boundable
4830 in terms only of x/M.
4831
4832 Given positive integers x and M, return an integer approximation to
4833 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4834 between the approximation and the exact result is at most 22. For
4835 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4836 both cases these are upper bounds on the error; it will usually be
4837 much smaller."""
4838
4839 # The basic algorithm is the following: let log1p be the function
4840 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4841 # the reduction
4842 #
4843 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4844 #
4845 # repeatedly until the argument to log1p is small (< 2**-L in
4846 # absolute value). For small y we can use the Taylor series
4847 # expansion
4848 #
4849 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4850 #
4851 # truncating at T such that y**T is small enough. The whole
4852 # computation is carried out in a form of fixed-point arithmetic,
4853 # with a real number z being represented by an integer
4854 # approximation to z*M. To avoid loss of precision, the y below
4855 # is actually an integer approximation to 2**R*y*M, where R is the
4856 # number of reductions performed so far.
4857
4858 y = x-M
4859 # argument reduction; R = number of reductions performed
4860 R = 0
4861 while (R <= L and long(abs(y)) << L-R >= M or
4862 R > L and abs(y) >> R-L >= M):
4863 y = _div_nearest(long(M*y) << 1,
4864 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4865 R += 1
4866
4867 # Taylor series with T terms
4868 T = -int(-10*len(str(M))//(3*L))
4869 yshift = _rshift_nearest(y, R)
4870 w = _div_nearest(M, T)
4871 for k in xrange(T-1, 0, -1):
4872 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4873
4874 return _div_nearest(w*y, M)
4875
4876def _dlog10(c, e, p):
4877 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4878 approximation to 10**p * log10(c*10**e), with an absolute error of
4879 at most 1. Assumes that c*10**e is not exactly 1."""
4880
4881 # increase precision by 2; compensate for this by dividing
4882 # final result by 100
4883 p += 2
4884
4885 # write c*10**e as d*10**f with either:
4886 # f >= 0 and 1 <= d <= 10, or
4887 # f <= 0 and 0.1 <= d <= 1.
4888 # Thus for c*10**e close to 1, f = 0
4889 l = len(str(c))
4890 f = e+l - (e+l >= 1)
4891
4892 if p > 0:
4893 M = 10**p
4894 k = e+p-f
4895 if k >= 0:
4896 c *= 10**k
4897 else:
4898 c = _div_nearest(c, 10**-k)
4899
4900 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004901 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004902 log_d = _div_nearest(log_d*M, log_10)
4903 log_tenpower = f*M # exact
4904 else:
4905 log_d = 0 # error < 2.31
4906 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4907
4908 return _div_nearest(log_tenpower+log_d, 100)
4909
4910def _dlog(c, e, p):
4911 """Given integers c, e and p with c > 0, compute an integer
4912 approximation to 10**p * log(c*10**e), with an absolute error of
4913 at most 1. Assumes that c*10**e is not exactly 1."""
4914
4915 # Increase precision by 2. The precision increase is compensated
4916 # for at the end with a division by 100.
4917 p += 2
4918
4919 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4920 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4921 # as 10**p * log(d) + 10**p*f * log(10).
4922 l = len(str(c))
4923 f = e+l - (e+l >= 1)
4924
4925 # compute approximation to 10**p*log(d), with error < 27
4926 if p > 0:
4927 k = e+p-f
4928 if k >= 0:
4929 c *= 10**k
4930 else:
4931 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4932
4933 # _ilog magnifies existing error in c by a factor of at most 10
4934 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4935 else:
4936 # p <= 0: just approximate the whole thing by 0; error < 2.31
4937 log_d = 0
4938
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004939 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00004940 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004941 extra = len(str(abs(f)))-1
4942 if p + extra >= 0:
4943 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4944 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4945 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00004946 else:
4947 f_log_ten = 0
4948 else:
4949 f_log_ten = 0
4950
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004951 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004952 return _div_nearest(f_log_ten + log_d, 100)
4953
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004954class _Log10Memoize(object):
4955 """Class to compute, store, and allow retrieval of, digits of the
4956 constant log(10) = 2.302585.... This constant is needed by
4957 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4958 def __init__(self):
4959 self.digits = "23025850929940456840179914546843642076011014886"
4960
4961 def getdigits(self, p):
4962 """Given an integer p >= 0, return floor(10**p)*log(10).
4963
4964 For example, self.getdigits(3) returns 2302.
4965 """
4966 # digits are stored as a string, for quick conversion to
4967 # integer in the case that we've already computed enough
4968 # digits; the stored digits should always be correct
4969 # (truncated, not rounded to nearest).
4970 if p < 0:
4971 raise ValueError("p should be nonnegative")
4972
4973 if p >= len(self.digits):
4974 # compute p+3, p+6, p+9, ... digits; continue until at
4975 # least one of the extra digits is nonzero
4976 extra = 3
4977 while True:
4978 # compute p+extra digits, correct to within 1ulp
4979 M = 10**(p+extra+2)
4980 digits = str(_div_nearest(_ilog(10*M, M), 100))
4981 if digits[-extra:] != '0'*extra:
4982 break
4983 extra += 3
4984 # keep all reliable digits so far; remove trailing zeros
4985 # and next nonzero digit
4986 self.digits = digits.rstrip('0')[:-1]
4987 return int(self.digits[:p+1])
4988
4989_log10_digits = _Log10Memoize().getdigits
4990
Facundo Batista353750c2007-09-13 18:13:15 +00004991def _iexp(x, M, L=8):
4992 """Given integers x and M, M > 0, such that x/M is small in absolute
4993 value, compute an integer approximation to M*exp(x/M). For 0 <=
4994 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4995 is usually much smaller)."""
4996
4997 # Algorithm: to compute exp(z) for a real number z, first divide z
4998 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4999 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5000 # series
5001 #
5002 # expm1(x) = x + x**2/2! + x**3/3! + ...
5003 #
5004 # Now use the identity
5005 #
5006 # expm1(2x) = expm1(x)*(expm1(x)+2)
5007 #
5008 # R times to compute the sequence expm1(z/2**R),
5009 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5010
5011 # Find R such that x/2**R/M <= 2**-L
5012 R = _nbits((long(x)<<L)//M)
5013
5014 # Taylor series. (2**L)**T > M
5015 T = -int(-10*len(str(M))//(3*L))
5016 y = _div_nearest(x, T)
5017 Mshift = long(M)<<R
5018 for i in xrange(T-1, 0, -1):
5019 y = _div_nearest(x*(Mshift + y), Mshift * i)
5020
5021 # Expansion
5022 for k in xrange(R-1, -1, -1):
5023 Mshift = long(M)<<(k+2)
5024 y = _div_nearest(y*(y+Mshift), Mshift)
5025
5026 return M+y
5027
5028def _dexp(c, e, p):
5029 """Compute an approximation to exp(c*10**e), with p decimal places of
5030 precision.
5031
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005032 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005033
5034 10**(p-1) <= d <= 10**p, and
5035 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5036
5037 In other words, d*10**f is an approximation to exp(c*10**e) with p
5038 digits of precision, and with an error in d of at most 1. This is
5039 almost, but not quite, the same as the error being < 1ulp: when d
5040 = 10**(p-1) the error could be up to 10 ulp."""
5041
5042 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5043 p += 2
5044
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005045 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005046 extra = max(0, e + len(str(c)) - 1)
5047 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005048
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005049 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005050 # rounding down
5051 shift = e+q
5052 if shift >= 0:
5053 cshift = c*10**shift
5054 else:
5055 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005056 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005057
5058 # reduce remainder back to original precision
5059 rem = _div_nearest(rem, 10**extra)
5060
5061 # error in result of _iexp < 120; error after division < 0.62
5062 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5063
5064def _dpower(xc, xe, yc, ye, p):
5065 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5066 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5067
5068 10**(p-1) <= c <= 10**p, and
5069 (c-1)*10**e < x**y < (c+1)*10**e
5070
5071 in other words, c*10**e is an approximation to x**y with p digits
5072 of precision, and with an error in c of at most 1. (This is
5073 almost, but not quite, the same as the error being < 1ulp: when c
5074 == 10**(p-1) we can only guarantee error < 10ulp.)
5075
5076 We assume that: x is positive and not equal to 1, and y is nonzero.
5077 """
5078
5079 # Find b such that 10**(b-1) <= |y| <= 10**b
5080 b = len(str(abs(yc))) + ye
5081
5082 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5083 lxc = _dlog(xc, xe, p+b+1)
5084
5085 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5086 shift = ye-b
5087 if shift >= 0:
5088 pc = lxc*yc*10**shift
5089 else:
5090 pc = _div_nearest(lxc*yc, 10**-shift)
5091
5092 if pc == 0:
5093 # we prefer a result that isn't exactly 1; this makes it
5094 # easier to compute a correctly rounded result in __pow__
5095 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5096 coeff, exp = 10**(p-1)+1, 1-p
5097 else:
5098 coeff, exp = 10**p-1, -p
5099 else:
5100 coeff, exp = _dexp(pc, -(p+1), p+1)
5101 coeff = _div_nearest(coeff, 10)
5102 exp += 1
5103
5104 return coeff, exp
5105
5106def _log10_lb(c, correction = {
5107 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5108 '6': 23, '7': 16, '8': 10, '9': 5}):
5109 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5110 if c <= 0:
5111 raise ValueError("The argument to _log10_lb should be nonnegative.")
5112 str_c = str(c)
5113 return 100*len(str_c) - correction[str_c[0]]
5114
Facundo Batista59c58842007-04-10 12:58:45 +00005115##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005116
Facundo Batista353750c2007-09-13 18:13:15 +00005117def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005118 """Convert other to Decimal.
5119
5120 Verifies that it's ok to use in an implicit construction.
5121 """
5122 if isinstance(other, Decimal):
5123 return other
5124 if isinstance(other, (int, long)):
5125 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005126 if raiseit:
5127 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005128 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005129
Facundo Batista59c58842007-04-10 12:58:45 +00005130##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005131
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005132# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005133# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005134
5135DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005136 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005137 traps=[DivisionByZero, Overflow, InvalidOperation],
5138 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005139 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005140 Emax=999999999,
5141 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005142 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005143)
5144
5145# Pre-made alternate contexts offered by the specification
5146# Don't change these; the user should be able to select these
5147# contexts and be able to reproduce results from other implementations
5148# of the spec.
5149
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005150BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005151 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005152 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5153 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005154)
5155
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005156ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005157 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005158 traps=[],
5159 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005160)
5161
5162
Facundo Batista72bc54f2007-11-23 17:59:00 +00005163##### crud for parsing strings #############################################
5164import re
5165
5166# Regular expression used for parsing numeric strings. Additional
5167# comments:
5168#
5169# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5170# whitespace. But note that the specification disallows whitespace in
5171# a numeric string.
5172#
5173# 2. For finite numbers (not infinities and NaNs) the body of the
5174# number between the optional sign and the optional exponent must have
5175# at least one decimal digit, possibly after the decimal point. The
5176# lookahead expression '(?=\d|\.\d)' checks this.
5177#
5178# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5179# other meaning for \d than the numbers [0-9].
5180
5181import re
5182_parser = re.compile(r""" # A numeric string consists of:
5183# \s*
5184 (?P<sign>[-+])? # an optional sign, followed by either...
5185 (
5186 (?=\d|\.\d) # ...a number (with at least one digit)
5187 (?P<int>\d*) # consisting of a (possibly empty) integer part
5188 (\.(?P<frac>\d*))? # followed by an optional fractional part
5189 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5190 |
5191 Inf(inity)? # ...an infinity, or...
5192 |
5193 (?P<signal>s)? # ...an (optionally signaling)
5194 NaN # NaN
5195 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5196 )
5197# \s*
5198 $
5199""", re.VERBOSE | re.IGNORECASE).match
5200
5201del re
5202
5203
Facundo Batista59c58842007-04-10 12:58:45 +00005204##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005205
Facundo Batista59c58842007-04-10 12:58:45 +00005206# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005207Inf = Decimal('Inf')
5208negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005209NaN = Decimal('NaN')
5210Dec_0 = Decimal(0)
5211Dec_p1 = Decimal(1)
5212Dec_n1 = Decimal(-1)
5213Dec_p2 = Decimal(2)
5214Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005215
Facundo Batista59c58842007-04-10 12:58:45 +00005216# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005217Infsign = (Inf, negInf)
5218
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005219
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005220
5221if __name__ == '__main__':
5222 import doctest, sys
5223 doctest.testmod(sys.modules[__name__])