blob: 6baa838e9ea03527088f0aade9842fecde5c3d4b [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
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000840 if self._is_special:
841 if self._isnan():
842 minus = '-'*self._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +0000843 if self._int == '0':
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000844 info = ''
845 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000846 info = self._int
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000847 if self._isnan() == 2:
848 return minus + 'sNaN' + info
849 return minus + 'NaN' + info
850 if self._isinfinity():
851 minus = '-'*self._sign
852 return minus + 'Infinity'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000853
854 if context is None:
855 context = getcontext()
856
Facundo Batista72bc54f2007-11-23 17:59:00 +0000857 tmp = list(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000858 numdigits = len(self._int)
859 leftdigits = self._exp + numdigits
Facundo Batista59c58842007-04-10 12:58:45 +0000860 if eng and not self: # self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
861 if self._exp < 0 and self._exp >= -6: # short, no need for e/E
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000862 s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
863 return s
Facundo Batista59c58842007-04-10 12:58:45 +0000864 # exp is closest mult. of 3 >= self._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000865 exp = ((self._exp - 1)// 3 + 1) * 3
866 if exp != self._exp:
867 s = '0.'+'0'*(exp - self._exp)
868 else:
869 s = '0'
870 if exp != 0:
871 if context.capitals:
872 s += 'E'
873 else:
874 s += 'e'
875 if exp > 0:
Facundo Batista59c58842007-04-10 12:58:45 +0000876 s += '+' # 0.0e+3, not 0.0e3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000877 s += str(exp)
878 s = '-'*self._sign + s
879 return s
880 if eng:
881 dotplace = (leftdigits-1)%3+1
882 adjexp = leftdigits -1 - (leftdigits-1)%3
883 else:
884 adjexp = leftdigits-1
885 dotplace = 1
886 if self._exp == 0:
887 pass
888 elif self._exp < 0 and adjexp >= 0:
889 tmp.insert(leftdigits, '.')
890 elif self._exp < 0 and adjexp >= -6:
891 tmp[0:0] = ['0'] * int(-leftdigits)
892 tmp.insert(0, '0.')
893 else:
894 if numdigits > dotplace:
895 tmp.insert(dotplace, '.')
896 elif numdigits < dotplace:
897 tmp.extend(['0']*(dotplace-numdigits))
898 if adjexp:
899 if not context.capitals:
900 tmp.append('e')
901 else:
902 tmp.append('E')
903 if adjexp > 0:
904 tmp.append('+')
905 tmp.append(str(adjexp))
906 if eng:
907 while tmp[0:1] == ['0']:
908 tmp[0:1] = []
909 if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
910 tmp[0:0] = ['0']
911 if self._sign:
912 tmp.insert(0, '-')
913
914 return ''.join(tmp)
915
916 def to_eng_string(self, context=None):
917 """Convert to engineering-type string.
918
919 Engineering notation has an exponent which is a multiple of 3, so there
920 are up to 3 digits left of the decimal place.
921
922 Same rules for when in exponential and when as a value as in __str__.
923 """
Facundo Batista353750c2007-09-13 18:13:15 +0000924 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000925
926 def __neg__(self, context=None):
927 """Returns a copy with the sign switched.
928
929 Rounds, if it has reason.
930 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000931 if self._is_special:
932 ans = self._check_nans(context=context)
933 if ans:
934 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000935
936 if not self:
937 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +0000938 ans = self.copy_sign(Dec_0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000939 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000940 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000941
942 if context is None:
943 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000944 if context._rounding_decision == ALWAYS_ROUND:
Facundo Batista353750c2007-09-13 18:13:15 +0000945 return ans._fix(context)
946 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000947
948 def __pos__(self, context=None):
949 """Returns a copy, unless it is a sNaN.
950
951 Rounds the number (if more then precision digits)
952 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000953 if self._is_special:
954 ans = self._check_nans(context=context)
955 if ans:
956 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000957
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000958 if not self:
959 # + (-0) = 0
Facundo Batista353750c2007-09-13 18:13:15 +0000960 ans = self.copy_sign(Dec_0)
961 else:
962 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000963
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000964 if context is None:
965 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000966 if context._rounding_decision == ALWAYS_ROUND:
Facundo Batista353750c2007-09-13 18:13:15 +0000967 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000968 return ans
969
970 def __abs__(self, round=1, context=None):
971 """Returns the absolute value of self.
972
973 If the second argument is 0, do not round.
974 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000975 if self._is_special:
976 ans = self._check_nans(context=context)
977 if ans:
978 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000979
980 if not round:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000981 if context is None:
982 context = getcontext()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000983 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000984 context._set_rounding_decision(NEVER_ROUND)
985
986 if self._sign:
987 ans = self.__neg__(context=context)
988 else:
989 ans = self.__pos__(context=context)
990
991 return ans
992
993 def __add__(self, other, context=None):
994 """Returns self + other.
995
996 -INF + INF (or the reverse) cause InvalidOperation errors.
997 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000998 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000999 if other is NotImplemented:
1000 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001001
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001002 if context is None:
1003 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001004
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001005 if self._is_special or other._is_special:
1006 ans = self._check_nans(other, context)
1007 if ans:
1008 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001010 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001011 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001012 if self._sign != other._sign and other._isinfinity():
1013 return context._raise_error(InvalidOperation, '-INF + INF')
1014 return Decimal(self)
1015 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001016 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001017
1018 shouldround = context._rounding_decision == ALWAYS_ROUND
1019
1020 exp = min(self._exp, other._exp)
1021 negativezero = 0
1022 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +00001023 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001024 negativezero = 1
1025
1026 if not self and not other:
1027 sign = min(self._sign, other._sign)
1028 if negativezero:
1029 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001030 ans = _dec_from_triple(sign, '0', exp)
Facundo Batista353750c2007-09-13 18:13:15 +00001031 if shouldround:
1032 ans = ans._fix(context)
1033 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001034 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001035 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001036 ans = other._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001037 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001038 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001039 return ans
1040 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001041 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001042 ans = self._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001043 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001044 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001045 return ans
1046
1047 op1 = _WorkRep(self)
1048 op2 = _WorkRep(other)
1049 op1, op2 = _normalize(op1, op2, shouldround, context.prec)
1050
1051 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001052 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001053 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001054 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001055 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batista353750c2007-09-13 18:13:15 +00001056 if shouldround:
1057 ans = ans._fix(context)
1058 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001059 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001060 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001061 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001062 if op1.sign == 1:
1063 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001064 op1.sign, op2.sign = op2.sign, op1.sign
1065 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001066 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001067 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001068 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001069 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001070 op1.sign, op2.sign = (0, 0)
1071 else:
1072 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001073 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001074
Raymond Hettinger17931de2004-10-27 06:21:46 +00001075 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001076 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001077 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001078 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001079
1080 result.exp = op1.exp
1081 ans = Decimal(result)
1082 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001083 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001084 return ans
1085
1086 __radd__ = __add__
1087
1088 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001089 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001090 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001091 if other is NotImplemented:
1092 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001093
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001094 if self._is_special or other._is_special:
1095 ans = self._check_nans(other, context=context)
1096 if ans:
1097 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001098
Facundo Batista353750c2007-09-13 18:13:15 +00001099 # self - other is computed as self + other.copy_negate()
1100 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001101
1102 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001103 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001104 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001105 if other is NotImplemented:
1106 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001107
Facundo Batista353750c2007-09-13 18:13:15 +00001108 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001109
Facundo Batista353750c2007-09-13 18:13:15 +00001110 def _increment(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001111 """Special case of add, adding 1eExponent
1112
1113 Since it is common, (rounding, for example) this adds
1114 (sign)*one E self._exp to the number more efficiently than add.
1115
Facundo Batista353750c2007-09-13 18:13:15 +00001116 Assumes that self is nonspecial.
1117
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001118 For example:
1119 Decimal('5.624e10')._increment() == Decimal('5.625e10')
1120 """
Facundo Batista72bc54f2007-11-23 17:59:00 +00001121 L = map(int, self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001122 L[-1] += 1
1123 spot = len(L)-1
1124 while L[spot] == 10:
1125 L[spot] = 0
1126 if spot == 0:
1127 L[0:0] = [1]
1128 break
1129 L[spot-1] += 1
1130 spot -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001131 return _dec_from_triple(self._sign, "".join(map(str, L)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001132
1133 def __mul__(self, other, context=None):
1134 """Return self * other.
1135
1136 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1137 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001138 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001139 if other is NotImplemented:
1140 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001141
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001142 if context is None:
1143 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001144
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001145 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001146
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001147 if self._is_special or other._is_special:
1148 ans = self._check_nans(other, context)
1149 if ans:
1150 return ans
1151
1152 if self._isinfinity():
1153 if not other:
1154 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1155 return Infsign[resultsign]
1156
1157 if other._isinfinity():
1158 if not self:
1159 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1160 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001161
1162 resultexp = self._exp + other._exp
1163 shouldround = context._rounding_decision == ALWAYS_ROUND
1164
1165 # Special case for multiplying by zero
1166 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001167 ans = _dec_from_triple(resultsign, '0', resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001168 if shouldround:
Facundo Batista59c58842007-04-10 12:58:45 +00001169 # Fixing in case the exponent is out of bounds
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001170 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001171 return ans
1172
1173 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001174 if self._int == '1':
1175 ans = _dec_from_triple(resultsign, other._int, resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001176 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001177 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001178 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001179 if other._int == '1':
1180 ans = _dec_from_triple(resultsign, self._int, resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001181 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001182 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001183 return ans
1184
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001185 op1 = _WorkRep(self)
1186 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001187
Facundo Batista72bc54f2007-11-23 17:59:00 +00001188 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001189 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001190 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001191
1192 return ans
1193 __rmul__ = __mul__
1194
1195 def __div__(self, other, context=None):
1196 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001197 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001198 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001199 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001200
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001201 if context is None:
1202 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001203
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001204 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001205
1206 if self._is_special or other._is_special:
1207 ans = self._check_nans(other, context)
1208 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001209 return ans
1210
1211 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001212 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001213
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001214 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001215 return Infsign[sign]
1216
1217 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001218 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001219 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001220
1221 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001222 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001223 if not self:
1224 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001225 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001226
Facundo Batistacce8df22007-09-18 16:53:18 +00001227 if not self:
1228 exp = self._exp - other._exp
1229 coeff = 0
1230 else:
1231 # OK, so neither = 0, INF or NaN
1232 shift = len(other._int) - len(self._int) + context.prec + 1
1233 exp = self._exp - other._exp - shift
1234 op1 = _WorkRep(self)
1235 op2 = _WorkRep(other)
1236 if shift >= 0:
1237 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1238 else:
1239 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1240 if remainder:
1241 # result is not exact; adjust to ensure correct rounding
1242 if coeff % 5 == 0:
1243 coeff += 1
1244 else:
1245 # result is exact; get as close to ideal exponent as possible
1246 ideal_exp = self._exp - other._exp
1247 while exp < ideal_exp and coeff % 10 == 0:
1248 coeff //= 10
1249 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001250
Facundo Batista72bc54f2007-11-23 17:59:00 +00001251 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001252 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001253
Facundo Batistacce8df22007-09-18 16:53:18 +00001254 __truediv__ = __div__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001255
Facundo Batistacce8df22007-09-18 16:53:18 +00001256 def _divide(self, other, context):
1257 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001258
Facundo Batistacce8df22007-09-18 16:53:18 +00001259 Assumes that neither self nor other is a NaN, that self is not
1260 infinite and that other is nonzero.
1261 """
1262 sign = self._sign ^ other._sign
1263 if other._isinfinity():
1264 ideal_exp = self._exp
1265 else:
1266 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001267
Facundo Batistacce8df22007-09-18 16:53:18 +00001268 expdiff = self.adjusted() - other.adjusted()
1269 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001270 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001271 self._rescale(ideal_exp, context.rounding))
1272 if expdiff <= context.prec:
1273 op1 = _WorkRep(self)
1274 op2 = _WorkRep(other)
1275 if op1.exp >= op2.exp:
1276 op1.int *= 10**(op1.exp - op2.exp)
1277 else:
1278 op2.int *= 10**(op2.exp - op1.exp)
1279 q, r = divmod(op1.int, op2.int)
1280 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001281 return (_dec_from_triple(sign, str(q), 0),
1282 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001283
Facundo Batistacce8df22007-09-18 16:53:18 +00001284 # Here the quotient is too large to be representable
1285 ans = context._raise_error(DivisionImpossible,
1286 'quotient too large in //, % or divmod')
1287 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001288
1289 def __rdiv__(self, other, context=None):
1290 """Swaps self/other and returns __div__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001291 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001292 if other is NotImplemented:
1293 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001294 return other.__div__(self, context=context)
1295 __rtruediv__ = __rdiv__
1296
1297 def __divmod__(self, other, context=None):
1298 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001299 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001300 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001301 other = _convert_other(other)
1302 if other is NotImplemented:
1303 return other
1304
1305 if context is None:
1306 context = getcontext()
1307
1308 ans = self._check_nans(other, context)
1309 if ans:
1310 return (ans, ans)
1311
1312 sign = self._sign ^ other._sign
1313 if self._isinfinity():
1314 if other._isinfinity():
1315 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1316 return ans, ans
1317 else:
1318 return (Infsign[sign],
1319 context._raise_error(InvalidOperation, 'INF % x'))
1320
1321 if not other:
1322 if not self:
1323 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1324 return ans, ans
1325 else:
1326 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1327 context._raise_error(InvalidOperation, 'x % 0'))
1328
1329 quotient, remainder = self._divide(other, context)
1330 if context._rounding_decision == ALWAYS_ROUND:
1331 remainder = remainder._fix(context)
1332 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001333
1334 def __rdivmod__(self, other, context=None):
1335 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001336 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001337 if other is NotImplemented:
1338 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001339 return other.__divmod__(self, context=context)
1340
1341 def __mod__(self, other, context=None):
1342 """
1343 self % other
1344 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001345 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001346 if other is NotImplemented:
1347 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001348
Facundo Batistacce8df22007-09-18 16:53:18 +00001349 if context is None:
1350 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001351
Facundo Batistacce8df22007-09-18 16:53:18 +00001352 ans = self._check_nans(other, context)
1353 if ans:
1354 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001355
Facundo Batistacce8df22007-09-18 16:53:18 +00001356 if self._isinfinity():
1357 return context._raise_error(InvalidOperation, 'INF % x')
1358 elif not other:
1359 if self:
1360 return context._raise_error(InvalidOperation, 'x % 0')
1361 else:
1362 return context._raise_error(DivisionUndefined, '0 % 0')
1363
1364 remainder = self._divide(other, context)[1]
1365 if context._rounding_decision == ALWAYS_ROUND:
1366 remainder = remainder._fix(context)
1367 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001368
1369 def __rmod__(self, other, context=None):
1370 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001371 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001372 if other is NotImplemented:
1373 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001374 return other.__mod__(self, context=context)
1375
1376 def remainder_near(self, other, context=None):
1377 """
1378 Remainder nearest to 0- abs(remainder-near) <= other/2
1379 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001380 if context is None:
1381 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001382
Facundo Batista353750c2007-09-13 18:13:15 +00001383 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001384
Facundo Batista353750c2007-09-13 18:13:15 +00001385 ans = self._check_nans(other, context)
1386 if ans:
1387 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001388
Facundo Batista353750c2007-09-13 18:13:15 +00001389 # self == +/-infinity -> InvalidOperation
1390 if self._isinfinity():
1391 return context._raise_error(InvalidOperation,
1392 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001393
Facundo Batista353750c2007-09-13 18:13:15 +00001394 # other == 0 -> either InvalidOperation or DivisionUndefined
1395 if not other:
1396 if self:
1397 return context._raise_error(InvalidOperation,
1398 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001399 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001400 return context._raise_error(DivisionUndefined,
1401 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001402
Facundo Batista353750c2007-09-13 18:13:15 +00001403 # other = +/-infinity -> remainder = self
1404 if other._isinfinity():
1405 ans = Decimal(self)
1406 return ans._fix(context)
1407
1408 # self = 0 -> remainder = self, with ideal exponent
1409 ideal_exponent = min(self._exp, other._exp)
1410 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001411 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001412 return ans._fix(context)
1413
1414 # catch most cases of large or small quotient
1415 expdiff = self.adjusted() - other.adjusted()
1416 if expdiff >= context.prec + 1:
1417 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001418 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001419 if expdiff <= -2:
1420 # expdiff <= -2 => abs(self/other) < 0.1
1421 ans = self._rescale(ideal_exponent, context.rounding)
1422 return ans._fix(context)
1423
1424 # adjust both arguments to have the same exponent, then divide
1425 op1 = _WorkRep(self)
1426 op2 = _WorkRep(other)
1427 if op1.exp >= op2.exp:
1428 op1.int *= 10**(op1.exp - op2.exp)
1429 else:
1430 op2.int *= 10**(op2.exp - op1.exp)
1431 q, r = divmod(op1.int, op2.int)
1432 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1433 # 10**ideal_exponent. Apply correction to ensure that
1434 # abs(remainder) <= abs(other)/2
1435 if 2*r + (q&1) > op2.int:
1436 r -= op2.int
1437 q += 1
1438
1439 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001440 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001441
1442 # result has same sign as self unless r is negative
1443 sign = self._sign
1444 if r < 0:
1445 sign = 1-sign
1446 r = -r
1447
Facundo Batista72bc54f2007-11-23 17:59:00 +00001448 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001449 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001450
1451 def __floordiv__(self, other, context=None):
1452 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001453 other = _convert_other(other)
1454 if other is NotImplemented:
1455 return other
1456
1457 if context is None:
1458 context = getcontext()
1459
1460 ans = self._check_nans(other, context)
1461 if ans:
1462 return ans
1463
1464 if self._isinfinity():
1465 if other._isinfinity():
1466 return context._raise_error(InvalidOperation, 'INF // INF')
1467 else:
1468 return Infsign[self._sign ^ other._sign]
1469
1470 if not other:
1471 if self:
1472 return context._raise_error(DivisionByZero, 'x // 0',
1473 self._sign ^ other._sign)
1474 else:
1475 return context._raise_error(DivisionUndefined, '0 // 0')
1476
1477 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001478
1479 def __rfloordiv__(self, other, context=None):
1480 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001481 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001482 if other is NotImplemented:
1483 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001484 return other.__floordiv__(self, context=context)
1485
1486 def __float__(self):
1487 """Float representation."""
1488 return float(str(self))
1489
1490 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001491 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001492 if self._is_special:
1493 if self._isnan():
1494 context = getcontext()
1495 return context._raise_error(InvalidContext)
1496 elif self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001497 raise OverflowError("Cannot convert infinity to long")
Facundo Batista353750c2007-09-13 18:13:15 +00001498 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001499 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001500 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001501 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001502 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001503
1504 def __long__(self):
1505 """Converts to a long.
1506
1507 Equivalent to long(int(self))
1508 """
1509 return long(self.__int__())
1510
Facundo Batista353750c2007-09-13 18:13:15 +00001511 def _fix_nan(self, context):
1512 """Decapitate the payload of a NaN to fit the context"""
1513 payload = self._int
1514
1515 # maximum length of payload is precision if _clamp=0,
1516 # precision-1 if _clamp=1.
1517 max_payload_len = context.prec - context._clamp
1518 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001519 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1520 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001521 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001522
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001523 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001524 """Round if it is necessary to keep self within prec precision.
1525
1526 Rounds and fixes the exponent. Does not raise on a sNaN.
1527
1528 Arguments:
1529 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001530 context - context used.
1531 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001532
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001533 if context is None:
1534 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001535
Facundo Batista353750c2007-09-13 18:13:15 +00001536 if self._is_special:
1537 if self._isnan():
1538 # decapitate payload if necessary
1539 return self._fix_nan(context)
1540 else:
1541 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001542 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001543
Facundo Batista353750c2007-09-13 18:13:15 +00001544 # if self is zero then exponent should be between Etiny and
1545 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1546 Etiny = context.Etiny()
1547 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001548 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001549 exp_max = [context.Emax, Etop][context._clamp]
1550 new_exp = min(max(self._exp, Etiny), exp_max)
1551 if new_exp != self._exp:
1552 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001553 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001554 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001555 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001556
1557 # exp_min is the smallest allowable exponent of the result,
1558 # equal to max(self.adjusted()-context.prec+1, Etiny)
1559 exp_min = len(self._int) + self._exp - context.prec
1560 if exp_min > Etop:
1561 # overflow: exp_min > Etop iff self.adjusted() > Emax
1562 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001563 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001564 return context._raise_error(Overflow, 'above Emax', self._sign)
1565 self_is_subnormal = exp_min < Etiny
1566 if self_is_subnormal:
1567 context._raise_error(Subnormal)
1568 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001569
Facundo Batista353750c2007-09-13 18:13:15 +00001570 # round if self has too many digits
1571 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001572 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001573 ans = self._rescale(exp_min, context.rounding)
1574 if ans != self:
1575 context._raise_error(Inexact)
1576 if self_is_subnormal:
1577 context._raise_error(Underflow)
1578 if not ans:
1579 # raise Clamped on underflow to 0
1580 context._raise_error(Clamped)
1581 elif len(ans._int) == context.prec+1:
1582 # we get here only if rescaling rounds the
1583 # cofficient up to exactly 10**context.prec
1584 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001585 ans = _dec_from_triple(ans._sign,
1586 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001587 else:
1588 # Inexact and Rounded have already been raised
1589 ans = context._raise_error(Overflow, 'above Emax',
1590 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001591 return ans
1592
Facundo Batista353750c2007-09-13 18:13:15 +00001593 # fold down if _clamp == 1 and self has too few digits
1594 if context._clamp == 1 and self._exp > Etop:
1595 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001596 self_padded = self._int + '0'*(self._exp - Etop)
1597 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001598
Facundo Batista353750c2007-09-13 18:13:15 +00001599 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001600 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001601
1602 _pick_rounding_function = {}
1603
Facundo Batista353750c2007-09-13 18:13:15 +00001604 # for each of the rounding functions below:
1605 # self is a finite, nonzero Decimal
1606 # prec is an integer satisfying 0 <= prec < len(self._int)
1607 # the rounded result will have exponent self._exp + len(self._int) - prec;
1608
1609 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001610 """Also known as round-towards-0, truncate."""
Facundo Batista353750c2007-09-13 18:13:15 +00001611 newexp = self._exp + len(self._int) - prec
Facundo Batista72bc54f2007-11-23 17:59:00 +00001612 return _dec_from_triple(self._sign, self._int[:prec] or '0', newexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001613
Facundo Batista353750c2007-09-13 18:13:15 +00001614 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001615 """Rounds away from 0."""
Facundo Batista353750c2007-09-13 18:13:15 +00001616 newexp = self._exp + len(self._int) - prec
Facundo Batista72bc54f2007-11-23 17:59:00 +00001617 tmp = _dec_from_triple(self._sign, self._int[:prec] or '0', newexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001618 for digit in self._int[prec:]:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001619 if digit != '0':
Facundo Batista353750c2007-09-13 18:13:15 +00001620 return tmp._increment()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001621 return tmp
1622
Facundo Batista353750c2007-09-13 18:13:15 +00001623 def _round_half_up(self, prec):
1624 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001625 if self._int[prec] in '56789':
Facundo Batista353750c2007-09-13 18:13:15 +00001626 return self._round_up(prec)
1627 else:
1628 return self._round_down(prec)
1629
1630 def _round_half_down(self, prec):
1631 """Round 5 down"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001632 if self._int[prec] == '5':
Facundo Batista353750c2007-09-13 18:13:15 +00001633 for digit in self._int[prec+1:]:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001634 if digit != '0':
Facundo Batista353750c2007-09-13 18:13:15 +00001635 break
1636 else:
1637 return self._round_down(prec)
1638 return self._round_half_up(prec)
1639
1640 def _round_half_even(self, prec):
1641 """Round 5 to even, rest to nearest."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001642 if prec and self._int[prec-1] in '13579':
Facundo Batista353750c2007-09-13 18:13:15 +00001643 return self._round_half_up(prec)
1644 else:
1645 return self._round_half_down(prec)
1646
1647 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001648 """Rounds up (not away from 0 if negative.)"""
1649 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001650 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001651 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001652 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001653
Facundo Batista353750c2007-09-13 18:13:15 +00001654 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001655 """Rounds down (not towards 0 if negative)"""
1656 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001657 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001658 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001659 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001660
Facundo Batista353750c2007-09-13 18:13:15 +00001661 def _round_05up(self, prec):
1662 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001663 if prec == 0 or self._int[prec-1] in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001664 return self._round_up(prec)
1665 else:
1666 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001667
Facundo Batista353750c2007-09-13 18:13:15 +00001668 def fma(self, other, third, context=None):
1669 """Fused multiply-add.
1670
1671 Returns self*other+third with no rounding of the intermediate
1672 product self*other.
1673
1674 self and other are multiplied together, with no rounding of
1675 the result. The third operand is then added to the result,
1676 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001677 """
Facundo Batista353750c2007-09-13 18:13:15 +00001678
1679 other = _convert_other(other, raiseit=True)
1680 third = _convert_other(third, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001681
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001682 if context is None:
1683 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001684
Facundo Batista353750c2007-09-13 18:13:15 +00001685 # do self*other in fresh context with no traps and no rounding
1686 mul_context = Context(traps=[], flags=[],
1687 _rounding_decision=NEVER_ROUND)
1688 product = self.__mul__(other, mul_context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001689
Facundo Batista353750c2007-09-13 18:13:15 +00001690 if mul_context.flags[InvalidOperation]:
1691 # reraise in current context
1692 return context._raise_error(InvalidOperation,
1693 'invalid multiplication in fma',
1694 1, product)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001695
Facundo Batista353750c2007-09-13 18:13:15 +00001696 ans = product.__add__(third, context)
1697 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001698
Facundo Batista353750c2007-09-13 18:13:15 +00001699 def _power_modulo(self, other, modulo, context=None):
1700 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001701
Facundo Batista353750c2007-09-13 18:13:15 +00001702 # if can't convert other and modulo to Decimal, raise
1703 # TypeError; there's no point returning NotImplemented (no
1704 # equivalent of __rpow__ for three argument pow)
1705 other = _convert_other(other, raiseit=True)
1706 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001707
Facundo Batista353750c2007-09-13 18:13:15 +00001708 if context is None:
1709 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001710
Facundo Batista353750c2007-09-13 18:13:15 +00001711 # deal with NaNs: if there are any sNaNs then first one wins,
1712 # (i.e. behaviour for NaNs is identical to that of fma)
1713 self_is_nan = self._isnan()
1714 other_is_nan = other._isnan()
1715 modulo_is_nan = modulo._isnan()
1716 if self_is_nan or other_is_nan or modulo_is_nan:
1717 if self_is_nan == 2:
1718 return context._raise_error(InvalidOperation, 'sNaN',
1719 1, self)
1720 if other_is_nan == 2:
1721 return context._raise_error(InvalidOperation, 'sNaN',
1722 1, other)
1723 if modulo_is_nan == 2:
1724 return context._raise_error(InvalidOperation, 'sNaN',
1725 1, modulo)
1726 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001727 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001728 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001729 return other._fix_nan(context)
1730 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001731
Facundo Batista353750c2007-09-13 18:13:15 +00001732 # check inputs: we apply same restrictions as Python's pow()
1733 if not (self._isinteger() and
1734 other._isinteger() and
1735 modulo._isinteger()):
1736 return context._raise_error(InvalidOperation,
1737 'pow() 3rd argument not allowed '
1738 'unless all arguments are integers')
1739 if other < 0:
1740 return context._raise_error(InvalidOperation,
1741 'pow() 2nd argument cannot be '
1742 'negative when 3rd argument specified')
1743 if not modulo:
1744 return context._raise_error(InvalidOperation,
1745 'pow() 3rd argument cannot be 0')
1746
1747 # additional restriction for decimal: the modulus must be less
1748 # than 10**prec in absolute value
1749 if modulo.adjusted() >= context.prec:
1750 return context._raise_error(InvalidOperation,
1751 'insufficient precision: pow() 3rd '
1752 'argument must not have more than '
1753 'precision digits')
1754
1755 # define 0**0 == NaN, for consistency with two-argument pow
1756 # (even though it hurts!)
1757 if not other and not self:
1758 return context._raise_error(InvalidOperation,
1759 'at least one of pow() 1st argument '
1760 'and 2nd argument must be nonzero ;'
1761 '0**0 is not defined')
1762
1763 # compute sign of result
1764 if other._iseven():
1765 sign = 0
1766 else:
1767 sign = self._sign
1768
1769 # convert modulo to a Python integer, and self and other to
1770 # Decimal integers (i.e. force their exponents to be >= 0)
1771 modulo = abs(int(modulo))
1772 base = _WorkRep(self.to_integral_value())
1773 exponent = _WorkRep(other.to_integral_value())
1774
1775 # compute result using integer pow()
1776 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1777 for i in xrange(exponent.exp):
1778 base = pow(base, 10, modulo)
1779 base = pow(base, exponent.int, modulo)
1780
Facundo Batista72bc54f2007-11-23 17:59:00 +00001781 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001782
1783 def _power_exact(self, other, p):
1784 """Attempt to compute self**other exactly.
1785
1786 Given Decimals self and other and an integer p, attempt to
1787 compute an exact result for the power self**other, with p
1788 digits of precision. Return None if self**other is not
1789 exactly representable in p digits.
1790
1791 Assumes that elimination of special cases has already been
1792 performed: self and other must both be nonspecial; self must
1793 be positive and not numerically equal to 1; other must be
1794 nonzero. For efficiency, other._exp should not be too large,
1795 so that 10**abs(other._exp) is a feasible calculation."""
1796
1797 # In the comments below, we write x for the value of self and
1798 # y for the value of other. Write x = xc*10**xe and y =
1799 # yc*10**ye.
1800
1801 # The main purpose of this method is to identify the *failure*
1802 # of x**y to be exactly representable with as little effort as
1803 # possible. So we look for cheap and easy tests that
1804 # eliminate the possibility of x**y being exact. Only if all
1805 # these tests are passed do we go on to actually compute x**y.
1806
1807 # Here's the main idea. First normalize both x and y. We
1808 # express y as a rational m/n, with m and n relatively prime
1809 # and n>0. Then for x**y to be exactly representable (at
1810 # *any* precision), xc must be the nth power of a positive
1811 # integer and xe must be divisible by n. If m is negative
1812 # then additionally xc must be a power of either 2 or 5, hence
1813 # a power of 2**n or 5**n.
1814 #
1815 # There's a limit to how small |y| can be: if y=m/n as above
1816 # then:
1817 #
1818 # (1) if xc != 1 then for the result to be representable we
1819 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1820 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1821 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1822 # representable.
1823 #
1824 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1825 # |y| < 1/|xe| then the result is not representable.
1826 #
1827 # Note that since x is not equal to 1, at least one of (1) and
1828 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1829 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1830 #
1831 # There's also a limit to how large y can be, at least if it's
1832 # positive: the normalized result will have coefficient xc**y,
1833 # so if it's representable then xc**y < 10**p, and y <
1834 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1835 # not exactly representable.
1836
1837 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1838 # so |y| < 1/xe and the result is not representable.
1839 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1840 # < 1/nbits(xc).
1841
1842 x = _WorkRep(self)
1843 xc, xe = x.int, x.exp
1844 while xc % 10 == 0:
1845 xc //= 10
1846 xe += 1
1847
1848 y = _WorkRep(other)
1849 yc, ye = y.int, y.exp
1850 while yc % 10 == 0:
1851 yc //= 10
1852 ye += 1
1853
1854 # case where xc == 1: result is 10**(xe*y), with xe*y
1855 # required to be an integer
1856 if xc == 1:
1857 if ye >= 0:
1858 exponent = xe*yc*10**ye
1859 else:
1860 exponent, remainder = divmod(xe*yc, 10**-ye)
1861 if remainder:
1862 return None
1863 if y.sign == 1:
1864 exponent = -exponent
1865 # if other is a nonnegative integer, use ideal exponent
1866 if other._isinteger() and other._sign == 0:
1867 ideal_exponent = self._exp*int(other)
1868 zeros = min(exponent-ideal_exponent, p-1)
1869 else:
1870 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001871 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001872
1873 # case where y is negative: xc must be either a power
1874 # of 2 or a power of 5.
1875 if y.sign == 1:
1876 last_digit = xc % 10
1877 if last_digit in (2,4,6,8):
1878 # quick test for power of 2
1879 if xc & -xc != xc:
1880 return None
1881 # now xc is a power of 2; e is its exponent
1882 e = _nbits(xc)-1
1883 # find e*y and xe*y; both must be integers
1884 if ye >= 0:
1885 y_as_int = yc*10**ye
1886 e = e*y_as_int
1887 xe = xe*y_as_int
1888 else:
1889 ten_pow = 10**-ye
1890 e, remainder = divmod(e*yc, ten_pow)
1891 if remainder:
1892 return None
1893 xe, remainder = divmod(xe*yc, ten_pow)
1894 if remainder:
1895 return None
1896
1897 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1898 return None
1899 xc = 5**e
1900
1901 elif last_digit == 5:
1902 # e >= log_5(xc) if xc is a power of 5; we have
1903 # equality all the way up to xc=5**2658
1904 e = _nbits(xc)*28//65
1905 xc, remainder = divmod(5**e, xc)
1906 if remainder:
1907 return None
1908 while xc % 5 == 0:
1909 xc //= 5
1910 e -= 1
1911 if ye >= 0:
1912 y_as_integer = yc*10**ye
1913 e = e*y_as_integer
1914 xe = xe*y_as_integer
1915 else:
1916 ten_pow = 10**-ye
1917 e, remainder = divmod(e*yc, ten_pow)
1918 if remainder:
1919 return None
1920 xe, remainder = divmod(xe*yc, ten_pow)
1921 if remainder:
1922 return None
1923 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1924 return None
1925 xc = 2**e
1926 else:
1927 return None
1928
1929 if xc >= 10**p:
1930 return None
1931 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00001932 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00001933
1934 # now y is positive; find m and n such that y = m/n
1935 if ye >= 0:
1936 m, n = yc*10**ye, 1
1937 else:
1938 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1939 return None
1940 xc_bits = _nbits(xc)
1941 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1942 return None
1943 m, n = yc, 10**(-ye)
1944 while m % 2 == n % 2 == 0:
1945 m //= 2
1946 n //= 2
1947 while m % 5 == n % 5 == 0:
1948 m //= 5
1949 n //= 5
1950
1951 # compute nth root of xc*10**xe
1952 if n > 1:
1953 # if 1 < xc < 2**n then xc isn't an nth power
1954 if xc != 1 and xc_bits <= n:
1955 return None
1956
1957 xe, rem = divmod(xe, n)
1958 if rem != 0:
1959 return None
1960
1961 # compute nth root of xc using Newton's method
1962 a = 1L << -(-_nbits(xc)//n) # initial estimate
1963 while True:
1964 q, r = divmod(xc, a**(n-1))
1965 if a <= q:
1966 break
1967 else:
1968 a = (a*(n-1) + q)//n
1969 if not (a == q and r == 0):
1970 return None
1971 xc = a
1972
1973 # now xc*10**xe is the nth root of the original xc*10**xe
1974 # compute mth power of xc*10**xe
1975
1976 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1977 # 10**p and the result is not representable.
1978 if xc > 1 and m > p*100//_log10_lb(xc):
1979 return None
1980 xc = xc**m
1981 xe *= m
1982 if xc > 10**p:
1983 return None
1984
1985 # by this point the result *is* exactly representable
1986 # adjust the exponent to get as close as possible to the ideal
1987 # exponent, if necessary
1988 str_xc = str(xc)
1989 if other._isinteger() and other._sign == 0:
1990 ideal_exponent = self._exp*int(other)
1991 zeros = min(xe-ideal_exponent, p-len(str_xc))
1992 else:
1993 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001994 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001995
1996 def __pow__(self, other, modulo=None, context=None):
1997 """Return self ** other [ % modulo].
1998
1999 With two arguments, compute self**other.
2000
2001 With three arguments, compute (self**other) % modulo. For the
2002 three argument form, the following restrictions on the
2003 arguments hold:
2004
2005 - all three arguments must be integral
2006 - other must be nonnegative
2007 - either self or other (or both) must be nonzero
2008 - modulo must be nonzero and must have at most p digits,
2009 where p is the context precision.
2010
2011 If any of these restrictions is violated the InvalidOperation
2012 flag is raised.
2013
2014 The result of pow(self, other, modulo) is identical to the
2015 result that would be obtained by computing (self**other) %
2016 modulo with unbounded precision, but is computed more
2017 efficiently. It is always exact.
2018 """
2019
2020 if modulo is not None:
2021 return self._power_modulo(other, modulo, context)
2022
2023 other = _convert_other(other)
2024 if other is NotImplemented:
2025 return other
2026
2027 if context is None:
2028 context = getcontext()
2029
2030 # either argument is a NaN => result is NaN
2031 ans = self._check_nans(other, context)
2032 if ans:
2033 return ans
2034
2035 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2036 if not other:
2037 if not self:
2038 return context._raise_error(InvalidOperation, '0 ** 0')
2039 else:
2040 return Dec_p1
2041
2042 # result has sign 1 iff self._sign is 1 and other is an odd integer
2043 result_sign = 0
2044 if self._sign == 1:
2045 if other._isinteger():
2046 if not other._iseven():
2047 result_sign = 1
2048 else:
2049 # -ve**noninteger = NaN
2050 # (-0)**noninteger = 0**noninteger
2051 if self:
2052 return context._raise_error(InvalidOperation,
2053 'x ** y with x negative and y not an integer')
2054 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002055 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002056
2057 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2058 if not self:
2059 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002060 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002061 else:
2062 return Infsign[result_sign]
2063
2064 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002065 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002066 if other._sign == 0:
2067 return Infsign[result_sign]
2068 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002069 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002070
Facundo Batista353750c2007-09-13 18:13:15 +00002071 # 1**other = 1, but the choice of exponent and the flags
2072 # depend on the exponent of self, and on whether other is a
2073 # positive integer, a negative integer, or neither
2074 if self == Dec_p1:
2075 if other._isinteger():
2076 # exp = max(self._exp*max(int(other), 0),
2077 # 1-context.prec) but evaluating int(other) directly
2078 # is dangerous until we know other is small (other
2079 # could be 1e999999999)
2080 if other._sign == 1:
2081 multiplier = 0
2082 elif other > context.prec:
2083 multiplier = context.prec
2084 else:
2085 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002086
Facundo Batista353750c2007-09-13 18:13:15 +00002087 exp = self._exp * multiplier
2088 if exp < 1-context.prec:
2089 exp = 1-context.prec
2090 context._raise_error(Rounded)
2091 else:
2092 context._raise_error(Inexact)
2093 context._raise_error(Rounded)
2094 exp = 1-context.prec
2095
Facundo Batista72bc54f2007-11-23 17:59:00 +00002096 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002097
2098 # compute adjusted exponent of self
2099 self_adj = self.adjusted()
2100
2101 # self ** infinity is infinity if self > 1, 0 if self < 1
2102 # self ** -infinity is infinity if self < 1, 0 if self > 1
2103 if other._isinfinity():
2104 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002105 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002106 else:
2107 return Infsign[result_sign]
2108
2109 # from here on, the result always goes through the call
2110 # to _fix at the end of this function.
2111 ans = None
2112
2113 # crude test to catch cases of extreme overflow/underflow. If
2114 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2115 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2116 # self**other >= 10**(Emax+1), so overflow occurs. The test
2117 # for underflow is similar.
2118 bound = self._log10_exp_bound() + other.adjusted()
2119 if (self_adj >= 0) == (other._sign == 0):
2120 # self > 1 and other +ve, or self < 1 and other -ve
2121 # possibility of overflow
2122 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002123 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002124 else:
2125 # self > 1 and other -ve, or self < 1 and other +ve
2126 # possibility of underflow to 0
2127 Etiny = context.Etiny()
2128 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002129 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002130
2131 # try for an exact result with precision +1
2132 if ans is None:
2133 ans = self._power_exact(other, context.prec + 1)
2134 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002135 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002136
2137 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2138 if ans is None:
2139 p = context.prec
2140 x = _WorkRep(self)
2141 xc, xe = x.int, x.exp
2142 y = _WorkRep(other)
2143 yc, ye = y.int, y.exp
2144 if y.sign == 1:
2145 yc = -yc
2146
2147 # compute correctly rounded result: start with precision +3,
2148 # then increase precision until result is unambiguously roundable
2149 extra = 3
2150 while True:
2151 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2152 if coeff % (5*10**(len(str(coeff))-p-1)):
2153 break
2154 extra += 3
2155
Facundo Batista72bc54f2007-11-23 17:59:00 +00002156 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002157
2158 # the specification says that for non-integer other we need to
2159 # raise Inexact, even when the result is actually exact. In
2160 # the same way, we need to raise Underflow here if the result
2161 # is subnormal. (The call to _fix will take care of raising
2162 # Rounded and Subnormal, as usual.)
2163 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002164 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002165 # pad with zeros up to length context.prec+1 if necessary
2166 if len(ans._int) <= context.prec:
2167 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002168 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2169 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002170 if ans.adjusted() < context.Emin:
2171 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002172
Facundo Batista353750c2007-09-13 18:13:15 +00002173 # unlike exp, ln and log10, the power function respects the
2174 # rounding mode; no need to use ROUND_HALF_EVEN here
2175 ans = ans._fix(context)
2176 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002177
2178 def __rpow__(self, other, context=None):
2179 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002180 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002181 if other is NotImplemented:
2182 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002183 return other.__pow__(self, context=context)
2184
2185 def normalize(self, context=None):
2186 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002187
Facundo Batista353750c2007-09-13 18:13:15 +00002188 if context is None:
2189 context = getcontext()
2190
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002191 if self._is_special:
2192 ans = self._check_nans(context=context)
2193 if ans:
2194 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002195
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002196 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002197 if dup._isinfinity():
2198 return dup
2199
2200 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002201 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002202 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002203 end = len(dup._int)
2204 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002205 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002206 exp += 1
2207 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002208 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002209
Facundo Batistabd2fe832007-09-13 18:42:09 +00002210 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002211 """Quantize self so its exponent is the same as that of exp.
2212
2213 Similar to self._rescale(exp._exp) but with error checking.
2214 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002215 exp = _convert_other(exp, raiseit=True)
2216
Facundo Batista353750c2007-09-13 18:13:15 +00002217 if context is None:
2218 context = getcontext()
2219 if rounding is None:
2220 rounding = context.rounding
2221
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002222 if self._is_special or exp._is_special:
2223 ans = self._check_nans(exp, context)
2224 if ans:
2225 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002226
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002227 if exp._isinfinity() or self._isinfinity():
2228 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002229 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002230 return context._raise_error(InvalidOperation,
2231 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002232
Facundo Batistabd2fe832007-09-13 18:42:09 +00002233 # if we're not watching exponents, do a simple rescale
2234 if not watchexp:
2235 ans = self._rescale(exp._exp, rounding)
2236 # raise Inexact and Rounded where appropriate
2237 if ans._exp > self._exp:
2238 context._raise_error(Rounded)
2239 if ans != self:
2240 context._raise_error(Inexact)
2241 return ans
2242
Facundo Batista353750c2007-09-13 18:13:15 +00002243 # exp._exp should be between Etiny and Emax
2244 if not (context.Etiny() <= exp._exp <= context.Emax):
2245 return context._raise_error(InvalidOperation,
2246 'target exponent out of bounds in quantize')
2247
2248 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002249 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002250 return ans._fix(context)
2251
2252 self_adjusted = self.adjusted()
2253 if self_adjusted > context.Emax:
2254 return context._raise_error(InvalidOperation,
2255 'exponent of quantize result too large for current context')
2256 if self_adjusted - exp._exp + 1 > context.prec:
2257 return context._raise_error(InvalidOperation,
2258 'quantize result has too many digits for current context')
2259
2260 ans = self._rescale(exp._exp, rounding)
2261 if ans.adjusted() > context.Emax:
2262 return context._raise_error(InvalidOperation,
2263 'exponent of quantize result too large for current context')
2264 if len(ans._int) > context.prec:
2265 return context._raise_error(InvalidOperation,
2266 'quantize result has too many digits for current context')
2267
2268 # raise appropriate flags
2269 if ans._exp > self._exp:
2270 context._raise_error(Rounded)
2271 if ans != self:
2272 context._raise_error(Inexact)
2273 if ans and ans.adjusted() < context.Emin:
2274 context._raise_error(Subnormal)
2275
2276 # call to fix takes care of any necessary folddown
2277 ans = ans._fix(context)
2278 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002279
2280 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002281 """Return True if self and other have the same exponent; otherwise
2282 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002283
Facundo Batista1a191df2007-10-02 17:01:24 +00002284 If either operand is a special value, the following rules are used:
2285 * return True if both operands are infinities
2286 * return True if both operands are NaNs
2287 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002288 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002289 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002290 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002291 return (self.is_nan() and other.is_nan() or
2292 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002293 return self._exp == other._exp
2294
Facundo Batista353750c2007-09-13 18:13:15 +00002295 def _rescale(self, exp, rounding):
2296 """Rescale self so that the exponent is exp, either by padding with zeros
2297 or by truncating digits, using the given rounding mode.
2298
2299 Specials are returned without change. This operation is
2300 quiet: it raises no flags, and uses no information from the
2301 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002302
2303 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002304 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002305 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002306 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002307 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002308 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002309 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002310
Facundo Batista353750c2007-09-13 18:13:15 +00002311 if self._exp >= exp:
2312 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002313 return _dec_from_triple(self._sign,
2314 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002315
Facundo Batista353750c2007-09-13 18:13:15 +00002316 # too many digits; round and lose data. If self.adjusted() <
2317 # exp-1, replace self by 10**(exp-1) before rounding
2318 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002319 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002320 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002321 digits = 0
2322 this_function = getattr(self, self._pick_rounding_function[rounding])
2323 return this_function(digits)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002324
Facundo Batista353750c2007-09-13 18:13:15 +00002325 def to_integral_exact(self, rounding=None, context=None):
2326 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002327
Facundo Batista353750c2007-09-13 18:13:15 +00002328 If no rounding mode is specified, take the rounding mode from
2329 the context. This method raises the Rounded and Inexact flags
2330 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002331
Facundo Batista353750c2007-09-13 18:13:15 +00002332 See also: to_integral_value, which does exactly the same as
2333 this method except that it doesn't raise Inexact or Rounded.
2334 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002335 if self._is_special:
2336 ans = self._check_nans(context=context)
2337 if ans:
2338 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002339 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002340 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002341 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002342 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002343 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002344 if context is None:
2345 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002346 if rounding is None:
2347 rounding = context.rounding
2348 context._raise_error(Rounded)
2349 ans = self._rescale(0, rounding)
2350 if ans != self:
2351 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002352 return ans
2353
Facundo Batista353750c2007-09-13 18:13:15 +00002354 def to_integral_value(self, rounding=None, context=None):
2355 """Rounds to the nearest integer, without raising inexact, rounded."""
2356 if context is None:
2357 context = getcontext()
2358 if rounding is None:
2359 rounding = context.rounding
2360 if self._is_special:
2361 ans = self._check_nans(context=context)
2362 if ans:
2363 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002364 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002365 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002366 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002367 else:
2368 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002369
Facundo Batista353750c2007-09-13 18:13:15 +00002370 # the method name changed, but we provide also the old one, for compatibility
2371 to_integral = to_integral_value
2372
2373 def sqrt(self, context=None):
2374 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002375 if self._is_special:
2376 ans = self._check_nans(context=context)
2377 if ans:
2378 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002379
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002380 if self._isinfinity() and self._sign == 0:
2381 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002382
2383 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002384 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002385 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002386 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002387
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002388 if context is None:
2389 context = getcontext()
2390
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002391 if self._sign == 1:
2392 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2393
Facundo Batista353750c2007-09-13 18:13:15 +00002394 # At this point self represents a positive number. Let p be
2395 # the desired precision and express self in the form c*100**e
2396 # with c a positive real number and e an integer, c and e
2397 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2398 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2399 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2400 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2401 # the closest integer to sqrt(c) with the even integer chosen
2402 # in the case of a tie.
2403 #
2404 # To ensure correct rounding in all cases, we use the
2405 # following trick: we compute the square root to an extra
2406 # place (precision p+1 instead of precision p), rounding down.
2407 # Then, if the result is inexact and its last digit is 0 or 5,
2408 # we increase the last digit to 1 or 6 respectively; if it's
2409 # exact we leave the last digit alone. Now the final round to
2410 # p places (or fewer in the case of underflow) will round
2411 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002412
Facundo Batista353750c2007-09-13 18:13:15 +00002413 # use an extra digit of precision
2414 prec = context.prec+1
2415
2416 # write argument in the form c*100**e where e = self._exp//2
2417 # is the 'ideal' exponent, to be used if the square root is
2418 # exactly representable. l is the number of 'digits' of c in
2419 # base 100, so that 100**(l-1) <= c < 100**l.
2420 op = _WorkRep(self)
2421 e = op.exp >> 1
2422 if op.exp & 1:
2423 c = op.int * 10
2424 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002425 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002426 c = op.int
2427 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002428
Facundo Batista353750c2007-09-13 18:13:15 +00002429 # rescale so that c has exactly prec base 100 'digits'
2430 shift = prec-l
2431 if shift >= 0:
2432 c *= 100**shift
2433 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002434 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002435 c, remainder = divmod(c, 100**-shift)
2436 exact = not remainder
2437 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002438
Facundo Batista353750c2007-09-13 18:13:15 +00002439 # find n = floor(sqrt(c)) using Newton's method
2440 n = 10**prec
2441 while True:
2442 q = c//n
2443 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002444 break
Facundo Batista353750c2007-09-13 18:13:15 +00002445 else:
2446 n = n + q >> 1
2447 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002448
Facundo Batista353750c2007-09-13 18:13:15 +00002449 if exact:
2450 # result is exact; rescale to use ideal exponent e
2451 if shift >= 0:
2452 # assert n % 10**shift == 0
2453 n //= 10**shift
2454 else:
2455 n *= 10**-shift
2456 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002457 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002458 # result is not exact; fix last digit as described above
2459 if n % 5 == 0:
2460 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002461
Facundo Batista72bc54f2007-11-23 17:59:00 +00002462 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002463
Facundo Batista353750c2007-09-13 18:13:15 +00002464 # round, and fit to current context
2465 context = context._shallow_copy()
2466 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002467 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002468 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002469
Facundo Batista353750c2007-09-13 18:13:15 +00002470 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002471
2472 def max(self, other, context=None):
2473 """Returns the larger value.
2474
Facundo Batista353750c2007-09-13 18:13:15 +00002475 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002476 NaN (and signals if one is sNaN). Also rounds.
2477 """
Facundo Batista353750c2007-09-13 18:13:15 +00002478 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002479
Facundo Batista6c398da2007-09-17 17:30:13 +00002480 if context is None:
2481 context = getcontext()
2482
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002483 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002484 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002485 # number is always returned
2486 sn = self._isnan()
2487 on = other._isnan()
2488 if sn or on:
2489 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002490 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002491 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002492 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002493 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002494
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002495 c = self.__cmp__(other)
2496 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002497 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002498 # then an ordering is applied:
2499 #
Facundo Batista59c58842007-04-10 12:58:45 +00002500 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002501 # positive sign and min returns the operand with the negative sign
2502 #
Facundo Batista59c58842007-04-10 12:58:45 +00002503 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002504 # the result. This is exactly the ordering used in compare_total.
2505 c = self.compare_total(other)
2506
2507 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002508 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002509 else:
2510 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002511
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002512 if context._rounding_decision == ALWAYS_ROUND:
2513 return ans._fix(context)
2514 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002515
2516 def min(self, other, context=None):
2517 """Returns the smaller value.
2518
Facundo Batista59c58842007-04-10 12:58:45 +00002519 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002520 NaN (and signals if one is sNaN). Also rounds.
2521 """
Facundo Batista353750c2007-09-13 18:13:15 +00002522 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002523
Facundo Batista6c398da2007-09-17 17:30:13 +00002524 if context is None:
2525 context = getcontext()
2526
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002527 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002528 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002529 # number is always returned
2530 sn = self._isnan()
2531 on = other._isnan()
2532 if sn or on:
2533 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002534 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002535 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002536 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002537 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002538
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002539 c = self.__cmp__(other)
2540 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002541 c = self.compare_total(other)
2542
2543 if c == -1:
2544 ans = self
2545 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002546 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002547
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002548 if context._rounding_decision == ALWAYS_ROUND:
2549 return ans._fix(context)
2550 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002551
2552 def _isinteger(self):
2553 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002554 if self._is_special:
2555 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002556 if self._exp >= 0:
2557 return True
2558 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002559 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002560
2561 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002562 """Returns True if self is even. Assumes self is an integer."""
2563 if not self or self._exp > 0:
2564 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002565 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002566
2567 def adjusted(self):
2568 """Return the adjusted exponent of self"""
2569 try:
2570 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002571 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002572 except TypeError:
2573 return 0
2574
Facundo Batista353750c2007-09-13 18:13:15 +00002575 def canonical(self, context=None):
2576 """Returns the same Decimal object.
2577
2578 As we do not have different encodings for the same number, the
2579 received object already is in its canonical form.
2580 """
2581 return self
2582
2583 def compare_signal(self, other, context=None):
2584 """Compares self to the other operand numerically.
2585
2586 It's pretty much like compare(), but all NaNs signal, with signaling
2587 NaNs taking precedence over quiet NaNs.
2588 """
2589 if context is None:
2590 context = getcontext()
2591
2592 self_is_nan = self._isnan()
2593 other_is_nan = other._isnan()
2594 if self_is_nan == 2:
2595 return context._raise_error(InvalidOperation, 'sNaN',
2596 1, self)
2597 if other_is_nan == 2:
2598 return context._raise_error(InvalidOperation, 'sNaN',
2599 1, other)
2600 if self_is_nan:
2601 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2602 1, self)
2603 if other_is_nan:
2604 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2605 1, other)
2606 return self.compare(other, context=context)
2607
2608 def compare_total(self, other):
2609 """Compares self to other using the abstract representations.
2610
2611 This is not like the standard compare, which use their numerical
2612 value. Note that a total ordering is defined for all possible abstract
2613 representations.
2614 """
2615 # if one is negative and the other is positive, it's easy
2616 if self._sign and not other._sign:
2617 return Dec_n1
2618 if not self._sign and other._sign:
2619 return Dec_p1
2620 sign = self._sign
2621
2622 # let's handle both NaN types
2623 self_nan = self._isnan()
2624 other_nan = other._isnan()
2625 if self_nan or other_nan:
2626 if self_nan == other_nan:
2627 if self._int < other._int:
2628 if sign:
2629 return Dec_p1
2630 else:
2631 return Dec_n1
2632 if self._int > other._int:
2633 if sign:
2634 return Dec_n1
2635 else:
2636 return Dec_p1
2637 return Dec_0
2638
2639 if sign:
2640 if self_nan == 1:
2641 return Dec_n1
2642 if other_nan == 1:
2643 return Dec_p1
2644 if self_nan == 2:
2645 return Dec_n1
2646 if other_nan == 2:
2647 return Dec_p1
2648 else:
2649 if self_nan == 1:
2650 return Dec_p1
2651 if other_nan == 1:
2652 return Dec_n1
2653 if self_nan == 2:
2654 return Dec_p1
2655 if other_nan == 2:
2656 return Dec_n1
2657
2658 if self < other:
2659 return Dec_n1
2660 if self > other:
2661 return Dec_p1
2662
2663 if self._exp < other._exp:
2664 if sign:
2665 return Dec_p1
2666 else:
2667 return Dec_n1
2668 if self._exp > other._exp:
2669 if sign:
2670 return Dec_n1
2671 else:
2672 return Dec_p1
2673 return Dec_0
2674
2675
2676 def compare_total_mag(self, other):
2677 """Compares self to other using abstract repr., ignoring sign.
2678
2679 Like compare_total, but with operand's sign ignored and assumed to be 0.
2680 """
2681 s = self.copy_abs()
2682 o = other.copy_abs()
2683 return s.compare_total(o)
2684
2685 def copy_abs(self):
2686 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002687 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002688
2689 def copy_negate(self):
2690 """Returns a copy with the sign inverted."""
2691 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002692 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002693 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002694 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002695
2696 def copy_sign(self, other):
2697 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002698 return _dec_from_triple(other._sign, self._int,
2699 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002700
2701 def exp(self, context=None):
2702 """Returns e ** self."""
2703
2704 if context is None:
2705 context = getcontext()
2706
2707 # exp(NaN) = NaN
2708 ans = self._check_nans(context=context)
2709 if ans:
2710 return ans
2711
2712 # exp(-Infinity) = 0
2713 if self._isinfinity() == -1:
2714 return Dec_0
2715
2716 # exp(0) = 1
2717 if not self:
2718 return Dec_p1
2719
2720 # exp(Infinity) = Infinity
2721 if self._isinfinity() == 1:
2722 return Decimal(self)
2723
2724 # the result is now guaranteed to be inexact (the true
2725 # mathematical result is transcendental). There's no need to
2726 # raise Rounded and Inexact here---they'll always be raised as
2727 # a result of the call to _fix.
2728 p = context.prec
2729 adj = self.adjusted()
2730
2731 # we only need to do any computation for quite a small range
2732 # of adjusted exponents---for example, -29 <= adj <= 10 for
2733 # the default context. For smaller exponent the result is
2734 # indistinguishable from 1 at the given precision, while for
2735 # larger exponent the result either overflows or underflows.
2736 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2737 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002738 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002739 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2740 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002741 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002742 elif self._sign == 0 and adj < -p:
2743 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002744 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002745 elif self._sign == 1 and adj < -p-1:
2746 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002747 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002748 # general case
2749 else:
2750 op = _WorkRep(self)
2751 c, e = op.int, op.exp
2752 if op.sign == 1:
2753 c = -c
2754
2755 # compute correctly rounded result: increase precision by
2756 # 3 digits at a time until we get an unambiguously
2757 # roundable result
2758 extra = 3
2759 while True:
2760 coeff, exp = _dexp(c, e, p+extra)
2761 if coeff % (5*10**(len(str(coeff))-p-1)):
2762 break
2763 extra += 3
2764
Facundo Batista72bc54f2007-11-23 17:59:00 +00002765 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002766
2767 # at this stage, ans should round correctly with *any*
2768 # rounding mode, not just with ROUND_HALF_EVEN
2769 context = context._shallow_copy()
2770 rounding = context._set_rounding(ROUND_HALF_EVEN)
2771 ans = ans._fix(context)
2772 context.rounding = rounding
2773
2774 return ans
2775
2776 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002777 """Return True if self is canonical; otherwise return False.
2778
2779 Currently, the encoding of a Decimal instance is always
2780 canonical, so this method returns True for any Decimal.
2781 """
2782 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002783
2784 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002785 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002786
Facundo Batista1a191df2007-10-02 17:01:24 +00002787 A Decimal instance is considered finite if it is neither
2788 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002789 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002790 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002791
2792 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002793 """Return True if self is infinite; otherwise return False."""
2794 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002795
2796 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002797 """Return True if self is a qNaN or sNaN; otherwise return False."""
2798 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002799
2800 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002801 """Return True if self is a normal number; otherwise return False."""
2802 if self._is_special or not self:
2803 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002804 if context is None:
2805 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002806 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002807
2808 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002809 """Return True if self is a quiet NaN; otherwise return False."""
2810 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002811
2812 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002813 """Return True if self is negative; otherwise return False."""
2814 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002815
2816 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002817 """Return True if self is a signaling NaN; otherwise return False."""
2818 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002819
2820 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002821 """Return True if self is subnormal; otherwise return False."""
2822 if self._is_special or not self:
2823 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002824 if context is None:
2825 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002826 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002827
2828 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002829 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002830 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002831
2832 def _ln_exp_bound(self):
2833 """Compute a lower bound for the adjusted exponent of self.ln().
2834 In other words, compute r such that self.ln() >= 10**r. Assumes
2835 that self is finite and positive and that self != 1.
2836 """
2837
2838 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2839 adj = self._exp + len(self._int) - 1
2840 if adj >= 1:
2841 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2842 return len(str(adj*23//10)) - 1
2843 if adj <= -2:
2844 # argument <= 0.1
2845 return len(str((-1-adj)*23//10)) - 1
2846 op = _WorkRep(self)
2847 c, e = op.int, op.exp
2848 if adj == 0:
2849 # 1 < self < 10
2850 num = str(c-10**-e)
2851 den = str(c)
2852 return len(num) - len(den) - (num < den)
2853 # adj == -1, 0.1 <= self < 1
2854 return e + len(str(10**-e - c)) - 1
2855
2856
2857 def ln(self, context=None):
2858 """Returns the natural (base e) logarithm of self."""
2859
2860 if context is None:
2861 context = getcontext()
2862
2863 # ln(NaN) = NaN
2864 ans = self._check_nans(context=context)
2865 if ans:
2866 return ans
2867
2868 # ln(0.0) == -Infinity
2869 if not self:
2870 return negInf
2871
2872 # ln(Infinity) = Infinity
2873 if self._isinfinity() == 1:
2874 return Inf
2875
2876 # ln(1.0) == 0.0
2877 if self == Dec_p1:
2878 return Dec_0
2879
2880 # ln(negative) raises InvalidOperation
2881 if self._sign == 1:
2882 return context._raise_error(InvalidOperation,
2883 'ln of a negative value')
2884
2885 # result is irrational, so necessarily inexact
2886 op = _WorkRep(self)
2887 c, e = op.int, op.exp
2888 p = context.prec
2889
2890 # correctly rounded result: repeatedly increase precision by 3
2891 # until we get an unambiguously roundable result
2892 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2893 while True:
2894 coeff = _dlog(c, e, places)
2895 # assert len(str(abs(coeff)))-p >= 1
2896 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2897 break
2898 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002899 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002900
2901 context = context._shallow_copy()
2902 rounding = context._set_rounding(ROUND_HALF_EVEN)
2903 ans = ans._fix(context)
2904 context.rounding = rounding
2905 return ans
2906
2907 def _log10_exp_bound(self):
2908 """Compute a lower bound for the adjusted exponent of self.log10().
2909 In other words, find r such that self.log10() >= 10**r.
2910 Assumes that self is finite and positive and that self != 1.
2911 """
2912
2913 # For x >= 10 or x < 0.1 we only need a bound on the integer
2914 # part of log10(self), and this comes directly from the
2915 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2916 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2917 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2918
2919 adj = self._exp + len(self._int) - 1
2920 if adj >= 1:
2921 # self >= 10
2922 return len(str(adj))-1
2923 if adj <= -2:
2924 # self < 0.1
2925 return len(str(-1-adj))-1
2926 op = _WorkRep(self)
2927 c, e = op.int, op.exp
2928 if adj == 0:
2929 # 1 < self < 10
2930 num = str(c-10**-e)
2931 den = str(231*c)
2932 return len(num) - len(den) - (num < den) + 2
2933 # adj == -1, 0.1 <= self < 1
2934 num = str(10**-e-c)
2935 return len(num) + e - (num < "231") - 1
2936
2937 def log10(self, context=None):
2938 """Returns the base 10 logarithm of self."""
2939
2940 if context is None:
2941 context = getcontext()
2942
2943 # log10(NaN) = NaN
2944 ans = self._check_nans(context=context)
2945 if ans:
2946 return ans
2947
2948 # log10(0.0) == -Infinity
2949 if not self:
2950 return negInf
2951
2952 # log10(Infinity) = Infinity
2953 if self._isinfinity() == 1:
2954 return Inf
2955
2956 # log10(negative or -Infinity) raises InvalidOperation
2957 if self._sign == 1:
2958 return context._raise_error(InvalidOperation,
2959 'log10 of a negative value')
2960
2961 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00002962 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00002963 # answer may need rounding
2964 ans = Decimal(self._exp + len(self._int) - 1)
2965 else:
2966 # result is irrational, so necessarily inexact
2967 op = _WorkRep(self)
2968 c, e = op.int, op.exp
2969 p = context.prec
2970
2971 # correctly rounded result: repeatedly increase precision
2972 # until result is unambiguously roundable
2973 places = p-self._log10_exp_bound()+2
2974 while True:
2975 coeff = _dlog10(c, e, places)
2976 # assert len(str(abs(coeff)))-p >= 1
2977 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2978 break
2979 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002980 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002981
2982 context = context._shallow_copy()
2983 rounding = context._set_rounding(ROUND_HALF_EVEN)
2984 ans = ans._fix(context)
2985 context.rounding = rounding
2986 return ans
2987
2988 def logb(self, context=None):
2989 """ Returns the exponent of the magnitude of self's MSD.
2990
2991 The result is the integer which is the exponent of the magnitude
2992 of the most significant digit of self (as though it were truncated
2993 to a single digit while maintaining the value of that digit and
2994 without limiting the resulting exponent).
2995 """
2996 # logb(NaN) = NaN
2997 ans = self._check_nans(context=context)
2998 if ans:
2999 return ans
3000
3001 if context is None:
3002 context = getcontext()
3003
3004 # logb(+/-Inf) = +Inf
3005 if self._isinfinity():
3006 return Inf
3007
3008 # logb(0) = -Inf, DivisionByZero
3009 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00003010 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00003011
3012 # otherwise, simply return the adjusted exponent of self, as a
3013 # Decimal. Note that no attempt is made to fit the result
3014 # into the current context.
3015 return Decimal(self.adjusted())
3016
3017 def _islogical(self):
3018 """Return True if self is a logical operand.
3019
3020 For being logical, it must be a finite numbers with a sign of 0,
3021 an exponent of 0, and a coefficient whose digits must all be
3022 either 0 or 1.
3023 """
3024 if self._sign != 0 or self._exp != 0:
3025 return False
3026 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003027 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00003028 return False
3029 return True
3030
3031 def _fill_logical(self, context, opa, opb):
3032 dif = context.prec - len(opa)
3033 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003034 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00003035 elif dif < 0:
3036 opa = opa[-context.prec:]
3037 dif = context.prec - len(opb)
3038 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003039 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00003040 elif dif < 0:
3041 opb = opb[-context.prec:]
3042 return opa, opb
3043
3044 def logical_and(self, other, context=None):
3045 """Applies an 'and' operation between self and other's digits."""
3046 if context is None:
3047 context = getcontext()
3048 if not self._islogical() or not other._islogical():
3049 return context._raise_error(InvalidOperation)
3050
3051 # fill to context.prec
3052 (opa, opb) = self._fill_logical(context, self._int, other._int)
3053
3054 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003055 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3056 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003057
3058 def logical_invert(self, context=None):
3059 """Invert all its digits."""
3060 if context is None:
3061 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003062 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3063 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003064
3065 def logical_or(self, other, context=None):
3066 """Applies an 'or' operation between self and other's digits."""
3067 if context is None:
3068 context = getcontext()
3069 if not self._islogical() or not other._islogical():
3070 return context._raise_error(InvalidOperation)
3071
3072 # fill to context.prec
3073 (opa, opb) = self._fill_logical(context, self._int, other._int)
3074
3075 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003076 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3077 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003078
3079 def logical_xor(self, other, context=None):
3080 """Applies an 'xor' operation between self and other's digits."""
3081 if context is None:
3082 context = getcontext()
3083 if not self._islogical() or not other._islogical():
3084 return context._raise_error(InvalidOperation)
3085
3086 # fill to context.prec
3087 (opa, opb) = self._fill_logical(context, self._int, other._int)
3088
3089 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003090 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3091 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003092
3093 def max_mag(self, other, context=None):
3094 """Compares the values numerically with their sign ignored."""
3095 other = _convert_other(other, raiseit=True)
3096
Facundo Batista6c398da2007-09-17 17:30:13 +00003097 if context is None:
3098 context = getcontext()
3099
Facundo Batista353750c2007-09-13 18:13:15 +00003100 if self._is_special or other._is_special:
3101 # If one operand is a quiet NaN and the other is number, then the
3102 # number is always returned
3103 sn = self._isnan()
3104 on = other._isnan()
3105 if sn or on:
3106 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003107 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003108 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003109 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003110 return self._check_nans(other, context)
3111
3112 c = self.copy_abs().__cmp__(other.copy_abs())
3113 if c == 0:
3114 c = self.compare_total(other)
3115
3116 if c == -1:
3117 ans = other
3118 else:
3119 ans = self
3120
Facundo Batista353750c2007-09-13 18:13:15 +00003121 if context._rounding_decision == ALWAYS_ROUND:
3122 return ans._fix(context)
3123 return ans
3124
3125 def min_mag(self, other, context=None):
3126 """Compares the values numerically with their sign ignored."""
3127 other = _convert_other(other, raiseit=True)
3128
Facundo Batista6c398da2007-09-17 17:30:13 +00003129 if context is None:
3130 context = getcontext()
3131
Facundo Batista353750c2007-09-13 18:13:15 +00003132 if self._is_special or other._is_special:
3133 # If one operand is a quiet NaN and the other is number, then the
3134 # number is always returned
3135 sn = self._isnan()
3136 on = other._isnan()
3137 if sn or on:
3138 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003139 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003140 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003141 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003142 return self._check_nans(other, context)
3143
3144 c = self.copy_abs().__cmp__(other.copy_abs())
3145 if c == 0:
3146 c = self.compare_total(other)
3147
3148 if c == -1:
3149 ans = self
3150 else:
3151 ans = other
3152
Facundo Batista353750c2007-09-13 18:13:15 +00003153 if context._rounding_decision == ALWAYS_ROUND:
3154 return ans._fix(context)
3155 return ans
3156
3157 def next_minus(self, context=None):
3158 """Returns the largest representable number smaller than itself."""
3159 if context is None:
3160 context = getcontext()
3161
3162 ans = self._check_nans(context=context)
3163 if ans:
3164 return ans
3165
3166 if self._isinfinity() == -1:
3167 return negInf
3168 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003169 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003170
3171 context = context.copy()
3172 context._set_rounding(ROUND_FLOOR)
3173 context._ignore_all_flags()
3174 new_self = self._fix(context)
3175 if new_self != self:
3176 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003177 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3178 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003179
3180 def next_plus(self, context=None):
3181 """Returns the smallest representable number larger than itself."""
3182 if context is None:
3183 context = getcontext()
3184
3185 ans = self._check_nans(context=context)
3186 if ans:
3187 return ans
3188
3189 if self._isinfinity() == 1:
3190 return Inf
3191 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003192 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003193
3194 context = context.copy()
3195 context._set_rounding(ROUND_CEILING)
3196 context._ignore_all_flags()
3197 new_self = self._fix(context)
3198 if new_self != self:
3199 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003200 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3201 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003202
3203 def next_toward(self, other, context=None):
3204 """Returns the number closest to self, in the direction towards other.
3205
3206 The result is the closest representable number to self
3207 (excluding self) that is in the direction towards other,
3208 unless both have the same value. If the two operands are
3209 numerically equal, then the result is a copy of self with the
3210 sign set to be the same as the sign of other.
3211 """
3212 other = _convert_other(other, raiseit=True)
3213
3214 if context is None:
3215 context = getcontext()
3216
3217 ans = self._check_nans(other, context)
3218 if ans:
3219 return ans
3220
3221 comparison = self.__cmp__(other)
3222 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003223 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003224
3225 if comparison == -1:
3226 ans = self.next_plus(context)
3227 else: # comparison == 1
3228 ans = self.next_minus(context)
3229
3230 # decide which flags to raise using value of ans
3231 if ans._isinfinity():
3232 context._raise_error(Overflow,
3233 'Infinite result from next_toward',
3234 ans._sign)
3235 context._raise_error(Rounded)
3236 context._raise_error(Inexact)
3237 elif ans.adjusted() < context.Emin:
3238 context._raise_error(Underflow)
3239 context._raise_error(Subnormal)
3240 context._raise_error(Rounded)
3241 context._raise_error(Inexact)
3242 # if precision == 1 then we don't raise Clamped for a
3243 # result 0E-Etiny.
3244 if not ans:
3245 context._raise_error(Clamped)
3246
3247 return ans
3248
3249 def number_class(self, context=None):
3250 """Returns an indication of the class of self.
3251
3252 The class is one of the following strings:
3253 -sNaN
3254 -NaN
3255 -Infinity
3256 -Normal
3257 -Subnormal
3258 -Zero
3259 +Zero
3260 +Subnormal
3261 +Normal
3262 +Infinity
3263 """
3264 if self.is_snan():
3265 return "sNaN"
3266 if self.is_qnan():
3267 return "NaN"
3268 inf = self._isinfinity()
3269 if inf == 1:
3270 return "+Infinity"
3271 if inf == -1:
3272 return "-Infinity"
3273 if self.is_zero():
3274 if self._sign:
3275 return "-Zero"
3276 else:
3277 return "+Zero"
3278 if context is None:
3279 context = getcontext()
3280 if self.is_subnormal(context=context):
3281 if self._sign:
3282 return "-Subnormal"
3283 else:
3284 return "+Subnormal"
3285 # just a normal, regular, boring number, :)
3286 if self._sign:
3287 return "-Normal"
3288 else:
3289 return "+Normal"
3290
3291 def radix(self):
3292 """Just returns 10, as this is Decimal, :)"""
3293 return Decimal(10)
3294
3295 def rotate(self, other, context=None):
3296 """Returns a rotated copy of self, value-of-other times."""
3297 if context is None:
3298 context = getcontext()
3299
3300 ans = self._check_nans(other, context)
3301 if ans:
3302 return ans
3303
3304 if other._exp != 0:
3305 return context._raise_error(InvalidOperation)
3306 if not (-context.prec <= int(other) <= context.prec):
3307 return context._raise_error(InvalidOperation)
3308
3309 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003310 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003311
3312 # get values, pad if necessary
3313 torot = int(other)
3314 rotdig = self._int
3315 topad = context.prec - len(rotdig)
3316 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003317 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003318
3319 # let's rotate!
3320 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003321 return _dec_from_triple(self._sign,
3322 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003323
3324 def scaleb (self, other, context=None):
3325 """Returns self operand after adding the second value to its exp."""
3326 if context is None:
3327 context = getcontext()
3328
3329 ans = self._check_nans(other, context)
3330 if ans:
3331 return ans
3332
3333 if other._exp != 0:
3334 return context._raise_error(InvalidOperation)
3335 liminf = -2 * (context.Emax + context.prec)
3336 limsup = 2 * (context.Emax + context.prec)
3337 if not (liminf <= int(other) <= limsup):
3338 return context._raise_error(InvalidOperation)
3339
3340 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003341 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003342
Facundo Batista72bc54f2007-11-23 17:59:00 +00003343 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003344 d = d._fix(context)
3345 return d
3346
3347 def shift(self, other, context=None):
3348 """Returns a shifted copy of self, value-of-other times."""
3349 if context is None:
3350 context = getcontext()
3351
3352 ans = self._check_nans(other, context)
3353 if ans:
3354 return ans
3355
3356 if other._exp != 0:
3357 return context._raise_error(InvalidOperation)
3358 if not (-context.prec <= int(other) <= context.prec):
3359 return context._raise_error(InvalidOperation)
3360
3361 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003362 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003363
3364 # get values, pad if necessary
3365 torot = int(other)
3366 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003367 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003368 rotdig = self._int
3369 topad = context.prec - len(rotdig)
3370 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003371 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003372
3373 # let's shift!
3374 if torot < 0:
3375 rotated = rotdig[:torot]
3376 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003377 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003378 rotated = rotated[-context.prec:]
3379
Facundo Batista72bc54f2007-11-23 17:59:00 +00003380 return _dec_from_triple(self._sign,
3381 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003382
Facundo Batista59c58842007-04-10 12:58:45 +00003383 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003384 def __reduce__(self):
3385 return (self.__class__, (str(self),))
3386
3387 def __copy__(self):
3388 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003389 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003390 return self.__class__(str(self))
3391
3392 def __deepcopy__(self, memo):
3393 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003394 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003395 return self.__class__(str(self))
3396
Facundo Batista72bc54f2007-11-23 17:59:00 +00003397def _dec_from_triple(sign, coefficient, exponent, special=False):
3398 """Create a decimal instance directly, without any validation,
3399 normalization (e.g. removal of leading zeros) or argument
3400 conversion.
3401
3402 This function is for *internal use only*.
3403 """
3404
3405 self = object.__new__(Decimal)
3406 self._sign = sign
3407 self._int = coefficient
3408 self._exp = exponent
3409 self._is_special = special
3410
3411 return self
3412
Facundo Batista59c58842007-04-10 12:58:45 +00003413##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003414
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003415
3416# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003417rounding_functions = [name for name in Decimal.__dict__.keys()
3418 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003419for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003420 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003421 globalname = name[1:].upper()
3422 val = globals()[globalname]
3423 Decimal._pick_rounding_function[val] = name
3424
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003425del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003426
Nick Coghlanced12182006-09-02 03:54:17 +00003427class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003428 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003429
Nick Coghlanced12182006-09-02 03:54:17 +00003430 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003431 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003432 """
3433 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003434 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003435 def __enter__(self):
3436 self.saved_context = getcontext()
3437 setcontext(self.new_context)
3438 return self.new_context
3439 def __exit__(self, t, v, tb):
3440 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003441
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003442class Context(object):
3443 """Contains the context for a Decimal instance.
3444
3445 Contains:
3446 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003447 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003448 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003449 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003450 raised when it is caused. Otherwise, a value is
3451 substituted in.
3452 flags - When an exception is caused, flags[exception] is incremented.
3453 (Whether or not the trap_enabler is set)
3454 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003455 Emin - Minimum exponent
3456 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003457 capitals - If 1, 1*10^1 is printed as 1E+1.
3458 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003459 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003460 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003461
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003462 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003463 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003464 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003465 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003466 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003467 _ignored_flags=None):
3468 if flags is None:
3469 flags = []
3470 if _ignored_flags is None:
3471 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003472 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003473 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003474 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003475 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003476 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003477 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003478 for name, val in locals().items():
3479 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003480 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003481 else:
3482 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003483 del self.self
3484
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003485 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003486 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003487 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003488 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3489 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3490 % vars(self))
3491 names = [f.__name__ for f, v in self.flags.items() if v]
3492 s.append('flags=[' + ', '.join(names) + ']')
3493 names = [t.__name__ for t, v in self.traps.items() if v]
3494 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003495 return ', '.join(s) + ')'
3496
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003497 def clear_flags(self):
3498 """Reset all flags to zero"""
3499 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003500 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003501
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003502 def _shallow_copy(self):
3503 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003504 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003505 self._rounding_decision, self.Emin, self.Emax,
3506 self.capitals, self._clamp, self._ignored_flags)
3507 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003508
3509 def copy(self):
3510 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003511 nc = Context(self.prec, self.rounding, self.traps.copy(),
3512 self.flags.copy(), self._rounding_decision, self.Emin,
3513 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003514 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003515 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003516
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003517 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003518 """Handles an error
3519
3520 If the flag is in _ignored_flags, returns the default response.
3521 Otherwise, it increments the flag, then, if the corresponding
3522 trap_enabler is set, it reaises the exception. Otherwise, it returns
3523 the default value after incrementing the flag.
3524 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003525 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003526 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003527 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003528 return error().handle(self, *args)
3529
3530 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003531 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003532 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003533 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003534
3535 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003536 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003537 raise error, explanation
3538
3539 def _ignore_all_flags(self):
3540 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003541 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003542
3543 def _ignore_flags(self, *flags):
3544 """Ignore the flags, if they are raised"""
3545 # Do not mutate-- This way, copies of a context leave the original
3546 # alone.
3547 self._ignored_flags = (self._ignored_flags + list(flags))
3548 return list(flags)
3549
3550 def _regard_flags(self, *flags):
3551 """Stop ignoring the flags, if they are raised"""
3552 if flags and isinstance(flags[0], (tuple,list)):
3553 flags = flags[0]
3554 for flag in flags:
3555 self._ignored_flags.remove(flag)
3556
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003557 def __hash__(self):
3558 """A Context cannot be hashed."""
3559 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003560 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003561
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003562 def Etiny(self):
3563 """Returns Etiny (= Emin - prec + 1)"""
3564 return int(self.Emin - self.prec + 1)
3565
3566 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003567 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003568 return int(self.Emax - self.prec + 1)
3569
3570 def _set_rounding_decision(self, type):
3571 """Sets the rounding decision.
3572
3573 Sets the rounding decision, and returns the current (previous)
3574 rounding decision. Often used like:
3575
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003576 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003577 # That so you don't change the calling context
3578 # if an error occurs in the middle (say DivisionImpossible is raised).
3579
3580 rounding = context._set_rounding_decision(NEVER_ROUND)
3581 instance = instance / Decimal(2)
3582 context._set_rounding_decision(rounding)
3583
3584 This will make it not round for that operation.
3585 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003586
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003587 rounding = self._rounding_decision
3588 self._rounding_decision = type
3589 return rounding
3590
3591 def _set_rounding(self, type):
3592 """Sets the rounding type.
3593
3594 Sets the rounding type, and returns the current (previous)
3595 rounding type. Often used like:
3596
3597 context = context.copy()
3598 # so you don't change the calling context
3599 # if an error occurs in the middle.
3600 rounding = context._set_rounding(ROUND_UP)
3601 val = self.__sub__(other, context=context)
3602 context._set_rounding(rounding)
3603
3604 This will make it round up for that operation.
3605 """
3606 rounding = self.rounding
3607 self.rounding= type
3608 return rounding
3609
Raymond Hettingerfed52962004-07-14 15:41:57 +00003610 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003611 """Creates a new Decimal instance but using self as context."""
3612 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003613 if d._isnan() and len(d._int) > self.prec - self._clamp:
3614 return self._raise_error(ConversionSyntax,
3615 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003616 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003617
Facundo Batista59c58842007-04-10 12:58:45 +00003618 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003619 def abs(self, a):
3620 """Returns the absolute value of the operand.
3621
3622 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003623 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003624 the plus operation on the operand.
3625
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003626 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003627 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003628 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003629 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003630 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003631 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003632 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003633 Decimal("101.5")
3634 """
3635 return a.__abs__(context=self)
3636
3637 def add(self, a, b):
3638 """Return the sum of the two operands.
3639
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003640 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003641 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003642 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003643 Decimal("1.02E+4")
3644 """
3645 return a.__add__(b, context=self)
3646
3647 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003648 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003649
Facundo Batista353750c2007-09-13 18:13:15 +00003650 def canonical(self, a):
3651 """Returns the same Decimal object.
3652
3653 As we do not have different encodings for the same number, the
3654 received object already is in its canonical form.
3655
3656 >>> ExtendedContext.canonical(Decimal('2.50'))
3657 Decimal("2.50")
3658 """
3659 return a.canonical(context=self)
3660
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003661 def compare(self, a, b):
3662 """Compares values numerically.
3663
3664 If the signs of the operands differ, a value representing each operand
3665 ('-1' if the operand is less than zero, '0' if the operand is zero or
3666 negative zero, or '1' if the operand is greater than zero) is used in
3667 place of that operand for the comparison instead of the actual
3668 operand.
3669
3670 The comparison is then effected by subtracting the second operand from
3671 the first and then returning a value according to the result of the
3672 subtraction: '-1' if the result is less than zero, '0' if the result is
3673 zero or negative zero, or '1' if the result is greater than zero.
3674
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003675 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003676 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003677 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003678 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003679 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003680 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003681 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003682 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003683 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003684 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003685 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003686 Decimal("-1")
3687 """
3688 return a.compare(b, context=self)
3689
Facundo Batista353750c2007-09-13 18:13:15 +00003690 def compare_signal(self, a, b):
3691 """Compares the values of the two operands numerically.
3692
3693 It's pretty much like compare(), but all NaNs signal, with signaling
3694 NaNs taking precedence over quiet NaNs.
3695
3696 >>> c = ExtendedContext
3697 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3698 Decimal("-1")
3699 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3700 Decimal("0")
3701 >>> c.flags[InvalidOperation] = 0
3702 >>> print c.flags[InvalidOperation]
3703 0
3704 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3705 Decimal("NaN")
3706 >>> print c.flags[InvalidOperation]
3707 1
3708 >>> c.flags[InvalidOperation] = 0
3709 >>> print c.flags[InvalidOperation]
3710 0
3711 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3712 Decimal("NaN")
3713 >>> print c.flags[InvalidOperation]
3714 1
3715 """
3716 return a.compare_signal(b, context=self)
3717
3718 def compare_total(self, a, b):
3719 """Compares two operands using their abstract representation.
3720
3721 This is not like the standard compare, which use their numerical
3722 value. Note that a total ordering is defined for all possible abstract
3723 representations.
3724
3725 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3726 Decimal("-1")
3727 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3728 Decimal("-1")
3729 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3730 Decimal("-1")
3731 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3732 Decimal("0")
3733 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3734 Decimal("1")
3735 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3736 Decimal("-1")
3737 """
3738 return a.compare_total(b)
3739
3740 def compare_total_mag(self, a, b):
3741 """Compares two operands using their abstract representation ignoring sign.
3742
3743 Like compare_total, but with operand's sign ignored and assumed to be 0.
3744 """
3745 return a.compare_total_mag(b)
3746
3747 def copy_abs(self, a):
3748 """Returns a copy of the operand with the sign set to 0.
3749
3750 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3751 Decimal("2.1")
3752 >>> ExtendedContext.copy_abs(Decimal('-100'))
3753 Decimal("100")
3754 """
3755 return a.copy_abs()
3756
3757 def copy_decimal(self, a):
3758 """Returns a copy of the decimal objet.
3759
3760 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3761 Decimal("2.1")
3762 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3763 Decimal("-1.00")
3764 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003765 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003766
3767 def copy_negate(self, a):
3768 """Returns a copy of the operand with the sign inverted.
3769
3770 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3771 Decimal("-101.5")
3772 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3773 Decimal("101.5")
3774 """
3775 return a.copy_negate()
3776
3777 def copy_sign(self, a, b):
3778 """Copies the second operand's sign to the first one.
3779
3780 In detail, it returns a copy of the first operand with the sign
3781 equal to the sign of the second operand.
3782
3783 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3784 Decimal("1.50")
3785 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3786 Decimal("1.50")
3787 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3788 Decimal("-1.50")
3789 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3790 Decimal("-1.50")
3791 """
3792 return a.copy_sign(b)
3793
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003794 def divide(self, a, b):
3795 """Decimal division in a specified context.
3796
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003797 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003798 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003799 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003800 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003801 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003802 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003803 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003804 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003805 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003806 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003807 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003808 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003809 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003810 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003811 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003812 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003813 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003814 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003815 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003816 Decimal("1.20E+6")
3817 """
3818 return a.__div__(b, context=self)
3819
3820 def divide_int(self, a, b):
3821 """Divides two numbers and returns the integer part of the result.
3822
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003823 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003824 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003825 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003826 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003827 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003828 Decimal("3")
3829 """
3830 return a.__floordiv__(b, context=self)
3831
3832 def divmod(self, a, b):
3833 return a.__divmod__(b, context=self)
3834
Facundo Batista353750c2007-09-13 18:13:15 +00003835 def exp(self, a):
3836 """Returns e ** a.
3837
3838 >>> c = ExtendedContext.copy()
3839 >>> c.Emin = -999
3840 >>> c.Emax = 999
3841 >>> c.exp(Decimal('-Infinity'))
3842 Decimal("0")
3843 >>> c.exp(Decimal('-1'))
3844 Decimal("0.367879441")
3845 >>> c.exp(Decimal('0'))
3846 Decimal("1")
3847 >>> c.exp(Decimal('1'))
3848 Decimal("2.71828183")
3849 >>> c.exp(Decimal('0.693147181'))
3850 Decimal("2.00000000")
3851 >>> c.exp(Decimal('+Infinity'))
3852 Decimal("Infinity")
3853 """
3854 return a.exp(context=self)
3855
3856 def fma(self, a, b, c):
3857 """Returns a multiplied by b, plus c.
3858
3859 The first two operands are multiplied together, using multiply,
3860 the third operand is then added to the result of that
3861 multiplication, using add, all with only one final rounding.
3862
3863 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3864 Decimal("22")
3865 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3866 Decimal("-8")
3867 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3868 Decimal("1.38435736E+12")
3869 """
3870 return a.fma(b, c, context=self)
3871
3872 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003873 """Return True if the operand is canonical; otherwise return False.
3874
3875 Currently, the encoding of a Decimal instance is always
3876 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00003877
3878 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003879 True
Facundo Batista353750c2007-09-13 18:13:15 +00003880 """
Facundo Batista1a191df2007-10-02 17:01:24 +00003881 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00003882
3883 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003884 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003885
Facundo Batista1a191df2007-10-02 17:01:24 +00003886 A Decimal instance is considered finite if it is neither
3887 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00003888
3889 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003890 True
Facundo Batista353750c2007-09-13 18:13:15 +00003891 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003892 True
Facundo Batista353750c2007-09-13 18:13:15 +00003893 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003894 True
Facundo Batista353750c2007-09-13 18:13:15 +00003895 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003896 False
Facundo Batista353750c2007-09-13 18:13:15 +00003897 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003898 False
Facundo Batista353750c2007-09-13 18:13:15 +00003899 """
3900 return a.is_finite()
3901
3902 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003903 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003904
3905 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003906 False
Facundo Batista353750c2007-09-13 18:13:15 +00003907 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003908 True
Facundo Batista353750c2007-09-13 18:13:15 +00003909 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003910 False
Facundo Batista353750c2007-09-13 18:13:15 +00003911 """
3912 return a.is_infinite()
3913
3914 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003915 """Return True if the operand is a qNaN or sNaN;
3916 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003917
3918 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003919 False
Facundo Batista353750c2007-09-13 18:13:15 +00003920 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003921 True
Facundo Batista353750c2007-09-13 18:13:15 +00003922 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003923 True
Facundo Batista353750c2007-09-13 18:13:15 +00003924 """
3925 return a.is_nan()
3926
3927 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003928 """Return True if the operand is a normal number;
3929 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003930
3931 >>> c = ExtendedContext.copy()
3932 >>> c.Emin = -999
3933 >>> c.Emax = 999
3934 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003935 True
Facundo Batista353750c2007-09-13 18:13:15 +00003936 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003937 False
Facundo Batista353750c2007-09-13 18:13:15 +00003938 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003939 False
Facundo Batista353750c2007-09-13 18:13:15 +00003940 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003941 False
Facundo Batista353750c2007-09-13 18:13:15 +00003942 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003943 False
Facundo Batista353750c2007-09-13 18:13:15 +00003944 """
3945 return a.is_normal(context=self)
3946
3947 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003948 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003949
3950 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003951 False
Facundo Batista353750c2007-09-13 18:13:15 +00003952 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003953 True
Facundo Batista353750c2007-09-13 18:13:15 +00003954 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003955 False
Facundo Batista353750c2007-09-13 18:13:15 +00003956 """
3957 return a.is_qnan()
3958
3959 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003960 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003961
3962 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003963 False
Facundo Batista353750c2007-09-13 18:13:15 +00003964 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003965 True
Facundo Batista353750c2007-09-13 18:13:15 +00003966 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003967 True
Facundo Batista353750c2007-09-13 18:13:15 +00003968 """
3969 return a.is_signed()
3970
3971 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003972 """Return True if the operand is a signaling NaN;
3973 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003974
3975 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003976 False
Facundo Batista353750c2007-09-13 18:13:15 +00003977 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003978 False
Facundo Batista353750c2007-09-13 18:13:15 +00003979 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003980 True
Facundo Batista353750c2007-09-13 18:13:15 +00003981 """
3982 return a.is_snan()
3983
3984 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003985 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003986
3987 >>> c = ExtendedContext.copy()
3988 >>> c.Emin = -999
3989 >>> c.Emax = 999
3990 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003991 False
Facundo Batista353750c2007-09-13 18:13:15 +00003992 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003993 True
Facundo Batista353750c2007-09-13 18:13:15 +00003994 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003995 False
Facundo Batista353750c2007-09-13 18:13:15 +00003996 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003997 False
Facundo Batista353750c2007-09-13 18:13:15 +00003998 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003999 False
Facundo Batista353750c2007-09-13 18:13:15 +00004000 """
4001 return a.is_subnormal(context=self)
4002
4003 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004004 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004005
4006 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004007 True
Facundo Batista353750c2007-09-13 18:13:15 +00004008 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004009 False
Facundo Batista353750c2007-09-13 18:13:15 +00004010 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004011 True
Facundo Batista353750c2007-09-13 18:13:15 +00004012 """
4013 return a.is_zero()
4014
4015 def ln(self, a):
4016 """Returns the natural (base e) logarithm of the operand.
4017
4018 >>> c = ExtendedContext.copy()
4019 >>> c.Emin = -999
4020 >>> c.Emax = 999
4021 >>> c.ln(Decimal('0'))
4022 Decimal("-Infinity")
4023 >>> c.ln(Decimal('1.000'))
4024 Decimal("0")
4025 >>> c.ln(Decimal('2.71828183'))
4026 Decimal("1.00000000")
4027 >>> c.ln(Decimal('10'))
4028 Decimal("2.30258509")
4029 >>> c.ln(Decimal('+Infinity'))
4030 Decimal("Infinity")
4031 """
4032 return a.ln(context=self)
4033
4034 def log10(self, a):
4035 """Returns the base 10 logarithm of the operand.
4036
4037 >>> c = ExtendedContext.copy()
4038 >>> c.Emin = -999
4039 >>> c.Emax = 999
4040 >>> c.log10(Decimal('0'))
4041 Decimal("-Infinity")
4042 >>> c.log10(Decimal('0.001'))
4043 Decimal("-3")
4044 >>> c.log10(Decimal('1.000'))
4045 Decimal("0")
4046 >>> c.log10(Decimal('2'))
4047 Decimal("0.301029996")
4048 >>> c.log10(Decimal('10'))
4049 Decimal("1")
4050 >>> c.log10(Decimal('70'))
4051 Decimal("1.84509804")
4052 >>> c.log10(Decimal('+Infinity'))
4053 Decimal("Infinity")
4054 """
4055 return a.log10(context=self)
4056
4057 def logb(self, a):
4058 """ Returns the exponent of the magnitude of the operand's MSD.
4059
4060 The result is the integer which is the exponent of the magnitude
4061 of the most significant digit of the operand (as though the
4062 operand were truncated to a single digit while maintaining the
4063 value of that digit and without limiting the resulting exponent).
4064
4065 >>> ExtendedContext.logb(Decimal('250'))
4066 Decimal("2")
4067 >>> ExtendedContext.logb(Decimal('2.50'))
4068 Decimal("0")
4069 >>> ExtendedContext.logb(Decimal('0.03'))
4070 Decimal("-2")
4071 >>> ExtendedContext.logb(Decimal('0'))
4072 Decimal("-Infinity")
4073 """
4074 return a.logb(context=self)
4075
4076 def logical_and(self, a, b):
4077 """Applies the logical operation 'and' between each operand's digits.
4078
4079 The operands must be both logical numbers.
4080
4081 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4082 Decimal("0")
4083 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4084 Decimal("0")
4085 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4086 Decimal("0")
4087 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4088 Decimal("1")
4089 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4090 Decimal("1000")
4091 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4092 Decimal("10")
4093 """
4094 return a.logical_and(b, context=self)
4095
4096 def logical_invert(self, a):
4097 """Invert all the digits in the operand.
4098
4099 The operand must be a logical number.
4100
4101 >>> ExtendedContext.logical_invert(Decimal('0'))
4102 Decimal("111111111")
4103 >>> ExtendedContext.logical_invert(Decimal('1'))
4104 Decimal("111111110")
4105 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4106 Decimal("0")
4107 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4108 Decimal("10101010")
4109 """
4110 return a.logical_invert(context=self)
4111
4112 def logical_or(self, a, b):
4113 """Applies the logical operation 'or' between each operand's digits.
4114
4115 The operands must be both logical numbers.
4116
4117 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4118 Decimal("0")
4119 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4120 Decimal("1")
4121 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4122 Decimal("1")
4123 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4124 Decimal("1")
4125 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4126 Decimal("1110")
4127 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4128 Decimal("1110")
4129 """
4130 return a.logical_or(b, context=self)
4131
4132 def logical_xor(self, a, b):
4133 """Applies the logical operation 'xor' between each operand's digits.
4134
4135 The operands must be both logical numbers.
4136
4137 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4138 Decimal("0")
4139 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4140 Decimal("1")
4141 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4142 Decimal("1")
4143 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4144 Decimal("0")
4145 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4146 Decimal("110")
4147 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4148 Decimal("1101")
4149 """
4150 return a.logical_xor(b, context=self)
4151
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004152 def max(self, a,b):
4153 """max compares two values numerically and returns the maximum.
4154
4155 If either operand is a NaN then the general rules apply.
4156 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004157 operation. If they are numerically equal then the left-hand operand
4158 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004159 infinity) of the two operands is chosen as the result.
4160
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004161 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004162 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004163 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004164 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004165 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004166 Decimal("1")
4167 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4168 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004169 """
4170 return a.max(b, context=self)
4171
Facundo Batista353750c2007-09-13 18:13:15 +00004172 def max_mag(self, a, b):
4173 """Compares the values numerically with their sign ignored."""
4174 return a.max_mag(b, context=self)
4175
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004176 def min(self, a,b):
4177 """min compares two values numerically and returns the minimum.
4178
4179 If either operand is a NaN then the general rules apply.
4180 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004181 operation. If they are numerically equal then the left-hand operand
4182 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004183 infinity) of the two operands is chosen as the result.
4184
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004185 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004186 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004187 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004188 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004189 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004190 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004191 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4192 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004193 """
4194 return a.min(b, context=self)
4195
Facundo Batista353750c2007-09-13 18:13:15 +00004196 def min_mag(self, a, b):
4197 """Compares the values numerically with their sign ignored."""
4198 return a.min_mag(b, context=self)
4199
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004200 def minus(self, a):
4201 """Minus corresponds to unary prefix minus in Python.
4202
4203 The operation is evaluated using the same rules as subtract; the
4204 operation minus(a) is calculated as subtract('0', a) where the '0'
4205 has the same exponent as the operand.
4206
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004207 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004208 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004209 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004210 Decimal("1.3")
4211 """
4212 return a.__neg__(context=self)
4213
4214 def multiply(self, a, b):
4215 """multiply multiplies two operands.
4216
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004217 If either operand is a special value then the general rules apply.
4218 Otherwise, the operands are multiplied together ('long multiplication'),
4219 resulting in a number which may be as long as the sum of the lengths
4220 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004221
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004222 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004223 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004224 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004225 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004226 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004227 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004228 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004229 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004230 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004231 Decimal("4.28135971E+11")
4232 """
4233 return a.__mul__(b, context=self)
4234
Facundo Batista353750c2007-09-13 18:13:15 +00004235 def next_minus(self, a):
4236 """Returns the largest representable number smaller than a.
4237
4238 >>> c = ExtendedContext.copy()
4239 >>> c.Emin = -999
4240 >>> c.Emax = 999
4241 >>> ExtendedContext.next_minus(Decimal('1'))
4242 Decimal("0.999999999")
4243 >>> c.next_minus(Decimal('1E-1007'))
4244 Decimal("0E-1007")
4245 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4246 Decimal("-1.00000004")
4247 >>> c.next_minus(Decimal('Infinity'))
4248 Decimal("9.99999999E+999")
4249 """
4250 return a.next_minus(context=self)
4251
4252 def next_plus(self, a):
4253 """Returns the smallest representable number larger than a.
4254
4255 >>> c = ExtendedContext.copy()
4256 >>> c.Emin = -999
4257 >>> c.Emax = 999
4258 >>> ExtendedContext.next_plus(Decimal('1'))
4259 Decimal("1.00000001")
4260 >>> c.next_plus(Decimal('-1E-1007'))
4261 Decimal("-0E-1007")
4262 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4263 Decimal("-1.00000002")
4264 >>> c.next_plus(Decimal('-Infinity'))
4265 Decimal("-9.99999999E+999")
4266 """
4267 return a.next_plus(context=self)
4268
4269 def next_toward(self, a, b):
4270 """Returns the number closest to a, in direction towards b.
4271
4272 The result is the closest representable number from the first
4273 operand (but not the first operand) that is in the direction
4274 towards the second operand, unless the operands have the same
4275 value.
4276
4277 >>> c = ExtendedContext.copy()
4278 >>> c.Emin = -999
4279 >>> c.Emax = 999
4280 >>> c.next_toward(Decimal('1'), Decimal('2'))
4281 Decimal("1.00000001")
4282 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4283 Decimal("-0E-1007")
4284 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4285 Decimal("-1.00000002")
4286 >>> c.next_toward(Decimal('1'), Decimal('0'))
4287 Decimal("0.999999999")
4288 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4289 Decimal("0E-1007")
4290 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4291 Decimal("-1.00000004")
4292 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4293 Decimal("-0.00")
4294 """
4295 return a.next_toward(b, context=self)
4296
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004297 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004298 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004299
4300 Essentially a plus operation with all trailing zeros removed from the
4301 result.
4302
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004303 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004304 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004305 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004306 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004307 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004308 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004309 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004310 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004311 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004312 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004313 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004314 Decimal("0")
4315 """
4316 return a.normalize(context=self)
4317
Facundo Batista353750c2007-09-13 18:13:15 +00004318 def number_class(self, a):
4319 """Returns an indication of the class of the operand.
4320
4321 The class is one of the following strings:
4322 -sNaN
4323 -NaN
4324 -Infinity
4325 -Normal
4326 -Subnormal
4327 -Zero
4328 +Zero
4329 +Subnormal
4330 +Normal
4331 +Infinity
4332
4333 >>> c = Context(ExtendedContext)
4334 >>> c.Emin = -999
4335 >>> c.Emax = 999
4336 >>> c.number_class(Decimal('Infinity'))
4337 '+Infinity'
4338 >>> c.number_class(Decimal('1E-10'))
4339 '+Normal'
4340 >>> c.number_class(Decimal('2.50'))
4341 '+Normal'
4342 >>> c.number_class(Decimal('0.1E-999'))
4343 '+Subnormal'
4344 >>> c.number_class(Decimal('0'))
4345 '+Zero'
4346 >>> c.number_class(Decimal('-0'))
4347 '-Zero'
4348 >>> c.number_class(Decimal('-0.1E-999'))
4349 '-Subnormal'
4350 >>> c.number_class(Decimal('-1E-10'))
4351 '-Normal'
4352 >>> c.number_class(Decimal('-2.50'))
4353 '-Normal'
4354 >>> c.number_class(Decimal('-Infinity'))
4355 '-Infinity'
4356 >>> c.number_class(Decimal('NaN'))
4357 'NaN'
4358 >>> c.number_class(Decimal('-NaN'))
4359 'NaN'
4360 >>> c.number_class(Decimal('sNaN'))
4361 'sNaN'
4362 """
4363 return a.number_class(context=self)
4364
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004365 def plus(self, a):
4366 """Plus corresponds to unary prefix plus in Python.
4367
4368 The operation is evaluated using the same rules as add; the
4369 operation plus(a) is calculated as add('0', a) where the '0'
4370 has the same exponent as the operand.
4371
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004372 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004373 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004374 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004375 Decimal("-1.3")
4376 """
4377 return a.__pos__(context=self)
4378
4379 def power(self, a, b, modulo=None):
4380 """Raises a to the power of b, to modulo if given.
4381
Facundo Batista353750c2007-09-13 18:13:15 +00004382 With two arguments, compute a**b. If a is negative then b
4383 must be integral. The result will be inexact unless b is
4384 integral and the result is finite and can be expressed exactly
4385 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004386
Facundo Batista353750c2007-09-13 18:13:15 +00004387 With three arguments, compute (a**b) % modulo. For the
4388 three argument form, the following restrictions on the
4389 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004390
Facundo Batista353750c2007-09-13 18:13:15 +00004391 - all three arguments must be integral
4392 - b must be nonnegative
4393 - at least one of a or b must be nonzero
4394 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004395
Facundo Batista353750c2007-09-13 18:13:15 +00004396 The result of pow(a, b, modulo) is identical to the result
4397 that would be obtained by computing (a**b) % modulo with
4398 unbounded precision, but is computed more efficiently. It is
4399 always exact.
4400
4401 >>> c = ExtendedContext.copy()
4402 >>> c.Emin = -999
4403 >>> c.Emax = 999
4404 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004405 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004406 >>> c.power(Decimal('-2'), Decimal('3'))
4407 Decimal("-8")
4408 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004409 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004410 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004411 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004412 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4413 Decimal("2.00000000")
4414 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004415 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004416 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004417 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004418 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004419 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004420 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004421 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004422 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004423 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004424 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004425 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004426 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004427 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004428 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004429 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004430
4431 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4432 Decimal("11")
4433 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4434 Decimal("-11")
4435 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4436 Decimal("1")
4437 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4438 Decimal("11")
4439 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4440 Decimal("11729830")
4441 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4442 Decimal("-0")
4443 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4444 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004445 """
4446 return a.__pow__(b, modulo, context=self)
4447
4448 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004449 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004450
4451 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004452 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004453 exponent is being increased), multiplied by a positive power of ten (if
4454 the exponent is being decreased), or is unchanged (if the exponent is
4455 already equal to that of the right-hand operand).
4456
4457 Unlike other operations, if the length of the coefficient after the
4458 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004459 operation condition is raised. This guarantees that, unless there is
4460 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004461 equal to that of the right-hand operand.
4462
4463 Also unlike other operations, quantize will never raise Underflow, even
4464 if the result is subnormal and inexact.
4465
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004466 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004467 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004468 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004469 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004470 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004471 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004472 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004473 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004474 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004475 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004476 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004477 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004478 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004479 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004480 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004481 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004482 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004483 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004484 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004485 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004486 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004487 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004488 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004489 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004490 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004491 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004492 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004493 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004494 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004495 Decimal("2E+2")
4496 """
4497 return a.quantize(b, context=self)
4498
Facundo Batista353750c2007-09-13 18:13:15 +00004499 def radix(self):
4500 """Just returns 10, as this is Decimal, :)
4501
4502 >>> ExtendedContext.radix()
4503 Decimal("10")
4504 """
4505 return Decimal(10)
4506
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004507 def remainder(self, a, b):
4508 """Returns the remainder from integer division.
4509
4510 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004511 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004512 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004513 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004514
4515 This operation will fail under the same conditions as integer division
4516 (that is, if integer division on the same two operands would fail, the
4517 remainder cannot be calculated).
4518
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004519 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004520 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004521 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004522 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004523 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004524 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004525 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004526 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004527 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004528 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004529 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004530 Decimal("1.0")
4531 """
4532 return a.__mod__(b, context=self)
4533
4534 def remainder_near(self, a, b):
4535 """Returns to be "a - b * n", where n is the integer nearest the exact
4536 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004537 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004538 sign of a.
4539
4540 This operation will fail under the same conditions as integer division
4541 (that is, if integer division on the same two operands would fail, the
4542 remainder cannot be calculated).
4543
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004544 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004545 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004546 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004547 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004548 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004549 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004550 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004551 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004552 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004553 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004554 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004555 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004556 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004557 Decimal("-0.3")
4558 """
4559 return a.remainder_near(b, context=self)
4560
Facundo Batista353750c2007-09-13 18:13:15 +00004561 def rotate(self, a, b):
4562 """Returns a rotated copy of a, b times.
4563
4564 The coefficient of the result is a rotated copy of the digits in
4565 the coefficient of the first operand. The number of places of
4566 rotation is taken from the absolute value of the second operand,
4567 with the rotation being to the left if the second operand is
4568 positive or to the right otherwise.
4569
4570 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4571 Decimal("400000003")
4572 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4573 Decimal("12")
4574 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4575 Decimal("891234567")
4576 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4577 Decimal("123456789")
4578 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4579 Decimal("345678912")
4580 """
4581 return a.rotate(b, context=self)
4582
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004583 def same_quantum(self, a, b):
4584 """Returns True if the two operands have the same exponent.
4585
4586 The result is never affected by either the sign or the coefficient of
4587 either operand.
4588
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004589 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004590 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004591 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004592 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004593 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004594 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004595 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004596 True
4597 """
4598 return a.same_quantum(b)
4599
Facundo Batista353750c2007-09-13 18:13:15 +00004600 def scaleb (self, a, b):
4601 """Returns the first operand after adding the second value its exp.
4602
4603 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4604 Decimal("0.0750")
4605 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4606 Decimal("7.50")
4607 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4608 Decimal("7.50E+3")
4609 """
4610 return a.scaleb (b, context=self)
4611
4612 def shift(self, a, b):
4613 """Returns a shifted copy of a, b times.
4614
4615 The coefficient of the result is a shifted copy of the digits
4616 in the coefficient of the first operand. The number of places
4617 to shift is taken from the absolute value of the second operand,
4618 with the shift being to the left if the second operand is
4619 positive or to the right otherwise. Digits shifted into the
4620 coefficient are zeros.
4621
4622 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4623 Decimal("400000000")
4624 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4625 Decimal("0")
4626 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4627 Decimal("1234567")
4628 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4629 Decimal("123456789")
4630 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4631 Decimal("345678900")
4632 """
4633 return a.shift(b, context=self)
4634
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004635 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004636 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004637
4638 If the result must be inexact, it is rounded using the round-half-even
4639 algorithm.
4640
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004641 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004642 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004643 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004644 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004645 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004646 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004647 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004648 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004649 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004650 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004651 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004652 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004653 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004654 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004655 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004656 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004657 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004658 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004659 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004660 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004661 """
4662 return a.sqrt(context=self)
4663
4664 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004665 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004666
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004667 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004668 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004669 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004670 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004671 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004672 Decimal("-0.77")
4673 """
4674 return a.__sub__(b, context=self)
4675
4676 def to_eng_string(self, a):
4677 """Converts a number to a string, using scientific notation.
4678
4679 The operation is not affected by the context.
4680 """
4681 return a.to_eng_string(context=self)
4682
4683 def to_sci_string(self, a):
4684 """Converts a number to a string, using scientific notation.
4685
4686 The operation is not affected by the context.
4687 """
4688 return a.__str__(context=self)
4689
Facundo Batista353750c2007-09-13 18:13:15 +00004690 def to_integral_exact(self, a):
4691 """Rounds to an integer.
4692
4693 When the operand has a negative exponent, the result is the same
4694 as using the quantize() operation using the given operand as the
4695 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4696 of the operand as the precision setting; Inexact and Rounded flags
4697 are allowed in this operation. The rounding mode is taken from the
4698 context.
4699
4700 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4701 Decimal("2")
4702 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4703 Decimal("100")
4704 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4705 Decimal("100")
4706 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4707 Decimal("102")
4708 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4709 Decimal("-102")
4710 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4711 Decimal("1.0E+6")
4712 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4713 Decimal("7.89E+77")
4714 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4715 Decimal("-Infinity")
4716 """
4717 return a.to_integral_exact(context=self)
4718
4719 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004720 """Rounds to an integer.
4721
4722 When the operand has a negative exponent, the result is the same
4723 as using the quantize() operation using the given operand as the
4724 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4725 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004726 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004727
Facundo Batista353750c2007-09-13 18:13:15 +00004728 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004729 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004730 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004731 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004732 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004733 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004734 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004735 Decimal("102")
Facundo Batista353750c2007-09-13 18:13:15 +00004736 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004737 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004738 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004739 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004740 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004741 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004742 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004743 Decimal("-Infinity")
4744 """
Facundo Batista353750c2007-09-13 18:13:15 +00004745 return a.to_integral_value(context=self)
4746
4747 # the method name changed, but we provide also the old one, for compatibility
4748 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004749
4750class _WorkRep(object):
4751 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004752 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004753 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004754 # exp: None, int, or string
4755
4756 def __init__(self, value=None):
4757 if value is None:
4758 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004759 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004760 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004761 elif isinstance(value, Decimal):
4762 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004763 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004764 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004765 else:
4766 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004767 self.sign = value[0]
4768 self.int = value[1]
4769 self.exp = value[2]
4770
4771 def __repr__(self):
4772 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4773
4774 __str__ = __repr__
4775
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004776
4777
4778def _normalize(op1, op2, shouldround = 0, prec = 0):
4779 """Normalizes op1, op2 to have the same exp and length of coefficient.
4780
4781 Done during addition.
4782 """
Facundo Batista353750c2007-09-13 18:13:15 +00004783 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004784 tmp = op2
4785 other = op1
4786 else:
4787 tmp = op1
4788 other = op2
4789
Facundo Batista353750c2007-09-13 18:13:15 +00004790 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4791 # Then adding 10**exp to tmp has the same effect (after rounding)
4792 # as adding any positive quantity smaller than 10**exp; similarly
4793 # for subtraction. So if other is smaller than 10**exp we replace
4794 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4795 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004796 tmp_len = len(str(tmp.int))
4797 other_len = len(str(other.int))
Facundo Batista353750c2007-09-13 18:13:15 +00004798 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4799 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004800 other.int = 1
Facundo Batista353750c2007-09-13 18:13:15 +00004801 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004802
Facundo Batista353750c2007-09-13 18:13:15 +00004803 tmp.int *= 10 ** (tmp.exp - other.exp)
4804 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004805 return op1, op2
4806
Facundo Batista353750c2007-09-13 18:13:15 +00004807##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4808
4809# This function from Tim Peters was taken from here:
4810# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4811# The correction being in the function definition is for speed, and
4812# the whole function is not resolved with math.log because of avoiding
4813# the use of floats.
4814def _nbits(n, correction = {
4815 '0': 4, '1': 3, '2': 2, '3': 2,
4816 '4': 1, '5': 1, '6': 1, '7': 1,
4817 '8': 0, '9': 0, 'a': 0, 'b': 0,
4818 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4819 """Number of bits in binary representation of the positive integer n,
4820 or 0 if n == 0.
4821 """
4822 if n < 0:
4823 raise ValueError("The argument to _nbits should be nonnegative.")
4824 hex_n = "%x" % n
4825 return 4*len(hex_n) - correction[hex_n[0]]
4826
4827def _sqrt_nearest(n, a):
4828 """Closest integer to the square root of the positive integer n. a is
4829 an initial approximation to the square root. Any positive integer
4830 will do for a, but the closer a is to the square root of n the
4831 faster convergence will be.
4832
4833 """
4834 if n <= 0 or a <= 0:
4835 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4836
4837 b=0
4838 while a != b:
4839 b, a = a, a--n//a>>1
4840 return a
4841
4842def _rshift_nearest(x, shift):
4843 """Given an integer x and a nonnegative integer shift, return closest
4844 integer to x / 2**shift; use round-to-even in case of a tie.
4845
4846 """
4847 b, q = 1L << shift, x >> shift
4848 return q + (2*(x & (b-1)) + (q&1) > b)
4849
4850def _div_nearest(a, b):
4851 """Closest integer to a/b, a and b positive integers; rounds to even
4852 in the case of a tie.
4853
4854 """
4855 q, r = divmod(a, b)
4856 return q + (2*r + (q&1) > b)
4857
4858def _ilog(x, M, L = 8):
4859 """Integer approximation to M*log(x/M), with absolute error boundable
4860 in terms only of x/M.
4861
4862 Given positive integers x and M, return an integer approximation to
4863 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4864 between the approximation and the exact result is at most 22. For
4865 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4866 both cases these are upper bounds on the error; it will usually be
4867 much smaller."""
4868
4869 # The basic algorithm is the following: let log1p be the function
4870 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4871 # the reduction
4872 #
4873 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4874 #
4875 # repeatedly until the argument to log1p is small (< 2**-L in
4876 # absolute value). For small y we can use the Taylor series
4877 # expansion
4878 #
4879 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4880 #
4881 # truncating at T such that y**T is small enough. The whole
4882 # computation is carried out in a form of fixed-point arithmetic,
4883 # with a real number z being represented by an integer
4884 # approximation to z*M. To avoid loss of precision, the y below
4885 # is actually an integer approximation to 2**R*y*M, where R is the
4886 # number of reductions performed so far.
4887
4888 y = x-M
4889 # argument reduction; R = number of reductions performed
4890 R = 0
4891 while (R <= L and long(abs(y)) << L-R >= M or
4892 R > L and abs(y) >> R-L >= M):
4893 y = _div_nearest(long(M*y) << 1,
4894 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4895 R += 1
4896
4897 # Taylor series with T terms
4898 T = -int(-10*len(str(M))//(3*L))
4899 yshift = _rshift_nearest(y, R)
4900 w = _div_nearest(M, T)
4901 for k in xrange(T-1, 0, -1):
4902 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4903
4904 return _div_nearest(w*y, M)
4905
4906def _dlog10(c, e, p):
4907 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4908 approximation to 10**p * log10(c*10**e), with an absolute error of
4909 at most 1. Assumes that c*10**e is not exactly 1."""
4910
4911 # increase precision by 2; compensate for this by dividing
4912 # final result by 100
4913 p += 2
4914
4915 # write c*10**e as d*10**f with either:
4916 # f >= 0 and 1 <= d <= 10, or
4917 # f <= 0 and 0.1 <= d <= 1.
4918 # Thus for c*10**e close to 1, f = 0
4919 l = len(str(c))
4920 f = e+l - (e+l >= 1)
4921
4922 if p > 0:
4923 M = 10**p
4924 k = e+p-f
4925 if k >= 0:
4926 c *= 10**k
4927 else:
4928 c = _div_nearest(c, 10**-k)
4929
4930 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004931 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004932 log_d = _div_nearest(log_d*M, log_10)
4933 log_tenpower = f*M # exact
4934 else:
4935 log_d = 0 # error < 2.31
4936 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4937
4938 return _div_nearest(log_tenpower+log_d, 100)
4939
4940def _dlog(c, e, p):
4941 """Given integers c, e and p with c > 0, compute an integer
4942 approximation to 10**p * log(c*10**e), with an absolute error of
4943 at most 1. Assumes that c*10**e is not exactly 1."""
4944
4945 # Increase precision by 2. The precision increase is compensated
4946 # for at the end with a division by 100.
4947 p += 2
4948
4949 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4950 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4951 # as 10**p * log(d) + 10**p*f * log(10).
4952 l = len(str(c))
4953 f = e+l - (e+l >= 1)
4954
4955 # compute approximation to 10**p*log(d), with error < 27
4956 if p > 0:
4957 k = e+p-f
4958 if k >= 0:
4959 c *= 10**k
4960 else:
4961 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4962
4963 # _ilog magnifies existing error in c by a factor of at most 10
4964 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4965 else:
4966 # p <= 0: just approximate the whole thing by 0; error < 2.31
4967 log_d = 0
4968
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004969 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00004970 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004971 extra = len(str(abs(f)))-1
4972 if p + extra >= 0:
4973 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4974 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4975 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00004976 else:
4977 f_log_ten = 0
4978 else:
4979 f_log_ten = 0
4980
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004981 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004982 return _div_nearest(f_log_ten + log_d, 100)
4983
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004984class _Log10Memoize(object):
4985 """Class to compute, store, and allow retrieval of, digits of the
4986 constant log(10) = 2.302585.... This constant is needed by
4987 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4988 def __init__(self):
4989 self.digits = "23025850929940456840179914546843642076011014886"
4990
4991 def getdigits(self, p):
4992 """Given an integer p >= 0, return floor(10**p)*log(10).
4993
4994 For example, self.getdigits(3) returns 2302.
4995 """
4996 # digits are stored as a string, for quick conversion to
4997 # integer in the case that we've already computed enough
4998 # digits; the stored digits should always be correct
4999 # (truncated, not rounded to nearest).
5000 if p < 0:
5001 raise ValueError("p should be nonnegative")
5002
5003 if p >= len(self.digits):
5004 # compute p+3, p+6, p+9, ... digits; continue until at
5005 # least one of the extra digits is nonzero
5006 extra = 3
5007 while True:
5008 # compute p+extra digits, correct to within 1ulp
5009 M = 10**(p+extra+2)
5010 digits = str(_div_nearest(_ilog(10*M, M), 100))
5011 if digits[-extra:] != '0'*extra:
5012 break
5013 extra += 3
5014 # keep all reliable digits so far; remove trailing zeros
5015 # and next nonzero digit
5016 self.digits = digits.rstrip('0')[:-1]
5017 return int(self.digits[:p+1])
5018
5019_log10_digits = _Log10Memoize().getdigits
5020
Facundo Batista353750c2007-09-13 18:13:15 +00005021def _iexp(x, M, L=8):
5022 """Given integers x and M, M > 0, such that x/M is small in absolute
5023 value, compute an integer approximation to M*exp(x/M). For 0 <=
5024 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5025 is usually much smaller)."""
5026
5027 # Algorithm: to compute exp(z) for a real number z, first divide z
5028 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5029 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5030 # series
5031 #
5032 # expm1(x) = x + x**2/2! + x**3/3! + ...
5033 #
5034 # Now use the identity
5035 #
5036 # expm1(2x) = expm1(x)*(expm1(x)+2)
5037 #
5038 # R times to compute the sequence expm1(z/2**R),
5039 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5040
5041 # Find R such that x/2**R/M <= 2**-L
5042 R = _nbits((long(x)<<L)//M)
5043
5044 # Taylor series. (2**L)**T > M
5045 T = -int(-10*len(str(M))//(3*L))
5046 y = _div_nearest(x, T)
5047 Mshift = long(M)<<R
5048 for i in xrange(T-1, 0, -1):
5049 y = _div_nearest(x*(Mshift + y), Mshift * i)
5050
5051 # Expansion
5052 for k in xrange(R-1, -1, -1):
5053 Mshift = long(M)<<(k+2)
5054 y = _div_nearest(y*(y+Mshift), Mshift)
5055
5056 return M+y
5057
5058def _dexp(c, e, p):
5059 """Compute an approximation to exp(c*10**e), with p decimal places of
5060 precision.
5061
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005062 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005063
5064 10**(p-1) <= d <= 10**p, and
5065 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5066
5067 In other words, d*10**f is an approximation to exp(c*10**e) with p
5068 digits of precision, and with an error in d of at most 1. This is
5069 almost, but not quite, the same as the error being < 1ulp: when d
5070 = 10**(p-1) the error could be up to 10 ulp."""
5071
5072 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5073 p += 2
5074
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005075 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005076 extra = max(0, e + len(str(c)) - 1)
5077 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005078
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005079 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005080 # rounding down
5081 shift = e+q
5082 if shift >= 0:
5083 cshift = c*10**shift
5084 else:
5085 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005086 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005087
5088 # reduce remainder back to original precision
5089 rem = _div_nearest(rem, 10**extra)
5090
5091 # error in result of _iexp < 120; error after division < 0.62
5092 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5093
5094def _dpower(xc, xe, yc, ye, p):
5095 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5096 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5097
5098 10**(p-1) <= c <= 10**p, and
5099 (c-1)*10**e < x**y < (c+1)*10**e
5100
5101 in other words, c*10**e is an approximation to x**y with p digits
5102 of precision, and with an error in c of at most 1. (This is
5103 almost, but not quite, the same as the error being < 1ulp: when c
5104 == 10**(p-1) we can only guarantee error < 10ulp.)
5105
5106 We assume that: x is positive and not equal to 1, and y is nonzero.
5107 """
5108
5109 # Find b such that 10**(b-1) <= |y| <= 10**b
5110 b = len(str(abs(yc))) + ye
5111
5112 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5113 lxc = _dlog(xc, xe, p+b+1)
5114
5115 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5116 shift = ye-b
5117 if shift >= 0:
5118 pc = lxc*yc*10**shift
5119 else:
5120 pc = _div_nearest(lxc*yc, 10**-shift)
5121
5122 if pc == 0:
5123 # we prefer a result that isn't exactly 1; this makes it
5124 # easier to compute a correctly rounded result in __pow__
5125 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5126 coeff, exp = 10**(p-1)+1, 1-p
5127 else:
5128 coeff, exp = 10**p-1, -p
5129 else:
5130 coeff, exp = _dexp(pc, -(p+1), p+1)
5131 coeff = _div_nearest(coeff, 10)
5132 exp += 1
5133
5134 return coeff, exp
5135
5136def _log10_lb(c, correction = {
5137 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5138 '6': 23, '7': 16, '8': 10, '9': 5}):
5139 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5140 if c <= 0:
5141 raise ValueError("The argument to _log10_lb should be nonnegative.")
5142 str_c = str(c)
5143 return 100*len(str_c) - correction[str_c[0]]
5144
Facundo Batista59c58842007-04-10 12:58:45 +00005145##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005146
Facundo Batista353750c2007-09-13 18:13:15 +00005147def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005148 """Convert other to Decimal.
5149
5150 Verifies that it's ok to use in an implicit construction.
5151 """
5152 if isinstance(other, Decimal):
5153 return other
5154 if isinstance(other, (int, long)):
5155 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005156 if raiseit:
5157 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005158 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005159
Facundo Batista59c58842007-04-10 12:58:45 +00005160##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005161
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005162# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005163# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005164
5165DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005166 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005167 traps=[DivisionByZero, Overflow, InvalidOperation],
5168 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005169 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005170 Emax=999999999,
5171 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005172 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005173)
5174
5175# Pre-made alternate contexts offered by the specification
5176# Don't change these; the user should be able to select these
5177# contexts and be able to reproduce results from other implementations
5178# of the spec.
5179
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005180BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005181 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005182 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5183 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005184)
5185
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005186ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005187 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005188 traps=[],
5189 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005190)
5191
5192
Facundo Batista72bc54f2007-11-23 17:59:00 +00005193##### crud for parsing strings #############################################
5194import re
5195
5196# Regular expression used for parsing numeric strings. Additional
5197# comments:
5198#
5199# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5200# whitespace. But note that the specification disallows whitespace in
5201# a numeric string.
5202#
5203# 2. For finite numbers (not infinities and NaNs) the body of the
5204# number between the optional sign and the optional exponent must have
5205# at least one decimal digit, possibly after the decimal point. The
5206# lookahead expression '(?=\d|\.\d)' checks this.
5207#
5208# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5209# other meaning for \d than the numbers [0-9].
5210
5211import re
5212_parser = re.compile(r""" # A numeric string consists of:
5213# \s*
5214 (?P<sign>[-+])? # an optional sign, followed by either...
5215 (
5216 (?=\d|\.\d) # ...a number (with at least one digit)
5217 (?P<int>\d*) # consisting of a (possibly empty) integer part
5218 (\.(?P<frac>\d*))? # followed by an optional fractional part
5219 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5220 |
5221 Inf(inity)? # ...an infinity, or...
5222 |
5223 (?P<signal>s)? # ...an (optionally signaling)
5224 NaN # NaN
5225 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5226 )
5227# \s*
5228 $
5229""", re.VERBOSE | re.IGNORECASE).match
5230
5231del re
5232
5233
Facundo Batista59c58842007-04-10 12:58:45 +00005234##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005235
Facundo Batista59c58842007-04-10 12:58:45 +00005236# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005237Inf = Decimal('Inf')
5238negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005239NaN = Decimal('NaN')
5240Dec_0 = Decimal(0)
5241Dec_p1 = Decimal(1)
5242Dec_n1 = Decimal(-1)
5243Dec_p2 = Decimal(2)
5244Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005245
Facundo Batista59c58842007-04-10 12:58:45 +00005246# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005247Infsign = (Inf, negInf)
5248
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005249
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005250
5251if __name__ == '__main__':
5252 import doctest, sys
5253 doctest.testmod(sys.modules[__name__])