blob: 1f5ff129628a425c3e1f230ef0a604806f2e187e [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
Guido van Rossumd8faa362007-04-27 19:54:29 +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)
Guido van Rossum7131f842007-02-09 20:13:25 +000059>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000600.333333333
61>>> getcontext().prec = 18
Guido van Rossum7131f842007-02-09 20:13:25 +000062>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000630.333333333333333333
Guido van Rossum7131f842007-02-09 20:13:25 +000064>>> print(dig.sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000651
Guido van Rossum7131f842007-02-09 20:13:25 +000066>>> print(Decimal(3).sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000671.73205080756887729
Guido van Rossum7131f842007-02-09 20:13:25 +000068>>> print(Decimal(3) ** 123)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000694.85192780976896427E+58
70>>> inf = Decimal(1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000071>>> print(inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000072Infinity
73>>> neginf = Decimal(-1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000074>>> print(neginf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000075-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000076>>> print(neginf + inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000077NaN
Guido van Rossum7131f842007-02-09 20:13:25 +000078>>> print(neginf * inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000079-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000080>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000081Infinity
Raymond Hettingerbf440692004-07-10 14:14:37 +000082>>> getcontext().traps[DivisionByZero] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000083>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000084Traceback (most recent call last):
85 ...
86 ...
87 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +000088decimal.DivisionByZero: x / 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000089>>> c = Context()
Raymond Hettingerbf440692004-07-10 14:14:37 +000090>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +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
Guido van Rossum7131f842007-02-09 20:13:25 +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
Guido van Rossum7131f842007-02-09 20:13:25 +000099>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000
Guido van Rossum7131f842007-02-09 20:13:25 +0000101>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000102Traceback (most recent call last):
103 ...
104 ...
105 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +0000106decimal.InvalidOperation: 0 / 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000107>>> 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
Guido van Rossum7131f842007-02-09 20:13:25 +0000111>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000112NaN
Guido van Rossum7131f842007-02-09 20:13:25 +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',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000131 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000132
133 # Functions for manipulating contexts
Thomas Wouters89f507f2006-12-13 04:49:30 +0000134 'setcontext', 'getcontext', 'localcontext'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000135]
136
Guido van Rossuma13f4a12007-12-10 20:04:04 +0000137import numbers as _numbers
Raymond Hettingereb260842005-06-07 18:52:34 +0000138import copy as _copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000139
Guido van Rossumd8faa362007-04-27 19:54:29 +0000140# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000141ROUND_DOWN = 'ROUND_DOWN'
142ROUND_HALF_UP = 'ROUND_HALF_UP'
143ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
144ROUND_CEILING = 'ROUND_CEILING'
145ROUND_FLOOR = 'ROUND_FLOOR'
146ROUND_UP = 'ROUND_UP'
147ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000148ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000149
Guido van Rossumd8faa362007-04-27 19:54:29 +0000150# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000151
152class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000153 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000154
155 Used exceptions derive from this.
156 If an exception derives from another exception besides this (such as
157 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
158 called if the others are present. This isn't actually used for
159 anything, though.
160
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000161 handle -- Called when context._raise_error is called and the
162 trap_enabler is set. First argument is self, second is the
163 context. More arguments can be given, those being after
164 the explanation in _raise_error (For example,
165 context._raise_error(NewError, '(-x)!', self._sign) would
166 call NewError().handle(context, self._sign).)
167
168 To define a new exception, it should be sufficient to have it derive
169 from DecimalException.
170 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000171 def handle(self, context, *args):
172 pass
173
174
175class Clamped(DecimalException):
176 """Exponent of a 0 changed to fit bounds.
177
178 This occurs and signals clamped if the exponent of a result has been
179 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000180 representation. This may occur when the exponent of a zero result would
181 be outside the bounds of a representation, or when a large normal
182 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000183 this latter case, the exponent is reduced to fit and the corresponding
184 number of zero digits are appended to the coefficient ("fold-down").
185 """
186
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000187class InvalidOperation(DecimalException):
188 """An invalid operation was performed.
189
190 Various bad things cause this:
191
192 Something creates a signaling NaN
193 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000194 0 * (+-)INF
195 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000196 x % 0
197 (+-)INF % x
198 x._rescale( non-integer )
199 sqrt(-x) , x > 0
200 0 ** 0
201 x ** (non-integer)
202 x ** (+-)INF
203 An operand is invalid
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000204
205 The result of the operation after these is a quiet positive NaN,
206 except when the cause is a signaling NaN, in which case the result is
207 also a quiet NaN, but with the original sign, and an optional
208 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000209 """
210 def handle(self, context, *args):
211 if args:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000212 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
213 return ans._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000214 return NaN
215
216class ConversionSyntax(InvalidOperation):
217 """Trying to convert badly formed string.
218
219 This occurs and signals invalid-operation if an string is being
220 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000221 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000222 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000223 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000224 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000225
226class DivisionByZero(DecimalException, ZeroDivisionError):
227 """Division by 0.
228
229 This occurs and signals division-by-zero if division of a finite number
230 by zero was attempted (during a divide-integer or divide operation, or a
231 power operation with negative right-hand operand), and the dividend was
232 not zero.
233
234 The result of the operation is [sign,inf], where sign is the exclusive
235 or of the signs of the operands for divide, or is 1 for an odd power of
236 -0, for power.
237 """
238
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000239 def handle(self, context, sign, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000240 return Infsign[sign]
241
242class DivisionImpossible(InvalidOperation):
243 """Cannot perform the division adequately.
244
245 This occurs and signals invalid-operation if the integer result of a
246 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000247 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000248 """
249
250 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000251 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000252
253class DivisionUndefined(InvalidOperation, ZeroDivisionError):
254 """Undefined result of division.
255
256 This occurs and signals invalid-operation if division by zero was
257 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000258 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000259 """
260
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000261 def handle(self, context, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000262 return NaN
263
264class Inexact(DecimalException):
265 """Had to round, losing information.
266
267 This occurs and signals inexact whenever the result of an operation is
268 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000269 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000270 result in all cases is unchanged.
271
272 The inexact signal may be tested (or trapped) to determine if a given
273 operation (or sequence of operations) was inexact.
274 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000275
276class InvalidContext(InvalidOperation):
277 """Invalid context. Unknown rounding, for example.
278
279 This occurs and signals invalid-operation if an invalid context was
Guido van Rossumd8faa362007-04-27 19:54:29 +0000280 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000281 on creation and either the precision exceeds the capability of the
282 underlying concrete representation or an unknown or unsupported rounding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000283 was specified. These aspects of the context need only be checked when
284 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000285 """
286
287 def handle(self, context, *args):
288 return NaN
289
290class Rounded(DecimalException):
291 """Number got rounded (not necessarily changed during rounding).
292
293 This occurs and signals rounded whenever the result of an operation is
294 rounded (that is, some zero or non-zero digits were discarded from the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000295 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000296 result in all cases is unchanged.
297
298 The rounded signal may be tested (or trapped) to determine if a given
299 operation (or sequence of operations) caused a loss of precision.
300 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000301
302class Subnormal(DecimalException):
303 """Exponent < Emin before rounding.
304
305 This occurs and signals subnormal whenever the result of a conversion or
306 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000307 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000308
309 The subnormal signal may be tested (or trapped) to determine if a given
310 or operation (or sequence of operations) yielded a subnormal result.
311 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000312
313class Overflow(Inexact, Rounded):
314 """Numerical overflow.
315
316 This occurs and signals overflow if the adjusted exponent of a result
317 (from a conversion or from an operation that is not an attempt to divide
318 by zero), after rounding, would be greater than the largest value that
319 can be handled by the implementation (the value Emax).
320
321 The result depends on the rounding mode:
322
323 For round-half-up and round-half-even (and for round-half-down and
324 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000325 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000326 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000327 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000328 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000329 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000330 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000331 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000332 will also be raised.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000333 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000334
335 def handle(self, context, sign, *args):
336 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000337 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000338 return Infsign[sign]
339 if sign == 0:
340 if context.rounding == ROUND_CEILING:
341 return Infsign[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000342 return _dec_from_triple(sign, '9'*context.prec,
343 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000344 if sign == 1:
345 if context.rounding == ROUND_FLOOR:
346 return Infsign[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000347 return _dec_from_triple(sign, '9'*context.prec,
348 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000349
350
351class Underflow(Inexact, Rounded, Subnormal):
352 """Numerical underflow with result rounded to 0.
353
354 This occurs and signals underflow if a result is inexact and the
355 adjusted exponent of the result would be smaller (more negative) than
356 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000357 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000358
359 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000360 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000361 in 0 with the sign of the intermediate result and an exponent of Etiny.
362
363 In all cases, Inexact, Rounded, and Subnormal will also be raised.
364 """
365
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000366# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000367_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000368 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000369
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000370# Map conditions (per the spec) to signals
371_condition_map = {ConversionSyntax:InvalidOperation,
372 DivisionImpossible:InvalidOperation,
373 DivisionUndefined:InvalidOperation,
374 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000375
Guido van Rossumd8faa362007-04-27 19:54:29 +0000376##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000377
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000378# The getcontext() and setcontext() function manage access to a thread-local
379# current context. Py2.4 offers direct support for thread locals. If that
380# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000381# work for older Pythons. If threads are not part of the build, create a
382# mock threading object with threading.local() returning the module namespace.
383
384try:
385 import threading
386except ImportError:
387 # Python was compiled without threads; create a mock object instead
388 import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +0000389 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000390 def local(self, sys=sys):
391 return sys.modules[__name__]
392 threading = MockThreading()
393 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000394
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000395try:
396 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000397
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000398except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000399
Guido van Rossumd8faa362007-04-27 19:54:29 +0000400 # To fix reloading, force it to create a new context
401 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000402 if hasattr(threading.currentThread(), '__decimal_context__'):
403 del threading.currentThread().__decimal_context__
404
405 def setcontext(context):
406 """Set this thread's context to context."""
407 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000408 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000409 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000410 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000411
412 def getcontext():
413 """Returns this thread's context.
414
415 If this thread does not yet have a context, returns
416 a new context and sets this thread's context.
417 New contexts are copies of DefaultContext.
418 """
419 try:
420 return threading.currentThread().__decimal_context__
421 except AttributeError:
422 context = Context()
423 threading.currentThread().__decimal_context__ = context
424 return context
425
426else:
427
428 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000429 if hasattr(local, '__decimal_context__'):
430 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000431
432 def getcontext(_local=local):
433 """Returns this thread's context.
434
435 If this thread does not yet have a context, returns
436 a new context and sets this thread's context.
437 New contexts are copies of DefaultContext.
438 """
439 try:
440 return _local.__decimal_context__
441 except AttributeError:
442 context = Context()
443 _local.__decimal_context__ = context
444 return context
445
446 def setcontext(context, _local=local):
447 """Set this thread's context to context."""
448 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000449 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000450 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000451 _local.__decimal_context__ = context
452
453 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000454
Thomas Wouters89f507f2006-12-13 04:49:30 +0000455def localcontext(ctx=None):
456 """Return a context manager for a copy of the supplied context
457
458 Uses a copy of the current context if no context is specified
459 The returned context manager creates a local decimal context
460 in a with statement:
461 def sin(x):
462 with localcontext() as ctx:
463 ctx.prec += 2
464 # Rest of sin calculation algorithm
465 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000466 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000467
468 def sin(x):
469 with localcontext(ExtendedContext):
470 # Rest of sin calculation algorithm
471 # uses the Extended Context from the
472 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000473 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000474
475 """
476 # The string below can't be included in the docstring until Python 2.6
477 # as the doctest module doesn't understand __future__ statements
478 """
479 >>> from __future__ import with_statement
Guido van Rossum7131f842007-02-09 20:13:25 +0000480 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000481 28
482 >>> with localcontext():
483 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000484 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000485 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000486 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000487 30
488 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000489 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000490 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000491 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000492 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000493 28
494 """
495 if ctx is None: ctx = getcontext()
496 return _ContextManager(ctx)
497
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000498
Guido van Rossumd8faa362007-04-27 19:54:29 +0000499##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000500
Guido van Rossuma13f4a12007-12-10 20:04:04 +0000501class Decimal(_numbers.Real, _numbers.Inexact):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000502 """Floating point class for decimal arithmetic."""
503
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000504 __slots__ = ('_exp','_int','_sign', '_is_special')
505 # Generally, the value of the Decimal instance is given by
506 # (-1)**_sign * _int * 10**_exp
507 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000508
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000509 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000510 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000511 """Create a decimal point instance.
512
513 >>> Decimal('3.14') # string input
514 Decimal("3.14")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000515 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000516 Decimal("3.14")
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000517 >>> Decimal(314) # int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000518 Decimal("314")
519 >>> Decimal(Decimal(314)) # another decimal instance
520 Decimal("314")
521 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000522
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000523 # Note that the coefficient, self._int, is actually stored as
524 # a string rather than as a tuple of digits. This speeds up
525 # the "digits to integer" and "integer to digits" conversions
526 # that are used in almost every arithmetic operation on
527 # Decimals. This is an internal detail: the as_tuple function
528 # and the Decimal constructor still deal with tuples of
529 # digits.
530
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000531 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000532
Christian Heimesd59c64c2007-11-30 19:27:20 +0000533 # From a string
534 # REs insist on real strings, so we can too.
535 if isinstance(value, str):
536 m = _parser(value)
537 if m is None:
538 if context is None:
539 context = getcontext()
540 return context._raise_error(ConversionSyntax,
541 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000542
Christian Heimesd59c64c2007-11-30 19:27:20 +0000543 if m.group('sign') == "-":
544 self._sign = 1
545 else:
546 self._sign = 0
547 intpart = m.group('int')
548 if intpart is not None:
549 # finite number
550 fracpart = m.group('frac')
551 exp = int(m.group('exp') or '0')
552 if fracpart is not None:
553 self._int = (intpart+fracpart).lstrip('0') or '0'
554 self._exp = exp - len(fracpart)
555 else:
556 self._int = intpart.lstrip('0') or '0'
557 self._exp = exp
558 self._is_special = False
559 else:
560 diag = m.group('diag')
561 if diag is not None:
562 # NaN
563 self._int = diag.lstrip('0')
564 if m.group('signal'):
565 self._exp = 'N'
566 else:
567 self._exp = 'n'
568 else:
569 # infinity
570 self._int = '0'
571 self._exp = 'F'
572 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000573 return self
574
575 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000576 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000577 if value >= 0:
578 self._sign = 0
579 else:
580 self._sign = 1
581 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000582 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000583 self._is_special = False
584 return self
585
586 # From another decimal
587 if isinstance(value, Decimal):
588 self._exp = value._exp
589 self._sign = value._sign
590 self._int = value._int
591 self._is_special = value._is_special
592 return self
593
594 # From an internal working value
595 if isinstance(value, _WorkRep):
596 self._sign = value.sign
597 self._int = str(value.int)
598 self._exp = int(value.exp)
599 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000600 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000601
602 # tuple/list conversion (possibly from as_tuple())
603 if isinstance(value, (list,tuple)):
604 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000605 raise ValueError('Invalid tuple size in creation of Decimal '
606 'from list or tuple. The list or tuple '
607 'should have exactly three elements.')
608 # process sign. The isinstance test rejects floats
609 if not (isinstance(value[0], int) and value[0] in (0,1)):
610 raise ValueError("Invalid sign. The first value in the tuple "
611 "should be an integer; either 0 for a "
612 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000613 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000614 if value[2] == 'F':
615 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000616 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000617 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000618 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000619 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000620 # process and validate the digits in value[1]
621 digits = []
622 for digit in value[1]:
623 if isinstance(digit, int) and 0 <= digit <= 9:
624 # skip leading zeros
625 if digits or digit != 0:
626 digits.append(digit)
627 else:
628 raise ValueError("The second value in the tuple must "
629 "be composed of integers in the range "
630 "0 through 9.")
631 if value[2] in ('n', 'N'):
632 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000633 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000634 self._exp = value[2]
635 self._is_special = True
636 elif isinstance(value[2], int):
637 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000638 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000639 self._exp = value[2]
640 self._is_special = False
641 else:
642 raise ValueError("The third value in the tuple must "
643 "be an integer, or one of the "
644 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000645 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000646
Raymond Hettingerbf440692004-07-10 14:14:37 +0000647 if isinstance(value, float):
648 raise TypeError("Cannot convert float to Decimal. " +
649 "First convert the float to a string")
650
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000651 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000652
653 def _isnan(self):
654 """Returns whether the number is not actually one.
655
656 0 if a number
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000657 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000658 2 if sNaN
659 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000660 if self._is_special:
661 exp = self._exp
662 if exp == 'n':
663 return 1
664 elif exp == 'N':
665 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000666 return 0
667
668 def _isinfinity(self):
669 """Returns whether the number is infinite
670
671 0 if finite or not a number
672 1 if +INF
673 -1 if -INF
674 """
675 if self._exp == 'F':
676 if self._sign:
677 return -1
678 return 1
679 return 0
680
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000681 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000682 """Returns whether the number is not actually one.
683
684 if self, other are sNaN, signal
685 if self, other are NaN return nan
686 return 0
687
688 Done before operations.
689 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000690
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000691 self_is_nan = self._isnan()
692 if other is None:
693 other_is_nan = False
694 else:
695 other_is_nan = other._isnan()
696
697 if self_is_nan or other_is_nan:
698 if context is None:
699 context = getcontext()
700
701 if self_is_nan == 2:
702 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000703 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000704 if other_is_nan == 2:
705 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000706 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000707 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000708 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000709
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000710 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000711 return 0
712
Jack Diederich4dafcc42006-11-28 19:15:13 +0000713 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000714 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000715
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000716 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000717 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000718 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000719
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000720 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000721 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000722 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000723 # Never return NotImplemented
724 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000725
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000726 if self._is_special or other._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000727 # check for nans, without raising on a signaling nan
728 if self._isnan() or other._isnan():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000729 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000730
731 # INF = INF
732 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000733
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000734 # check for zeros; note that cmp(0, -0) should return 0
735 if not self:
736 if not other:
737 return 0
738 else:
739 return -((-1)**other._sign)
740 if not other:
741 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000742
Guido van Rossumd8faa362007-04-27 19:54:29 +0000743 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000744 if other._sign < self._sign:
745 return -1
746 if self._sign < other._sign:
747 return 1
748
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000749 self_adjusted = self.adjusted()
750 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000751 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000752 self_padded = self._int + '0'*(self._exp - other._exp)
753 other_padded = other._int + '0'*(other._exp - self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000754 return cmp(self_padded, other_padded) * (-1)**self._sign
755 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000756 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000757 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000758 return -((-1)**self._sign)
759
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000760 def __eq__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000761 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000762 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000763 return self.__cmp__(other) == 0
764
765 def __ne__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000766 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000767 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000768 return self.__cmp__(other) != 0
769
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000770 def __lt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000771 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000772 return NotImplemented
773 return self.__cmp__(other) < 0
774
775 def __le__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000776 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000777 return NotImplemented
778 return self.__cmp__(other) <= 0
779
780 def __gt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000781 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000782 return NotImplemented
783 return self.__cmp__(other) > 0
784
785 def __ge__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000786 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000787 return NotImplemented
788 return self.__cmp__(other) >= 0
789
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000790 def compare(self, other, context=None):
791 """Compares one to another.
792
793 -1 => a < b
794 0 => a = b
795 1 => a > b
796 NaN => one is NaN
797 Like __cmp__, but returns Decimal instances.
798 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000799 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000800
Guido van Rossumd8faa362007-04-27 19:54:29 +0000801 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000802 if (self._is_special or other and other._is_special):
803 ans = self._check_nans(other, context)
804 if ans:
805 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000806
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000807 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000808
809 def __hash__(self):
810 """x.__hash__() <==> hash(x)"""
811 # Decimal integers must hash the same as the ints
Christian Heimes2380ac72008-01-09 00:17:24 +0000812 #
813 # The hash of a nonspecial noninteger Decimal must depend only
814 # on the value of that Decimal, and not on its representation.
815 # For example: hash(Decimal("100E-1")) == hash(Decimal("10")).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000816 if self._is_special:
817 if self._isnan():
818 raise TypeError('Cannot hash a NaN value.')
819 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000820 if not self:
821 return 0
822 if self._isinteger():
823 op = _WorkRep(self.to_integral_value())
824 # to make computation feasible for Decimals with large
825 # exponent, we use the fact that hash(n) == hash(m) for
826 # any two nonzero integers n and m such that (i) n and m
827 # have the same sign, and (ii) n is congruent to m modulo
828 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
829 # hash((-1)**s*c*pow(10, e, 2**64-1).
830 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Christian Heimes2380ac72008-01-09 00:17:24 +0000831 # The value of a nonzero nonspecial Decimal instance is
832 # faithfully represented by the triple consisting of its sign,
833 # its adjusted exponent, and its coefficient with trailing
834 # zeros removed.
835 return hash((self._sign,
836 self._exp+len(self._int),
837 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000838
839 def as_tuple(self):
840 """Represents the number as a triple tuple.
841
842 To show the internals exactly as they are.
843 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000844 return (self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000845
846 def __repr__(self):
847 """Represents the number as an instance of Decimal."""
848 # Invariant: eval(repr(d)) == d
849 return 'Decimal("%s")' % str(self)
850
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000851 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000852 """Return string representation of the number in scientific notation.
853
854 Captures all of the information in the underlying representation.
855 """
856
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000857 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000858 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000859 if self._exp == 'F':
860 return sign + 'Infinity'
861 elif self._exp == 'n':
862 return sign + 'NaN' + self._int
863 else: # self._exp == 'N'
864 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000865
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000866 # number of digits of self._int to left of decimal point
867 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000868
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000869 # dotplace is number of digits of self._int to the left of the
870 # decimal point in the mantissa of the output string (that is,
871 # after adjusting the exponent)
872 if self._exp <= 0 and leftdigits > -6:
873 # no exponent required
874 dotplace = leftdigits
875 elif not eng:
876 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000877 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000878 elif self._int == '0':
879 # engineering notation, zero
880 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000881 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000882 # engineering notation, nonzero
883 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000884
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000885 if dotplace <= 0:
886 intpart = '0'
887 fracpart = '.' + '0'*(-dotplace) + self._int
888 elif dotplace >= len(self._int):
889 intpart = self._int+'0'*(dotplace-len(self._int))
890 fracpart = ''
891 else:
892 intpart = self._int[:dotplace]
893 fracpart = '.' + self._int[dotplace:]
894 if leftdigits == dotplace:
895 exp = ''
896 else:
897 if context is None:
898 context = getcontext()
899 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
900
901 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000902
903 def to_eng_string(self, context=None):
904 """Convert to engineering-type string.
905
906 Engineering notation has an exponent which is a multiple of 3, so there
907 are up to 3 digits left of the decimal place.
908
909 Same rules for when in exponential and when as a value as in __str__.
910 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000911 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000912
913 def __neg__(self, context=None):
914 """Returns a copy with the sign switched.
915
916 Rounds, if it has reason.
917 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000918 if self._is_special:
919 ans = self._check_nans(context=context)
920 if ans:
921 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000922
923 if not self:
924 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000925 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000926 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000927 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000928
929 if context is None:
930 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +0000931 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000932
933 def __pos__(self, context=None):
934 """Returns a copy, unless it is a sNaN.
935
936 Rounds the number (if more then precision digits)
937 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000938 if self._is_special:
939 ans = self._check_nans(context=context)
940 if ans:
941 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000942
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000943 if not self:
944 # + (-0) = 0
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000945 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000946 else:
947 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000948
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000949 if context is None:
950 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +0000951 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000952
Christian Heimes2c181612007-12-17 20:04:13 +0000953 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000954 """Returns the absolute value of self.
955
Christian Heimes2c181612007-12-17 20:04:13 +0000956 If the keyword argument 'round' is false, do not round. The
957 expression self.__abs__(round=False) is equivalent to
958 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000959 """
Christian Heimes2c181612007-12-17 20:04:13 +0000960 if not round:
961 return self.copy_abs()
962
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000963 if self._is_special:
964 ans = self._check_nans(context=context)
965 if ans:
966 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000967
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000968 if self._sign:
969 ans = self.__neg__(context=context)
970 else:
971 ans = self.__pos__(context=context)
972
973 return ans
974
975 def __add__(self, other, context=None):
976 """Returns self + other.
977
978 -INF + INF (or the reverse) cause InvalidOperation errors.
979 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000980 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000981 if other is NotImplemented:
982 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000983
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000984 if context is None:
985 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000986
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000987 if self._is_special or other._is_special:
988 ans = self._check_nans(other, context)
989 if ans:
990 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000991
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000992 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000993 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000994 if self._sign != other._sign and other._isinfinity():
995 return context._raise_error(InvalidOperation, '-INF + INF')
996 return Decimal(self)
997 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000998 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000999
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000 exp = min(self._exp, other._exp)
1001 negativezero = 0
1002 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001003 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001004 negativezero = 1
1005
1006 if not self and not other:
1007 sign = min(self._sign, other._sign)
1008 if negativezero:
1009 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001010 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001011 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001012 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001013 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001014 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001015 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001016 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001017 return ans
1018 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001019 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001020 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001021 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001022 return ans
1023
1024 op1 = _WorkRep(self)
1025 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001026 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001027
1028 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001029 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001030 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001031 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001032 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001033 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001034 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001035 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001036 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001037 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001038 if op1.sign == 1:
1039 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001040 op1.sign, op2.sign = op2.sign, op1.sign
1041 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001042 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001043 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001044 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001045 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001046 op1.sign, op2.sign = (0, 0)
1047 else:
1048 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001049 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001050
Raymond Hettinger17931de2004-10-27 06:21:46 +00001051 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001052 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001053 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001054 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055
1056 result.exp = op1.exp
1057 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001058 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001059 return ans
1060
1061 __radd__ = __add__
1062
1063 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001064 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001065 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001066 if other is NotImplemented:
1067 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001068
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001069 if self._is_special or other._is_special:
1070 ans = self._check_nans(other, context=context)
1071 if ans:
1072 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001073
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001074 # self - other is computed as self + other.copy_negate()
1075 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001076
1077 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001078 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001079 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001080 if other is NotImplemented:
1081 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001082
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001083 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001084
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001085 def __mul__(self, other, context=None):
1086 """Return self * other.
1087
1088 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1089 """
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 Hettinger636a6b12004-09-19 01:54:09 +00001093
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001094 if context is None:
1095 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001096
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001097 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001098
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001099 if self._is_special or other._is_special:
1100 ans = self._check_nans(other, context)
1101 if ans:
1102 return ans
1103
1104 if self._isinfinity():
1105 if not other:
1106 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1107 return Infsign[resultsign]
1108
1109 if other._isinfinity():
1110 if not self:
1111 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1112 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001113
1114 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001115
1116 # Special case for multiplying by zero
1117 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001118 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001119 # Fixing in case the exponent is out of bounds
1120 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001121 return ans
1122
1123 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001124 if self._int == '1':
1125 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001126 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001127 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001128 if other._int == '1':
1129 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001130 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001131 return ans
1132
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001133 op1 = _WorkRep(self)
1134 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001135
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001136 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001137 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001138
1139 return ans
1140 __rmul__ = __mul__
1141
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001142 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001143 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001144 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001145 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001146 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001147
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001148 if context is None:
1149 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001150
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001151 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001152
1153 if self._is_special or other._is_special:
1154 ans = self._check_nans(other, context)
1155 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001156 return ans
1157
1158 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001159 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001160
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001161 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001162 return Infsign[sign]
1163
1164 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001165 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001166 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001167
1168 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001169 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001170 if not self:
1171 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001172 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001173
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001174 if not self:
1175 exp = self._exp - other._exp
1176 coeff = 0
1177 else:
1178 # OK, so neither = 0, INF or NaN
1179 shift = len(other._int) - len(self._int) + context.prec + 1
1180 exp = self._exp - other._exp - shift
1181 op1 = _WorkRep(self)
1182 op2 = _WorkRep(other)
1183 if shift >= 0:
1184 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1185 else:
1186 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1187 if remainder:
1188 # result is not exact; adjust to ensure correct rounding
1189 if coeff % 5 == 0:
1190 coeff += 1
1191 else:
1192 # result is exact; get as close to ideal exponent as possible
1193 ideal_exp = self._exp - other._exp
1194 while exp < ideal_exp and coeff % 10 == 0:
1195 coeff //= 10
1196 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001197
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001198 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001199 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001200
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001201 def _divide(self, other, context):
1202 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001203
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001204 Assumes that neither self nor other is a NaN, that self is not
1205 infinite and that other is nonzero.
1206 """
1207 sign = self._sign ^ other._sign
1208 if other._isinfinity():
1209 ideal_exp = self._exp
1210 else:
1211 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001212
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001213 expdiff = self.adjusted() - other.adjusted()
1214 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001215 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001216 self._rescale(ideal_exp, context.rounding))
1217 if expdiff <= context.prec:
1218 op1 = _WorkRep(self)
1219 op2 = _WorkRep(other)
1220 if op1.exp >= op2.exp:
1221 op1.int *= 10**(op1.exp - op2.exp)
1222 else:
1223 op2.int *= 10**(op2.exp - op1.exp)
1224 q, r = divmod(op1.int, op2.int)
1225 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001226 return (_dec_from_triple(sign, str(q), 0),
1227 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001228
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001229 # Here the quotient is too large to be representable
1230 ans = context._raise_error(DivisionImpossible,
1231 'quotient too large in //, % or divmod')
1232 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001233
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001234 def __rtruediv__(self, other, context=None):
1235 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001236 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001237 if other is NotImplemented:
1238 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001239 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001240
1241 def __divmod__(self, other, context=None):
1242 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001243 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001244 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001245 other = _convert_other(other)
1246 if other is NotImplemented:
1247 return other
1248
1249 if context is None:
1250 context = getcontext()
1251
1252 ans = self._check_nans(other, context)
1253 if ans:
1254 return (ans, ans)
1255
1256 sign = self._sign ^ other._sign
1257 if self._isinfinity():
1258 if other._isinfinity():
1259 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1260 return ans, ans
1261 else:
1262 return (Infsign[sign],
1263 context._raise_error(InvalidOperation, 'INF % x'))
1264
1265 if not other:
1266 if not self:
1267 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1268 return ans, ans
1269 else:
1270 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1271 context._raise_error(InvalidOperation, 'x % 0'))
1272
1273 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001274 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001275 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001276
1277 def __rdivmod__(self, other, context=None):
1278 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001279 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001280 if other is NotImplemented:
1281 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001282 return other.__divmod__(self, context=context)
1283
1284 def __mod__(self, other, context=None):
1285 """
1286 self % other
1287 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001288 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001289 if other is NotImplemented:
1290 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001291
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001292 if context is None:
1293 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001294
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001295 ans = self._check_nans(other, context)
1296 if ans:
1297 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001298
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001299 if self._isinfinity():
1300 return context._raise_error(InvalidOperation, 'INF % x')
1301 elif not other:
1302 if self:
1303 return context._raise_error(InvalidOperation, 'x % 0')
1304 else:
1305 return context._raise_error(DivisionUndefined, '0 % 0')
1306
1307 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001308 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001309 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001310
1311 def __rmod__(self, other, context=None):
1312 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001313 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001314 if other is NotImplemented:
1315 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001316 return other.__mod__(self, context=context)
1317
1318 def remainder_near(self, other, context=None):
1319 """
1320 Remainder nearest to 0- abs(remainder-near) <= other/2
1321 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001322 if context is None:
1323 context = getcontext()
1324
1325 other = _convert_other(other, raiseit=True)
1326
1327 ans = self._check_nans(other, context)
1328 if ans:
1329 return ans
1330
1331 # self == +/-infinity -> InvalidOperation
1332 if self._isinfinity():
1333 return context._raise_error(InvalidOperation,
1334 'remainder_near(infinity, x)')
1335
1336 # other == 0 -> either InvalidOperation or DivisionUndefined
1337 if not other:
1338 if self:
1339 return context._raise_error(InvalidOperation,
1340 'remainder_near(x, 0)')
1341 else:
1342 return context._raise_error(DivisionUndefined,
1343 'remainder_near(0, 0)')
1344
1345 # other = +/-infinity -> remainder = self
1346 if other._isinfinity():
1347 ans = Decimal(self)
1348 return ans._fix(context)
1349
1350 # self = 0 -> remainder = self, with ideal exponent
1351 ideal_exponent = min(self._exp, other._exp)
1352 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001353 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001354 return ans._fix(context)
1355
1356 # catch most cases of large or small quotient
1357 expdiff = self.adjusted() - other.adjusted()
1358 if expdiff >= context.prec + 1:
1359 # expdiff >= prec+1 => abs(self/other) > 10**prec
1360 return context._raise_error(DivisionImpossible)
1361 if expdiff <= -2:
1362 # expdiff <= -2 => abs(self/other) < 0.1
1363 ans = self._rescale(ideal_exponent, context.rounding)
1364 return ans._fix(context)
1365
1366 # adjust both arguments to have the same exponent, then divide
1367 op1 = _WorkRep(self)
1368 op2 = _WorkRep(other)
1369 if op1.exp >= op2.exp:
1370 op1.int *= 10**(op1.exp - op2.exp)
1371 else:
1372 op2.int *= 10**(op2.exp - op1.exp)
1373 q, r = divmod(op1.int, op2.int)
1374 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1375 # 10**ideal_exponent. Apply correction to ensure that
1376 # abs(remainder) <= abs(other)/2
1377 if 2*r + (q&1) > op2.int:
1378 r -= op2.int
1379 q += 1
1380
1381 if q >= 10**context.prec:
1382 return context._raise_error(DivisionImpossible)
1383
1384 # result has same sign as self unless r is negative
1385 sign = self._sign
1386 if r < 0:
1387 sign = 1-sign
1388 r = -r
1389
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001390 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001391 return ans._fix(context)
1392
1393 def __floordiv__(self, other, context=None):
1394 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001395 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001396 if other is NotImplemented:
1397 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001398
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001399 if context is None:
1400 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001401
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001402 ans = self._check_nans(other, context)
1403 if ans:
1404 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001405
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001406 if self._isinfinity():
1407 if other._isinfinity():
1408 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001409 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001410 return Infsign[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001411
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001412 if not other:
1413 if self:
1414 return context._raise_error(DivisionByZero, 'x // 0',
1415 self._sign ^ other._sign)
1416 else:
1417 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001418
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001419 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001420
1421 def __rfloordiv__(self, other, context=None):
1422 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001423 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001424 if other is NotImplemented:
1425 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001426 return other.__floordiv__(self, context=context)
1427
1428 def __float__(self):
1429 """Float representation."""
1430 return float(str(self))
1431
1432 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001433 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001434 if self._is_special:
1435 if self._isnan():
1436 context = getcontext()
1437 return context._raise_error(InvalidContext)
1438 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001439 raise OverflowError("Cannot convert infinity to int")
1440 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001441 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001442 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001443 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001444 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001445
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001446 def _fix_nan(self, context):
1447 """Decapitate the payload of a NaN to fit the context"""
1448 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001449
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001450 # maximum length of payload is precision if _clamp=0,
1451 # precision-1 if _clamp=1.
1452 max_payload_len = context.prec - context._clamp
1453 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001454 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1455 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001456 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001457
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001458 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001459 """Round if it is necessary to keep self within prec precision.
1460
1461 Rounds and fixes the exponent. Does not raise on a sNaN.
1462
1463 Arguments:
1464 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001465 context - context used.
1466 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001467
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001468 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001469 if self._isnan():
1470 # decapitate payload if necessary
1471 return self._fix_nan(context)
1472 else:
1473 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001474 return Decimal(self)
1475
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001476 # if self is zero then exponent should be between Etiny and
1477 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1478 Etiny = context.Etiny()
1479 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001480 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001481 exp_max = [context.Emax, Etop][context._clamp]
1482 new_exp = min(max(self._exp, Etiny), exp_max)
1483 if new_exp != self._exp:
1484 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001485 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001486 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001487 return Decimal(self)
1488
1489 # exp_min is the smallest allowable exponent of the result,
1490 # equal to max(self.adjusted()-context.prec+1, Etiny)
1491 exp_min = len(self._int) + self._exp - context.prec
1492 if exp_min > Etop:
1493 # overflow: exp_min > Etop iff self.adjusted() > Emax
1494 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001495 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001496 return context._raise_error(Overflow, 'above Emax', self._sign)
1497 self_is_subnormal = exp_min < Etiny
1498 if self_is_subnormal:
1499 context._raise_error(Subnormal)
1500 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001501
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001502 # round if self has too many digits
1503 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001504 context._raise_error(Rounded)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001505 digits = len(self._int) + self._exp - exp_min
1506 if digits < 0:
1507 self = _dec_from_triple(self._sign, '1', exp_min-1)
1508 digits = 0
1509 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1510 changed = this_function(digits)
1511 coeff = self._int[:digits] or '0'
1512 if changed == 1:
1513 coeff = str(int(coeff)+1)
1514 ans = _dec_from_triple(self._sign, coeff, exp_min)
1515
1516 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001517 context._raise_error(Inexact)
1518 if self_is_subnormal:
1519 context._raise_error(Underflow)
1520 if not ans:
1521 # raise Clamped on underflow to 0
1522 context._raise_error(Clamped)
1523 elif len(ans._int) == context.prec+1:
1524 # we get here only if rescaling rounds the
1525 # cofficient up to exactly 10**context.prec
1526 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001527 ans = _dec_from_triple(ans._sign,
1528 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001529 else:
1530 # Inexact and Rounded have already been raised
1531 ans = context._raise_error(Overflow, 'above Emax',
1532 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001533 return ans
1534
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001535 # fold down if _clamp == 1 and self has too few digits
1536 if context._clamp == 1 and self._exp > Etop:
1537 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001538 self_padded = self._int + '0'*(self._exp - Etop)
1539 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001540
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001541 # here self was representable to begin with; return unchanged
1542 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001543
1544 _pick_rounding_function = {}
1545
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001546 # for each of the rounding functions below:
1547 # self is a finite, nonzero Decimal
1548 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001549 #
1550 # each function returns either -1, 0, or 1, as follows:
1551 # 1 indicates that self should be rounded up (away from zero)
1552 # 0 indicates that self should be truncated, and that all the
1553 # digits to be truncated are zeros (so the value is unchanged)
1554 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001555
1556 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001557 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001558 if _all_zeros(self._int, prec):
1559 return 0
1560 else:
1561 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001562
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001563 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001564 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001565 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001566
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001567 def _round_half_up(self, prec):
1568 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001569 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001570 return 1
1571 elif _all_zeros(self._int, prec):
1572 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001573 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001574 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001575
1576 def _round_half_down(self, prec):
1577 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001578 if _exact_half(self._int, prec):
1579 return -1
1580 else:
1581 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001582
1583 def _round_half_even(self, prec):
1584 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001585 if _exact_half(self._int, prec) and \
1586 (prec == 0 or self._int[prec-1] in '02468'):
1587 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001588 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001589 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001590
1591 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001592 """Rounds up (not away from 0 if negative.)"""
1593 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001594 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001595 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001596 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001597
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001598 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001599 """Rounds down (not towards 0 if negative)"""
1600 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001601 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001602 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001603 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001604
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001605 def _round_05up(self, prec):
1606 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001607 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001608 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001609 else:
1610 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001611
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001612 def fma(self, other, third, context=None):
1613 """Fused multiply-add.
1614
1615 Returns self*other+third with no rounding of the intermediate
1616 product self*other.
1617
1618 self and other are multiplied together, with no rounding of
1619 the result. The third operand is then added to the result,
1620 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001621 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001622
1623 other = _convert_other(other, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001624
1625 # compute product; raise InvalidOperation if either operand is
1626 # a signaling NaN or if the product is zero times infinity.
1627 if self._is_special or other._is_special:
1628 if context is None:
1629 context = getcontext()
1630 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001631 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001632 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001633 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001634 if self._exp == 'n':
1635 product = self
1636 elif other._exp == 'n':
1637 product = other
1638 elif self._exp == 'F':
1639 if not other:
1640 return context._raise_error(InvalidOperation,
1641 'INF * 0 in fma')
1642 product = Infsign[self._sign ^ other._sign]
1643 elif other._exp == 'F':
1644 if not self:
1645 return context._raise_error(InvalidOperation,
1646 '0 * INF in fma')
1647 product = Infsign[self._sign ^ other._sign]
1648 else:
1649 product = _dec_from_triple(self._sign ^ other._sign,
1650 str(int(self._int) * int(other._int)),
1651 self._exp + other._exp)
1652
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001653 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001654 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001655
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001656 def _power_modulo(self, other, modulo, context=None):
1657 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001658
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001659 # if can't convert other and modulo to Decimal, raise
1660 # TypeError; there's no point returning NotImplemented (no
1661 # equivalent of __rpow__ for three argument pow)
1662 other = _convert_other(other, raiseit=True)
1663 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001664
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001665 if context is None:
1666 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001667
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001668 # deal with NaNs: if there are any sNaNs then first one wins,
1669 # (i.e. behaviour for NaNs is identical to that of fma)
1670 self_is_nan = self._isnan()
1671 other_is_nan = other._isnan()
1672 modulo_is_nan = modulo._isnan()
1673 if self_is_nan or other_is_nan or modulo_is_nan:
1674 if self_is_nan == 2:
1675 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001676 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001677 if other_is_nan == 2:
1678 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001679 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001680 if modulo_is_nan == 2:
1681 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001682 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001683 if self_is_nan:
1684 return self._fix_nan(context)
1685 if other_is_nan:
1686 return other._fix_nan(context)
1687 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001688
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001689 # check inputs: we apply same restrictions as Python's pow()
1690 if not (self._isinteger() and
1691 other._isinteger() and
1692 modulo._isinteger()):
1693 return context._raise_error(InvalidOperation,
1694 'pow() 3rd argument not allowed '
1695 'unless all arguments are integers')
1696 if other < 0:
1697 return context._raise_error(InvalidOperation,
1698 'pow() 2nd argument cannot be '
1699 'negative when 3rd argument specified')
1700 if not modulo:
1701 return context._raise_error(InvalidOperation,
1702 'pow() 3rd argument cannot be 0')
1703
1704 # additional restriction for decimal: the modulus must be less
1705 # than 10**prec in absolute value
1706 if modulo.adjusted() >= context.prec:
1707 return context._raise_error(InvalidOperation,
1708 'insufficient precision: pow() 3rd '
1709 'argument must not have more than '
1710 'precision digits')
1711
1712 # define 0**0 == NaN, for consistency with two-argument pow
1713 # (even though it hurts!)
1714 if not other and not self:
1715 return context._raise_error(InvalidOperation,
1716 'at least one of pow() 1st argument '
1717 'and 2nd argument must be nonzero ;'
1718 '0**0 is not defined')
1719
1720 # compute sign of result
1721 if other._iseven():
1722 sign = 0
1723 else:
1724 sign = self._sign
1725
1726 # convert modulo to a Python integer, and self and other to
1727 # Decimal integers (i.e. force their exponents to be >= 0)
1728 modulo = abs(int(modulo))
1729 base = _WorkRep(self.to_integral_value())
1730 exponent = _WorkRep(other.to_integral_value())
1731
1732 # compute result using integer pow()
1733 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1734 for i in range(exponent.exp):
1735 base = pow(base, 10, modulo)
1736 base = pow(base, exponent.int, modulo)
1737
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001738 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001739
1740 def _power_exact(self, other, p):
1741 """Attempt to compute self**other exactly.
1742
1743 Given Decimals self and other and an integer p, attempt to
1744 compute an exact result for the power self**other, with p
1745 digits of precision. Return None if self**other is not
1746 exactly representable in p digits.
1747
1748 Assumes that elimination of special cases has already been
1749 performed: self and other must both be nonspecial; self must
1750 be positive and not numerically equal to 1; other must be
1751 nonzero. For efficiency, other._exp should not be too large,
1752 so that 10**abs(other._exp) is a feasible calculation."""
1753
1754 # In the comments below, we write x for the value of self and
1755 # y for the value of other. Write x = xc*10**xe and y =
1756 # yc*10**ye.
1757
1758 # The main purpose of this method is to identify the *failure*
1759 # of x**y to be exactly representable with as little effort as
1760 # possible. So we look for cheap and easy tests that
1761 # eliminate the possibility of x**y being exact. Only if all
1762 # these tests are passed do we go on to actually compute x**y.
1763
1764 # Here's the main idea. First normalize both x and y. We
1765 # express y as a rational m/n, with m and n relatively prime
1766 # and n>0. Then for x**y to be exactly representable (at
1767 # *any* precision), xc must be the nth power of a positive
1768 # integer and xe must be divisible by n. If m is negative
1769 # then additionally xc must be a power of either 2 or 5, hence
1770 # a power of 2**n or 5**n.
1771 #
1772 # There's a limit to how small |y| can be: if y=m/n as above
1773 # then:
1774 #
1775 # (1) if xc != 1 then for the result to be representable we
1776 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1777 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1778 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1779 # representable.
1780 #
1781 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1782 # |y| < 1/|xe| then the result is not representable.
1783 #
1784 # Note that since x is not equal to 1, at least one of (1) and
1785 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1786 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1787 #
1788 # There's also a limit to how large y can be, at least if it's
1789 # positive: the normalized result will have coefficient xc**y,
1790 # so if it's representable then xc**y < 10**p, and y <
1791 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1792 # not exactly representable.
1793
1794 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1795 # so |y| < 1/xe and the result is not representable.
1796 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1797 # < 1/nbits(xc).
1798
1799 x = _WorkRep(self)
1800 xc, xe = x.int, x.exp
1801 while xc % 10 == 0:
1802 xc //= 10
1803 xe += 1
1804
1805 y = _WorkRep(other)
1806 yc, ye = y.int, y.exp
1807 while yc % 10 == 0:
1808 yc //= 10
1809 ye += 1
1810
1811 # case where xc == 1: result is 10**(xe*y), with xe*y
1812 # required to be an integer
1813 if xc == 1:
1814 if ye >= 0:
1815 exponent = xe*yc*10**ye
1816 else:
1817 exponent, remainder = divmod(xe*yc, 10**-ye)
1818 if remainder:
1819 return None
1820 if y.sign == 1:
1821 exponent = -exponent
1822 # if other is a nonnegative integer, use ideal exponent
1823 if other._isinteger() and other._sign == 0:
1824 ideal_exponent = self._exp*int(other)
1825 zeros = min(exponent-ideal_exponent, p-1)
1826 else:
1827 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001828 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001829
1830 # case where y is negative: xc must be either a power
1831 # of 2 or a power of 5.
1832 if y.sign == 1:
1833 last_digit = xc % 10
1834 if last_digit in (2,4,6,8):
1835 # quick test for power of 2
1836 if xc & -xc != xc:
1837 return None
1838 # now xc is a power of 2; e is its exponent
1839 e = _nbits(xc)-1
1840 # find e*y and xe*y; both must be integers
1841 if ye >= 0:
1842 y_as_int = yc*10**ye
1843 e = e*y_as_int
1844 xe = xe*y_as_int
1845 else:
1846 ten_pow = 10**-ye
1847 e, remainder = divmod(e*yc, ten_pow)
1848 if remainder:
1849 return None
1850 xe, remainder = divmod(xe*yc, ten_pow)
1851 if remainder:
1852 return None
1853
1854 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1855 return None
1856 xc = 5**e
1857
1858 elif last_digit == 5:
1859 # e >= log_5(xc) if xc is a power of 5; we have
1860 # equality all the way up to xc=5**2658
1861 e = _nbits(xc)*28//65
1862 xc, remainder = divmod(5**e, xc)
1863 if remainder:
1864 return None
1865 while xc % 5 == 0:
1866 xc //= 5
1867 e -= 1
1868 if ye >= 0:
1869 y_as_integer = yc*10**ye
1870 e = e*y_as_integer
1871 xe = xe*y_as_integer
1872 else:
1873 ten_pow = 10**-ye
1874 e, remainder = divmod(e*yc, ten_pow)
1875 if remainder:
1876 return None
1877 xe, remainder = divmod(xe*yc, ten_pow)
1878 if remainder:
1879 return None
1880 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1881 return None
1882 xc = 2**e
1883 else:
1884 return None
1885
1886 if xc >= 10**p:
1887 return None
1888 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001889 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001890
1891 # now y is positive; find m and n such that y = m/n
1892 if ye >= 0:
1893 m, n = yc*10**ye, 1
1894 else:
1895 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1896 return None
1897 xc_bits = _nbits(xc)
1898 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1899 return None
1900 m, n = yc, 10**(-ye)
1901 while m % 2 == n % 2 == 0:
1902 m //= 2
1903 n //= 2
1904 while m % 5 == n % 5 == 0:
1905 m //= 5
1906 n //= 5
1907
1908 # compute nth root of xc*10**xe
1909 if n > 1:
1910 # if 1 < xc < 2**n then xc isn't an nth power
1911 if xc != 1 and xc_bits <= n:
1912 return None
1913
1914 xe, rem = divmod(xe, n)
1915 if rem != 0:
1916 return None
1917
1918 # compute nth root of xc using Newton's method
1919 a = 1 << -(-_nbits(xc)//n) # initial estimate
1920 while True:
1921 q, r = divmod(xc, a**(n-1))
1922 if a <= q:
1923 break
1924 else:
1925 a = (a*(n-1) + q)//n
1926 if not (a == q and r == 0):
1927 return None
1928 xc = a
1929
1930 # now xc*10**xe is the nth root of the original xc*10**xe
1931 # compute mth power of xc*10**xe
1932
1933 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1934 # 10**p and the result is not representable.
1935 if xc > 1 and m > p*100//_log10_lb(xc):
1936 return None
1937 xc = xc**m
1938 xe *= m
1939 if xc > 10**p:
1940 return None
1941
1942 # by this point the result *is* exactly representable
1943 # adjust the exponent to get as close as possible to the ideal
1944 # exponent, if necessary
1945 str_xc = str(xc)
1946 if other._isinteger() and other._sign == 0:
1947 ideal_exponent = self._exp*int(other)
1948 zeros = min(xe-ideal_exponent, p-len(str_xc))
1949 else:
1950 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001951 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001952
1953 def __pow__(self, other, modulo=None, context=None):
1954 """Return self ** other [ % modulo].
1955
1956 With two arguments, compute self**other.
1957
1958 With three arguments, compute (self**other) % modulo. For the
1959 three argument form, the following restrictions on the
1960 arguments hold:
1961
1962 - all three arguments must be integral
1963 - other must be nonnegative
1964 - either self or other (or both) must be nonzero
1965 - modulo must be nonzero and must have at most p digits,
1966 where p is the context precision.
1967
1968 If any of these restrictions is violated the InvalidOperation
1969 flag is raised.
1970
1971 The result of pow(self, other, modulo) is identical to the
1972 result that would be obtained by computing (self**other) %
1973 modulo with unbounded precision, but is computed more
1974 efficiently. It is always exact.
1975 """
1976
1977 if modulo is not None:
1978 return self._power_modulo(other, modulo, context)
1979
1980 other = _convert_other(other)
1981 if other is NotImplemented:
1982 return other
1983
1984 if context is None:
1985 context = getcontext()
1986
1987 # either argument is a NaN => result is NaN
1988 ans = self._check_nans(other, context)
1989 if ans:
1990 return ans
1991
1992 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1993 if not other:
1994 if not self:
1995 return context._raise_error(InvalidOperation, '0 ** 0')
1996 else:
1997 return Dec_p1
1998
1999 # result has sign 1 iff self._sign is 1 and other is an odd integer
2000 result_sign = 0
2001 if self._sign == 1:
2002 if other._isinteger():
2003 if not other._iseven():
2004 result_sign = 1
2005 else:
2006 # -ve**noninteger = NaN
2007 # (-0)**noninteger = 0**noninteger
2008 if self:
2009 return context._raise_error(InvalidOperation,
2010 'x ** y with x negative and y not an integer')
2011 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002012 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002013
2014 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2015 if not self:
2016 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002017 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002018 else:
2019 return Infsign[result_sign]
2020
2021 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002022 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002023 if other._sign == 0:
2024 return Infsign[result_sign]
2025 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002026 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002027
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002028 # 1**other = 1, but the choice of exponent and the flags
2029 # depend on the exponent of self, and on whether other is a
2030 # positive integer, a negative integer, or neither
2031 if self == Dec_p1:
2032 if other._isinteger():
2033 # exp = max(self._exp*max(int(other), 0),
2034 # 1-context.prec) but evaluating int(other) directly
2035 # is dangerous until we know other is small (other
2036 # could be 1e999999999)
2037 if other._sign == 1:
2038 multiplier = 0
2039 elif other > context.prec:
2040 multiplier = context.prec
2041 else:
2042 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002043
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002044 exp = self._exp * multiplier
2045 if exp < 1-context.prec:
2046 exp = 1-context.prec
2047 context._raise_error(Rounded)
2048 else:
2049 context._raise_error(Inexact)
2050 context._raise_error(Rounded)
2051 exp = 1-context.prec
2052
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002053 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002054
2055 # compute adjusted exponent of self
2056 self_adj = self.adjusted()
2057
2058 # self ** infinity is infinity if self > 1, 0 if self < 1
2059 # self ** -infinity is infinity if self < 1, 0 if self > 1
2060 if other._isinfinity():
2061 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002062 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002063 else:
2064 return Infsign[result_sign]
2065
2066 # from here on, the result always goes through the call
2067 # to _fix at the end of this function.
2068 ans = None
2069
2070 # crude test to catch cases of extreme overflow/underflow. If
2071 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2072 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2073 # self**other >= 10**(Emax+1), so overflow occurs. The test
2074 # for underflow is similar.
2075 bound = self._log10_exp_bound() + other.adjusted()
2076 if (self_adj >= 0) == (other._sign == 0):
2077 # self > 1 and other +ve, or self < 1 and other -ve
2078 # possibility of overflow
2079 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002080 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002081 else:
2082 # self > 1 and other -ve, or self < 1 and other +ve
2083 # possibility of underflow to 0
2084 Etiny = context.Etiny()
2085 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002086 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002087
2088 # try for an exact result with precision +1
2089 if ans is None:
2090 ans = self._power_exact(other, context.prec + 1)
2091 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002092 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002093
2094 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2095 if ans is None:
2096 p = context.prec
2097 x = _WorkRep(self)
2098 xc, xe = x.int, x.exp
2099 y = _WorkRep(other)
2100 yc, ye = y.int, y.exp
2101 if y.sign == 1:
2102 yc = -yc
2103
2104 # compute correctly rounded result: start with precision +3,
2105 # then increase precision until result is unambiguously roundable
2106 extra = 3
2107 while True:
2108 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2109 if coeff % (5*10**(len(str(coeff))-p-1)):
2110 break
2111 extra += 3
2112
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002113 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002114
2115 # the specification says that for non-integer other we need to
2116 # raise Inexact, even when the result is actually exact. In
2117 # the same way, we need to raise Underflow here if the result
2118 # is subnormal. (The call to _fix will take care of raising
2119 # Rounded and Subnormal, as usual.)
2120 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002121 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002122 # pad with zeros up to length context.prec+1 if necessary
2123 if len(ans._int) <= context.prec:
2124 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002125 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2126 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002127 if ans.adjusted() < context.Emin:
2128 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002129
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002130 # unlike exp, ln and log10, the power function respects the
2131 # rounding mode; no need to use ROUND_HALF_EVEN here
2132 ans = ans._fix(context)
2133 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002134
2135 def __rpow__(self, other, context=None):
2136 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002137 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002138 if other is NotImplemented:
2139 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002140 return other.__pow__(self, context=context)
2141
2142 def normalize(self, context=None):
2143 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002144
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002145 if context is None:
2146 context = getcontext()
2147
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002148 if self._is_special:
2149 ans = self._check_nans(context=context)
2150 if ans:
2151 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002152
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002153 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002154 if dup._isinfinity():
2155 return dup
2156
2157 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002158 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002159 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002160 end = len(dup._int)
2161 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002162 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002163 exp += 1
2164 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002165 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002166
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002167 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002168 """Quantize self so its exponent is the same as that of exp.
2169
2170 Similar to self._rescale(exp._exp) but with error checking.
2171 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002172 exp = _convert_other(exp, raiseit=True)
2173
2174 if context is None:
2175 context = getcontext()
2176 if rounding is None:
2177 rounding = context.rounding
2178
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002179 if self._is_special or exp._is_special:
2180 ans = self._check_nans(exp, context)
2181 if ans:
2182 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002183
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002184 if exp._isinfinity() or self._isinfinity():
2185 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002186 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002187 return context._raise_error(InvalidOperation,
2188 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002189
2190 # if we're not watching exponents, do a simple rescale
2191 if not watchexp:
2192 ans = self._rescale(exp._exp, rounding)
2193 # raise Inexact and Rounded where appropriate
2194 if ans._exp > self._exp:
2195 context._raise_error(Rounded)
2196 if ans != self:
2197 context._raise_error(Inexact)
2198 return ans
2199
2200 # exp._exp should be between Etiny and Emax
2201 if not (context.Etiny() <= exp._exp <= context.Emax):
2202 return context._raise_error(InvalidOperation,
2203 'target exponent out of bounds in quantize')
2204
2205 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002206 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002207 return ans._fix(context)
2208
2209 self_adjusted = self.adjusted()
2210 if self_adjusted > context.Emax:
2211 return context._raise_error(InvalidOperation,
2212 'exponent of quantize result too large for current context')
2213 if self_adjusted - exp._exp + 1 > context.prec:
2214 return context._raise_error(InvalidOperation,
2215 'quantize result has too many digits for current context')
2216
2217 ans = self._rescale(exp._exp, rounding)
2218 if ans.adjusted() > context.Emax:
2219 return context._raise_error(InvalidOperation,
2220 'exponent of quantize result too large for current context')
2221 if len(ans._int) > context.prec:
2222 return context._raise_error(InvalidOperation,
2223 'quantize result has too many digits for current context')
2224
2225 # raise appropriate flags
2226 if ans._exp > self._exp:
2227 context._raise_error(Rounded)
2228 if ans != self:
2229 context._raise_error(Inexact)
2230 if ans and ans.adjusted() < context.Emin:
2231 context._raise_error(Subnormal)
2232
2233 # call to fix takes care of any necessary folddown
2234 ans = ans._fix(context)
2235 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002236
2237 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002238 """Return True if self and other have the same exponent; otherwise
2239 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002240
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002241 If either operand is a special value, the following rules are used:
2242 * return True if both operands are infinities
2243 * return True if both operands are NaNs
2244 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002245 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002246 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002247 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002248 return (self.is_nan() and other.is_nan() or
2249 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002250 return self._exp == other._exp
2251
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002252 def _rescale(self, exp, rounding):
2253 """Rescale self so that the exponent is exp, either by padding with zeros
2254 or by truncating digits, using the given rounding mode.
2255
2256 Specials are returned without change. This operation is
2257 quiet: it raises no flags, and uses no information from the
2258 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002259
2260 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002261 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002262 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002263 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002264 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002265 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002266 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002267
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002268 if self._exp >= exp:
2269 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002270 return _dec_from_triple(self._sign,
2271 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002272
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002273 # too many digits; round and lose data. If self.adjusted() <
2274 # exp-1, replace self by 10**(exp-1) before rounding
2275 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002276 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002277 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002278 digits = 0
2279 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002280 changed = this_function(digits)
2281 coeff = self._int[:digits] or '0'
2282 if changed == 1:
2283 coeff = str(int(coeff)+1)
2284 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002285
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002286 def to_integral_exact(self, rounding=None, context=None):
2287 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002288
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002289 If no rounding mode is specified, take the rounding mode from
2290 the context. This method raises the Rounded and Inexact flags
2291 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002292
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002293 See also: to_integral_value, which does exactly the same as
2294 this method except that it doesn't raise Inexact or Rounded.
2295 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002296 if self._is_special:
2297 ans = self._check_nans(context=context)
2298 if ans:
2299 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002300 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002301 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002302 return Decimal(self)
2303 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002304 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002305 if context is None:
2306 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002307 if rounding is None:
2308 rounding = context.rounding
2309 context._raise_error(Rounded)
2310 ans = self._rescale(0, rounding)
2311 if ans != self:
2312 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002313 return ans
2314
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002315 def to_integral_value(self, rounding=None, context=None):
2316 """Rounds to the nearest integer, without raising inexact, rounded."""
2317 if context is None:
2318 context = getcontext()
2319 if rounding is None:
2320 rounding = context.rounding
2321 if self._is_special:
2322 ans = self._check_nans(context=context)
2323 if ans:
2324 return ans
2325 return Decimal(self)
2326 if self._exp >= 0:
2327 return Decimal(self)
2328 else:
2329 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002330
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002331 # the method name changed, but we provide also the old one, for compatibility
2332 to_integral = to_integral_value
2333
2334 def sqrt(self, context=None):
2335 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002336 if self._is_special:
2337 ans = self._check_nans(context=context)
2338 if ans:
2339 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002340
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002341 if self._isinfinity() and self._sign == 0:
2342 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002343
2344 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002345 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002346 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002347 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002348
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002349 if context is None:
2350 context = getcontext()
2351
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002352 if self._sign == 1:
2353 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2354
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002355 # At this point self represents a positive number. Let p be
2356 # the desired precision and express self in the form c*100**e
2357 # with c a positive real number and e an integer, c and e
2358 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2359 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2360 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2361 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2362 # the closest integer to sqrt(c) with the even integer chosen
2363 # in the case of a tie.
2364 #
2365 # To ensure correct rounding in all cases, we use the
2366 # following trick: we compute the square root to an extra
2367 # place (precision p+1 instead of precision p), rounding down.
2368 # Then, if the result is inexact and its last digit is 0 or 5,
2369 # we increase the last digit to 1 or 6 respectively; if it's
2370 # exact we leave the last digit alone. Now the final round to
2371 # p places (or fewer in the case of underflow) will round
2372 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002373
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002374 # use an extra digit of precision
2375 prec = context.prec+1
2376
2377 # write argument in the form c*100**e where e = self._exp//2
2378 # is the 'ideal' exponent, to be used if the square root is
2379 # exactly representable. l is the number of 'digits' of c in
2380 # base 100, so that 100**(l-1) <= c < 100**l.
2381 op = _WorkRep(self)
2382 e = op.exp >> 1
2383 if op.exp & 1:
2384 c = op.int * 10
2385 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002386 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002387 c = op.int
2388 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002389
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002390 # rescale so that c has exactly prec base 100 'digits'
2391 shift = prec-l
2392 if shift >= 0:
2393 c *= 100**shift
2394 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002395 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002396 c, remainder = divmod(c, 100**-shift)
2397 exact = not remainder
2398 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002399
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002400 # find n = floor(sqrt(c)) using Newton's method
2401 n = 10**prec
2402 while True:
2403 q = c//n
2404 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002405 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002406 else:
2407 n = n + q >> 1
2408 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002409
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002410 if exact:
2411 # result is exact; rescale to use ideal exponent e
2412 if shift >= 0:
2413 # assert n % 10**shift == 0
2414 n //= 10**shift
2415 else:
2416 n *= 10**-shift
2417 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002418 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002419 # result is not exact; fix last digit as described above
2420 if n % 5 == 0:
2421 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002422
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002423 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002424
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002425 # round, and fit to current context
2426 context = context._shallow_copy()
2427 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002428 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002429 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002430
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002431 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002432
2433 def max(self, other, context=None):
2434 """Returns the larger value.
2435
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002436 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002437 NaN (and signals if one is sNaN). Also rounds.
2438 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002439 other = _convert_other(other, raiseit=True)
2440
2441 if context is None:
2442 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002443
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002444 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002445 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002446 # number is always returned
2447 sn = self._isnan()
2448 on = other._isnan()
2449 if sn or on:
2450 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002451 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002452 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002453 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002454 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002455
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002456 c = self.__cmp__(other)
2457 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002458 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002459 # then an ordering is applied:
2460 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002461 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002462 # positive sign and min returns the operand with the negative sign
2463 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002464 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002465 # the result. This is exactly the ordering used in compare_total.
2466 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002467
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002468 if c == -1:
2469 ans = other
2470 else:
2471 ans = self
2472
Christian Heimes2c181612007-12-17 20:04:13 +00002473 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002474
2475 def min(self, other, context=None):
2476 """Returns the smaller value.
2477
Guido van Rossumd8faa362007-04-27 19:54:29 +00002478 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002479 NaN (and signals if one is sNaN). Also rounds.
2480 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002481 other = _convert_other(other, raiseit=True)
2482
2483 if context is None:
2484 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002485
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002486 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002487 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002488 # number is always returned
2489 sn = self._isnan()
2490 on = other._isnan()
2491 if sn or on:
2492 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002493 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002494 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002495 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002496 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002497
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002498 c = self.__cmp__(other)
2499 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002500 c = self.compare_total(other)
2501
2502 if c == -1:
2503 ans = self
2504 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002505 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002506
Christian Heimes2c181612007-12-17 20:04:13 +00002507 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002508
2509 def _isinteger(self):
2510 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002511 if self._is_special:
2512 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002513 if self._exp >= 0:
2514 return True
2515 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002516 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002517
2518 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002519 """Returns True if self is even. Assumes self is an integer."""
2520 if not self or self._exp > 0:
2521 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002522 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002523
2524 def adjusted(self):
2525 """Return the adjusted exponent of self"""
2526 try:
2527 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002528 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002529 except TypeError:
2530 return 0
2531
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002532 def canonical(self, context=None):
2533 """Returns the same Decimal object.
2534
2535 As we do not have different encodings for the same number, the
2536 received object already is in its canonical form.
2537 """
2538 return self
2539
2540 def compare_signal(self, other, context=None):
2541 """Compares self to the other operand numerically.
2542
2543 It's pretty much like compare(), but all NaNs signal, with signaling
2544 NaNs taking precedence over quiet NaNs.
2545 """
2546 if context is None:
2547 context = getcontext()
2548
2549 self_is_nan = self._isnan()
2550 other_is_nan = other._isnan()
2551 if self_is_nan == 2:
2552 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002553 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002554 if other_is_nan == 2:
2555 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002556 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002557 if self_is_nan:
2558 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002559 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002560 if other_is_nan:
2561 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002562 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002563 return self.compare(other, context=context)
2564
2565 def compare_total(self, other):
2566 """Compares self to other using the abstract representations.
2567
2568 This is not like the standard compare, which use their numerical
2569 value. Note that a total ordering is defined for all possible abstract
2570 representations.
2571 """
2572 # if one is negative and the other is positive, it's easy
2573 if self._sign and not other._sign:
2574 return Dec_n1
2575 if not self._sign and other._sign:
2576 return Dec_p1
2577 sign = self._sign
2578
2579 # let's handle both NaN types
2580 self_nan = self._isnan()
2581 other_nan = other._isnan()
2582 if self_nan or other_nan:
2583 if self_nan == other_nan:
2584 if self._int < other._int:
2585 if sign:
2586 return Dec_p1
2587 else:
2588 return Dec_n1
2589 if self._int > other._int:
2590 if sign:
2591 return Dec_n1
2592 else:
2593 return Dec_p1
2594 return Dec_0
2595
2596 if sign:
2597 if self_nan == 1:
2598 return Dec_n1
2599 if other_nan == 1:
2600 return Dec_p1
2601 if self_nan == 2:
2602 return Dec_n1
2603 if other_nan == 2:
2604 return Dec_p1
2605 else:
2606 if self_nan == 1:
2607 return Dec_p1
2608 if other_nan == 1:
2609 return Dec_n1
2610 if self_nan == 2:
2611 return Dec_p1
2612 if other_nan == 2:
2613 return Dec_n1
2614
2615 if self < other:
2616 return Dec_n1
2617 if self > other:
2618 return Dec_p1
2619
2620 if self._exp < other._exp:
2621 if sign:
2622 return Dec_p1
2623 else:
2624 return Dec_n1
2625 if self._exp > other._exp:
2626 if sign:
2627 return Dec_n1
2628 else:
2629 return Dec_p1
2630 return Dec_0
2631
2632
2633 def compare_total_mag(self, other):
2634 """Compares self to other using abstract repr., ignoring sign.
2635
2636 Like compare_total, but with operand's sign ignored and assumed to be 0.
2637 """
2638 s = self.copy_abs()
2639 o = other.copy_abs()
2640 return s.compare_total(o)
2641
2642 def copy_abs(self):
2643 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002644 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002645
2646 def copy_negate(self):
2647 """Returns a copy with the sign inverted."""
2648 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002649 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002650 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002651 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002652
2653 def copy_sign(self, other):
2654 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002655 return _dec_from_triple(other._sign, self._int,
2656 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002657
2658 def exp(self, context=None):
2659 """Returns e ** self."""
2660
2661 if context is None:
2662 context = getcontext()
2663
2664 # exp(NaN) = NaN
2665 ans = self._check_nans(context=context)
2666 if ans:
2667 return ans
2668
2669 # exp(-Infinity) = 0
2670 if self._isinfinity() == -1:
2671 return Dec_0
2672
2673 # exp(0) = 1
2674 if not self:
2675 return Dec_p1
2676
2677 # exp(Infinity) = Infinity
2678 if self._isinfinity() == 1:
2679 return Decimal(self)
2680
2681 # the result is now guaranteed to be inexact (the true
2682 # mathematical result is transcendental). There's no need to
2683 # raise Rounded and Inexact here---they'll always be raised as
2684 # a result of the call to _fix.
2685 p = context.prec
2686 adj = self.adjusted()
2687
2688 # we only need to do any computation for quite a small range
2689 # of adjusted exponents---for example, -29 <= adj <= 10 for
2690 # the default context. For smaller exponent the result is
2691 # indistinguishable from 1 at the given precision, while for
2692 # larger exponent the result either overflows or underflows.
2693 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2694 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002695 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002696 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2697 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002698 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002699 elif self._sign == 0 and adj < -p:
2700 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002701 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002702 elif self._sign == 1 and adj < -p-1:
2703 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002704 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002705 # general case
2706 else:
2707 op = _WorkRep(self)
2708 c, e = op.int, op.exp
2709 if op.sign == 1:
2710 c = -c
2711
2712 # compute correctly rounded result: increase precision by
2713 # 3 digits at a time until we get an unambiguously
2714 # roundable result
2715 extra = 3
2716 while True:
2717 coeff, exp = _dexp(c, e, p+extra)
2718 if coeff % (5*10**(len(str(coeff))-p-1)):
2719 break
2720 extra += 3
2721
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002722 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002723
2724 # at this stage, ans should round correctly with *any*
2725 # rounding mode, not just with ROUND_HALF_EVEN
2726 context = context._shallow_copy()
2727 rounding = context._set_rounding(ROUND_HALF_EVEN)
2728 ans = ans._fix(context)
2729 context.rounding = rounding
2730
2731 return ans
2732
2733 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002734 """Return True if self is canonical; otherwise return False.
2735
2736 Currently, the encoding of a Decimal instance is always
2737 canonical, so this method returns True for any Decimal.
2738 """
2739 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002740
2741 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002742 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002743
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002744 A Decimal instance is considered finite if it is neither
2745 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002746 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002747 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002748
2749 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002750 """Return True if self is infinite; otherwise return False."""
2751 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002752
2753 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002754 """Return True if self is a qNaN or sNaN; otherwise return False."""
2755 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002756
2757 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002758 """Return True if self is a normal number; otherwise return False."""
2759 if self._is_special or not self:
2760 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002761 if context is None:
2762 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002763 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002764
2765 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002766 """Return True if self is a quiet NaN; otherwise return False."""
2767 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002768
2769 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002770 """Return True if self is negative; otherwise return False."""
2771 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002772
2773 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002774 """Return True if self is a signaling NaN; otherwise return False."""
2775 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002776
2777 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002778 """Return True if self is subnormal; otherwise return False."""
2779 if self._is_special or not self:
2780 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002781 if context is None:
2782 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002783 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002784
2785 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002786 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002787 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002788
2789 def _ln_exp_bound(self):
2790 """Compute a lower bound for the adjusted exponent of self.ln().
2791 In other words, compute r such that self.ln() >= 10**r. Assumes
2792 that self is finite and positive and that self != 1.
2793 """
2794
2795 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2796 adj = self._exp + len(self._int) - 1
2797 if adj >= 1:
2798 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2799 return len(str(adj*23//10)) - 1
2800 if adj <= -2:
2801 # argument <= 0.1
2802 return len(str((-1-adj)*23//10)) - 1
2803 op = _WorkRep(self)
2804 c, e = op.int, op.exp
2805 if adj == 0:
2806 # 1 < self < 10
2807 num = str(c-10**-e)
2808 den = str(c)
2809 return len(num) - len(den) - (num < den)
2810 # adj == -1, 0.1 <= self < 1
2811 return e + len(str(10**-e - c)) - 1
2812
2813
2814 def ln(self, context=None):
2815 """Returns the natural (base e) logarithm of self."""
2816
2817 if context is None:
2818 context = getcontext()
2819
2820 # ln(NaN) = NaN
2821 ans = self._check_nans(context=context)
2822 if ans:
2823 return ans
2824
2825 # ln(0.0) == -Infinity
2826 if not self:
2827 return negInf
2828
2829 # ln(Infinity) = Infinity
2830 if self._isinfinity() == 1:
2831 return Inf
2832
2833 # ln(1.0) == 0.0
2834 if self == Dec_p1:
2835 return Dec_0
2836
2837 # ln(negative) raises InvalidOperation
2838 if self._sign == 1:
2839 return context._raise_error(InvalidOperation,
2840 'ln of a negative value')
2841
2842 # result is irrational, so necessarily inexact
2843 op = _WorkRep(self)
2844 c, e = op.int, op.exp
2845 p = context.prec
2846
2847 # correctly rounded result: repeatedly increase precision by 3
2848 # until we get an unambiguously roundable result
2849 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2850 while True:
2851 coeff = _dlog(c, e, places)
2852 # assert len(str(abs(coeff)))-p >= 1
2853 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2854 break
2855 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002856 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002857
2858 context = context._shallow_copy()
2859 rounding = context._set_rounding(ROUND_HALF_EVEN)
2860 ans = ans._fix(context)
2861 context.rounding = rounding
2862 return ans
2863
2864 def _log10_exp_bound(self):
2865 """Compute a lower bound for the adjusted exponent of self.log10().
2866 In other words, find r such that self.log10() >= 10**r.
2867 Assumes that self is finite and positive and that self != 1.
2868 """
2869
2870 # For x >= 10 or x < 0.1 we only need a bound on the integer
2871 # part of log10(self), and this comes directly from the
2872 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2873 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2874 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2875
2876 adj = self._exp + len(self._int) - 1
2877 if adj >= 1:
2878 # self >= 10
2879 return len(str(adj))-1
2880 if adj <= -2:
2881 # self < 0.1
2882 return len(str(-1-adj))-1
2883 op = _WorkRep(self)
2884 c, e = op.int, op.exp
2885 if adj == 0:
2886 # 1 < self < 10
2887 num = str(c-10**-e)
2888 den = str(231*c)
2889 return len(num) - len(den) - (num < den) + 2
2890 # adj == -1, 0.1 <= self < 1
2891 num = str(10**-e-c)
2892 return len(num) + e - (num < "231") - 1
2893
2894 def log10(self, context=None):
2895 """Returns the base 10 logarithm of self."""
2896
2897 if context is None:
2898 context = getcontext()
2899
2900 # log10(NaN) = NaN
2901 ans = self._check_nans(context=context)
2902 if ans:
2903 return ans
2904
2905 # log10(0.0) == -Infinity
2906 if not self:
2907 return negInf
2908
2909 # log10(Infinity) = Infinity
2910 if self._isinfinity() == 1:
2911 return Inf
2912
2913 # log10(negative or -Infinity) raises InvalidOperation
2914 if self._sign == 1:
2915 return context._raise_error(InvalidOperation,
2916 'log10 of a negative value')
2917
2918 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002919 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002920 # answer may need rounding
2921 ans = Decimal(self._exp + len(self._int) - 1)
2922 else:
2923 # result is irrational, so necessarily inexact
2924 op = _WorkRep(self)
2925 c, e = op.int, op.exp
2926 p = context.prec
2927
2928 # correctly rounded result: repeatedly increase precision
2929 # until result is unambiguously roundable
2930 places = p-self._log10_exp_bound()+2
2931 while True:
2932 coeff = _dlog10(c, e, places)
2933 # assert len(str(abs(coeff)))-p >= 1
2934 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2935 break
2936 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002937 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002938
2939 context = context._shallow_copy()
2940 rounding = context._set_rounding(ROUND_HALF_EVEN)
2941 ans = ans._fix(context)
2942 context.rounding = rounding
2943 return ans
2944
2945 def logb(self, context=None):
2946 """ Returns the exponent of the magnitude of self's MSD.
2947
2948 The result is the integer which is the exponent of the magnitude
2949 of the most significant digit of self (as though it were truncated
2950 to a single digit while maintaining the value of that digit and
2951 without limiting the resulting exponent).
2952 """
2953 # logb(NaN) = NaN
2954 ans = self._check_nans(context=context)
2955 if ans:
2956 return ans
2957
2958 if context is None:
2959 context = getcontext()
2960
2961 # logb(+/-Inf) = +Inf
2962 if self._isinfinity():
2963 return Inf
2964
2965 # logb(0) = -Inf, DivisionByZero
2966 if not self:
2967 return context._raise_error(DivisionByZero, 'logb(0)', 1)
2968
2969 # otherwise, simply return the adjusted exponent of self, as a
2970 # Decimal. Note that no attempt is made to fit the result
2971 # into the current context.
2972 return Decimal(self.adjusted())
2973
2974 def _islogical(self):
2975 """Return True if self is a logical operand.
2976
2977 For being logical, it must be a finite numbers with a sign of 0,
2978 an exponent of 0, and a coefficient whose digits must all be
2979 either 0 or 1.
2980 """
2981 if self._sign != 0 or self._exp != 0:
2982 return False
2983 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002984 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002985 return False
2986 return True
2987
2988 def _fill_logical(self, context, opa, opb):
2989 dif = context.prec - len(opa)
2990 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002991 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002992 elif dif < 0:
2993 opa = opa[-context.prec:]
2994 dif = context.prec - len(opb)
2995 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002996 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002997 elif dif < 0:
2998 opb = opb[-context.prec:]
2999 return opa, opb
3000
3001 def logical_and(self, other, context=None):
3002 """Applies an 'and' operation between self and other's digits."""
3003 if context is None:
3004 context = getcontext()
3005 if not self._islogical() or not other._islogical():
3006 return context._raise_error(InvalidOperation)
3007
3008 # fill to context.prec
3009 (opa, opb) = self._fill_logical(context, self._int, other._int)
3010
3011 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003012 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3013 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003014
3015 def logical_invert(self, context=None):
3016 """Invert all its digits."""
3017 if context is None:
3018 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003019 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3020 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003021
3022 def logical_or(self, other, context=None):
3023 """Applies an 'or' operation between self and other's digits."""
3024 if context is None:
3025 context = getcontext()
3026 if not self._islogical() or not other._islogical():
3027 return context._raise_error(InvalidOperation)
3028
3029 # fill to context.prec
3030 (opa, opb) = self._fill_logical(context, self._int, other._int)
3031
3032 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003033 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3034 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003035
3036 def logical_xor(self, other, context=None):
3037 """Applies an 'xor' operation between self and other's digits."""
3038 if context is None:
3039 context = getcontext()
3040 if not self._islogical() or not other._islogical():
3041 return context._raise_error(InvalidOperation)
3042
3043 # fill to context.prec
3044 (opa, opb) = self._fill_logical(context, self._int, other._int)
3045
3046 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003047 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3048 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003049
3050 def max_mag(self, other, context=None):
3051 """Compares the values numerically with their sign ignored."""
3052 other = _convert_other(other, raiseit=True)
3053
3054 if context is None:
3055 context = getcontext()
3056
3057 if self._is_special or other._is_special:
3058 # If one operand is a quiet NaN and the other is number, then the
3059 # number is always returned
3060 sn = self._isnan()
3061 on = other._isnan()
3062 if sn or on:
3063 if on == 1 and sn != 2:
3064 return self._fix_nan(context)
3065 if sn == 1 and on != 2:
3066 return other._fix_nan(context)
3067 return self._check_nans(other, context)
3068
3069 c = self.copy_abs().__cmp__(other.copy_abs())
3070 if c == 0:
3071 c = self.compare_total(other)
3072
3073 if c == -1:
3074 ans = other
3075 else:
3076 ans = self
3077
Christian Heimes2c181612007-12-17 20:04:13 +00003078 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003079
3080 def min_mag(self, other, context=None):
3081 """Compares the values numerically with their sign ignored."""
3082 other = _convert_other(other, raiseit=True)
3083
3084 if context is None:
3085 context = getcontext()
3086
3087 if self._is_special or other._is_special:
3088 # If one operand is a quiet NaN and the other is number, then the
3089 # number is always returned
3090 sn = self._isnan()
3091 on = other._isnan()
3092 if sn or on:
3093 if on == 1 and sn != 2:
3094 return self._fix_nan(context)
3095 if sn == 1 and on != 2:
3096 return other._fix_nan(context)
3097 return self._check_nans(other, context)
3098
3099 c = self.copy_abs().__cmp__(other.copy_abs())
3100 if c == 0:
3101 c = self.compare_total(other)
3102
3103 if c == -1:
3104 ans = self
3105 else:
3106 ans = other
3107
Christian Heimes2c181612007-12-17 20:04:13 +00003108 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003109
3110 def next_minus(self, context=None):
3111 """Returns the largest representable number smaller than itself."""
3112 if context is None:
3113 context = getcontext()
3114
3115 ans = self._check_nans(context=context)
3116 if ans:
3117 return ans
3118
3119 if self._isinfinity() == -1:
3120 return negInf
3121 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003122 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003123
3124 context = context.copy()
3125 context._set_rounding(ROUND_FLOOR)
3126 context._ignore_all_flags()
3127 new_self = self._fix(context)
3128 if new_self != self:
3129 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003130 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3131 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003132
3133 def next_plus(self, context=None):
3134 """Returns the smallest representable number larger than itself."""
3135 if context is None:
3136 context = getcontext()
3137
3138 ans = self._check_nans(context=context)
3139 if ans:
3140 return ans
3141
3142 if self._isinfinity() == 1:
3143 return Inf
3144 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003145 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003146
3147 context = context.copy()
3148 context._set_rounding(ROUND_CEILING)
3149 context._ignore_all_flags()
3150 new_self = self._fix(context)
3151 if new_self != self:
3152 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003153 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3154 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003155
3156 def next_toward(self, other, context=None):
3157 """Returns the number closest to self, in the direction towards other.
3158
3159 The result is the closest representable number to self
3160 (excluding self) that is in the direction towards other,
3161 unless both have the same value. If the two operands are
3162 numerically equal, then the result is a copy of self with the
3163 sign set to be the same as the sign of other.
3164 """
3165 other = _convert_other(other, raiseit=True)
3166
3167 if context is None:
3168 context = getcontext()
3169
3170 ans = self._check_nans(other, context)
3171 if ans:
3172 return ans
3173
3174 comparison = self.__cmp__(other)
3175 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003176 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003177
3178 if comparison == -1:
3179 ans = self.next_plus(context)
3180 else: # comparison == 1
3181 ans = self.next_minus(context)
3182
3183 # decide which flags to raise using value of ans
3184 if ans._isinfinity():
3185 context._raise_error(Overflow,
3186 'Infinite result from next_toward',
3187 ans._sign)
3188 context._raise_error(Rounded)
3189 context._raise_error(Inexact)
3190 elif ans.adjusted() < context.Emin:
3191 context._raise_error(Underflow)
3192 context._raise_error(Subnormal)
3193 context._raise_error(Rounded)
3194 context._raise_error(Inexact)
3195 # if precision == 1 then we don't raise Clamped for a
3196 # result 0E-Etiny.
3197 if not ans:
3198 context._raise_error(Clamped)
3199
3200 return ans
3201
3202 def number_class(self, context=None):
3203 """Returns an indication of the class of self.
3204
3205 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003206 sNaN
3207 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003208 -Infinity
3209 -Normal
3210 -Subnormal
3211 -Zero
3212 +Zero
3213 +Subnormal
3214 +Normal
3215 +Infinity
3216 """
3217 if self.is_snan():
3218 return "sNaN"
3219 if self.is_qnan():
3220 return "NaN"
3221 inf = self._isinfinity()
3222 if inf == 1:
3223 return "+Infinity"
3224 if inf == -1:
3225 return "-Infinity"
3226 if self.is_zero():
3227 if self._sign:
3228 return "-Zero"
3229 else:
3230 return "+Zero"
3231 if context is None:
3232 context = getcontext()
3233 if self.is_subnormal(context=context):
3234 if self._sign:
3235 return "-Subnormal"
3236 else:
3237 return "+Subnormal"
3238 # just a normal, regular, boring number, :)
3239 if self._sign:
3240 return "-Normal"
3241 else:
3242 return "+Normal"
3243
3244 def radix(self):
3245 """Just returns 10, as this is Decimal, :)"""
3246 return Decimal(10)
3247
3248 def rotate(self, other, context=None):
3249 """Returns a rotated copy of self, value-of-other times."""
3250 if context is None:
3251 context = getcontext()
3252
3253 ans = self._check_nans(other, context)
3254 if ans:
3255 return ans
3256
3257 if other._exp != 0:
3258 return context._raise_error(InvalidOperation)
3259 if not (-context.prec <= int(other) <= context.prec):
3260 return context._raise_error(InvalidOperation)
3261
3262 if self._isinfinity():
3263 return Decimal(self)
3264
3265 # get values, pad if necessary
3266 torot = int(other)
3267 rotdig = self._int
3268 topad = context.prec - len(rotdig)
3269 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003270 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003271
3272 # let's rotate!
3273 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003274 return _dec_from_triple(self._sign,
3275 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003276
3277 def scaleb (self, other, context=None):
3278 """Returns self operand after adding the second value to its exp."""
3279 if context is None:
3280 context = getcontext()
3281
3282 ans = self._check_nans(other, context)
3283 if ans:
3284 return ans
3285
3286 if other._exp != 0:
3287 return context._raise_error(InvalidOperation)
3288 liminf = -2 * (context.Emax + context.prec)
3289 limsup = 2 * (context.Emax + context.prec)
3290 if not (liminf <= int(other) <= limsup):
3291 return context._raise_error(InvalidOperation)
3292
3293 if self._isinfinity():
3294 return Decimal(self)
3295
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003296 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003297 d = d._fix(context)
3298 return d
3299
3300 def shift(self, other, context=None):
3301 """Returns a shifted copy of self, value-of-other times."""
3302 if context is None:
3303 context = getcontext()
3304
3305 ans = self._check_nans(other, context)
3306 if ans:
3307 return ans
3308
3309 if other._exp != 0:
3310 return context._raise_error(InvalidOperation)
3311 if not (-context.prec <= int(other) <= context.prec):
3312 return context._raise_error(InvalidOperation)
3313
3314 if self._isinfinity():
3315 return Decimal(self)
3316
3317 # get values, pad if necessary
3318 torot = int(other)
3319 if not torot:
3320 return Decimal(self)
3321 rotdig = self._int
3322 topad = context.prec - len(rotdig)
3323 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003324 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003325
3326 # let's shift!
3327 if torot < 0:
3328 rotated = rotdig[:torot]
3329 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003330 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003331 rotated = rotated[-context.prec:]
3332
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003333 return _dec_from_triple(self._sign,
3334 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003335
Guido van Rossumd8faa362007-04-27 19:54:29 +00003336 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003337 def __reduce__(self):
3338 return (self.__class__, (str(self),))
3339
3340 def __copy__(self):
3341 if type(self) == Decimal:
3342 return self # I'm immutable; therefore I am my own clone
3343 return self.__class__(str(self))
3344
3345 def __deepcopy__(self, memo):
3346 if type(self) == Decimal:
3347 return self # My components are also immutable
3348 return self.__class__(str(self))
3349
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003350def _dec_from_triple(sign, coefficient, exponent, special=False):
3351 """Create a decimal instance directly, without any validation,
3352 normalization (e.g. removal of leading zeros) or argument
3353 conversion.
3354
3355 This function is for *internal use only*.
3356 """
3357
3358 self = object.__new__(Decimal)
3359 self._sign = sign
3360 self._int = coefficient
3361 self._exp = exponent
3362 self._is_special = special
3363
3364 return self
3365
Guido van Rossumd8faa362007-04-27 19:54:29 +00003366##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003367
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003368
3369# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003370rounding_functions = [name for name in Decimal.__dict__.keys()
3371 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003372for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003373 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003374 globalname = name[1:].upper()
3375 val = globals()[globalname]
3376 Decimal._pick_rounding_function[val] = name
3377
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003378del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003379
Thomas Wouters89f507f2006-12-13 04:49:30 +00003380class _ContextManager(object):
3381 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003382
Thomas Wouters89f507f2006-12-13 04:49:30 +00003383 Sets a copy of the supplied context in __enter__() and restores
3384 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003385 """
3386 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003387 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003388 def __enter__(self):
3389 self.saved_context = getcontext()
3390 setcontext(self.new_context)
3391 return self.new_context
3392 def __exit__(self, t, v, tb):
3393 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003394
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003395class Context(object):
3396 """Contains the context for a Decimal instance.
3397
3398 Contains:
3399 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003400 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003401 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003402 raised when it is caused. Otherwise, a value is
3403 substituted in.
3404 flags - When an exception is caused, flags[exception] is incremented.
3405 (Whether or not the trap_enabler is set)
3406 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003407 Emin - Minimum exponent
3408 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003409 capitals - If 1, 1*10^1 is printed as 1E+1.
3410 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003411 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003412 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003413
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003414 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003415 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003416 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003417 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003418 _ignored_flags=None):
3419 if flags is None:
3420 flags = []
3421 if _ignored_flags is None:
3422 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003423 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003424 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003425 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003426 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003427 for name, val in locals().items():
3428 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003429 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003430 else:
3431 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003432 del self.self
3433
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003434 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003435 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003436 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003437 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3438 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3439 % vars(self))
3440 names = [f.__name__ for f, v in self.flags.items() if v]
3441 s.append('flags=[' + ', '.join(names) + ']')
3442 names = [t.__name__ for t, v in self.traps.items() if v]
3443 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003444 return ', '.join(s) + ')'
3445
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003446 def clear_flags(self):
3447 """Reset all flags to zero"""
3448 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003449 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003450
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003451 def _shallow_copy(self):
3452 """Returns a shallow copy from self."""
Christian Heimes2c181612007-12-17 20:04:13 +00003453 nc = Context(self.prec, self.rounding, self.traps,
3454 self.flags, self.Emin, self.Emax,
3455 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003456 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003457
3458 def copy(self):
3459 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003460 nc = Context(self.prec, self.rounding, self.traps.copy(),
Christian Heimes2c181612007-12-17 20:04:13 +00003461 self.flags.copy(), self.Emin, self.Emax,
3462 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003463 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003464 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003465
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003466 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003467 """Handles an error
3468
3469 If the flag is in _ignored_flags, returns the default response.
3470 Otherwise, it increments the flag, then, if the corresponding
3471 trap_enabler is set, it reaises the exception. Otherwise, it returns
3472 the default value after incrementing the flag.
3473 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003474 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003475 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003476 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003477 return error().handle(self, *args)
3478
3479 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003480 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003481 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003482 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003483
3484 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003485 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003486 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003487
3488 def _ignore_all_flags(self):
3489 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003490 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003491
3492 def _ignore_flags(self, *flags):
3493 """Ignore the flags, if they are raised"""
3494 # Do not mutate-- This way, copies of a context leave the original
3495 # alone.
3496 self._ignored_flags = (self._ignored_flags + list(flags))
3497 return list(flags)
3498
3499 def _regard_flags(self, *flags):
3500 """Stop ignoring the flags, if they are raised"""
3501 if flags and isinstance(flags[0], (tuple,list)):
3502 flags = flags[0]
3503 for flag in flags:
3504 self._ignored_flags.remove(flag)
3505
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003506 def __hash__(self):
3507 """A Context cannot be hashed."""
3508 # We inherit object.__hash__, so we must deny this explicitly
Guido van Rossumd8faa362007-04-27 19:54:29 +00003509 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003510
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003511 def Etiny(self):
3512 """Returns Etiny (= Emin - prec + 1)"""
3513 return int(self.Emin - self.prec + 1)
3514
3515 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003516 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003517 return int(self.Emax - self.prec + 1)
3518
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003519 def _set_rounding(self, type):
3520 """Sets the rounding type.
3521
3522 Sets the rounding type, and returns the current (previous)
3523 rounding type. Often used like:
3524
3525 context = context.copy()
3526 # so you don't change the calling context
3527 # if an error occurs in the middle.
3528 rounding = context._set_rounding(ROUND_UP)
3529 val = self.__sub__(other, context=context)
3530 context._set_rounding(rounding)
3531
3532 This will make it round up for that operation.
3533 """
3534 rounding = self.rounding
3535 self.rounding= type
3536 return rounding
3537
Raymond Hettingerfed52962004-07-14 15:41:57 +00003538 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003539 """Creates a new Decimal instance but using self as context."""
3540 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003541 if d._isnan() and len(d._int) > self.prec - self._clamp:
3542 return self._raise_error(ConversionSyntax,
3543 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003544 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003545
Guido van Rossumd8faa362007-04-27 19:54:29 +00003546 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003547 def abs(self, a):
3548 """Returns the absolute value of the operand.
3549
3550 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003551 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003552 the plus operation on the operand.
3553
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003554 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003555 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003556 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003557 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003558 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003559 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003560 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003561 Decimal("101.5")
3562 """
3563 return a.__abs__(context=self)
3564
3565 def add(self, a, b):
3566 """Return the sum of the two operands.
3567
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003568 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003569 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003570 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003571 Decimal("1.02E+4")
3572 """
3573 return a.__add__(b, context=self)
3574
3575 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003576 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003577
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003578 def canonical(self, a):
3579 """Returns the same Decimal object.
3580
3581 As we do not have different encodings for the same number, the
3582 received object already is in its canonical form.
3583
3584 >>> ExtendedContext.canonical(Decimal('2.50'))
3585 Decimal("2.50")
3586 """
3587 return a.canonical(context=self)
3588
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003589 def compare(self, a, b):
3590 """Compares values numerically.
3591
3592 If the signs of the operands differ, a value representing each operand
3593 ('-1' if the operand is less than zero, '0' if the operand is zero or
3594 negative zero, or '1' if the operand is greater than zero) is used in
3595 place of that operand for the comparison instead of the actual
3596 operand.
3597
3598 The comparison is then effected by subtracting the second operand from
3599 the first and then returning a value according to the result of the
3600 subtraction: '-1' if the result is less than zero, '0' if the result is
3601 zero or negative zero, or '1' if the result is greater than zero.
3602
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003603 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003604 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003605 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003606 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003607 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003608 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003609 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003610 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003611 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003612 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003613 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003614 Decimal("-1")
3615 """
3616 return a.compare(b, context=self)
3617
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003618 def compare_signal(self, a, b):
3619 """Compares the values of the two operands numerically.
3620
3621 It's pretty much like compare(), but all NaNs signal, with signaling
3622 NaNs taking precedence over quiet NaNs.
3623
3624 >>> c = ExtendedContext
3625 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3626 Decimal("-1")
3627 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3628 Decimal("0")
3629 >>> c.flags[InvalidOperation] = 0
3630 >>> print(c.flags[InvalidOperation])
3631 0
3632 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3633 Decimal("NaN")
3634 >>> print(c.flags[InvalidOperation])
3635 1
3636 >>> c.flags[InvalidOperation] = 0
3637 >>> print(c.flags[InvalidOperation])
3638 0
3639 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3640 Decimal("NaN")
3641 >>> print(c.flags[InvalidOperation])
3642 1
3643 """
3644 return a.compare_signal(b, context=self)
3645
3646 def compare_total(self, a, b):
3647 """Compares two operands using their abstract representation.
3648
3649 This is not like the standard compare, which use their numerical
3650 value. Note that a total ordering is defined for all possible abstract
3651 representations.
3652
3653 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3654 Decimal("-1")
3655 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3656 Decimal("-1")
3657 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3658 Decimal("-1")
3659 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3660 Decimal("0")
3661 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3662 Decimal("1")
3663 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3664 Decimal("-1")
3665 """
3666 return a.compare_total(b)
3667
3668 def compare_total_mag(self, a, b):
3669 """Compares two operands using their abstract representation ignoring sign.
3670
3671 Like compare_total, but with operand's sign ignored and assumed to be 0.
3672 """
3673 return a.compare_total_mag(b)
3674
3675 def copy_abs(self, a):
3676 """Returns a copy of the operand with the sign set to 0.
3677
3678 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3679 Decimal("2.1")
3680 >>> ExtendedContext.copy_abs(Decimal('-100'))
3681 Decimal("100")
3682 """
3683 return a.copy_abs()
3684
3685 def copy_decimal(self, a):
3686 """Returns a copy of the decimal objet.
3687
3688 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3689 Decimal("2.1")
3690 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3691 Decimal("-1.00")
3692 """
3693 return Decimal(a)
3694
3695 def copy_negate(self, a):
3696 """Returns a copy of the operand with the sign inverted.
3697
3698 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3699 Decimal("-101.5")
3700 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3701 Decimal("101.5")
3702 """
3703 return a.copy_negate()
3704
3705 def copy_sign(self, a, b):
3706 """Copies the second operand's sign to the first one.
3707
3708 In detail, it returns a copy of the first operand with the sign
3709 equal to the sign of the second operand.
3710
3711 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3712 Decimal("1.50")
3713 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3714 Decimal("1.50")
3715 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3716 Decimal("-1.50")
3717 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3718 Decimal("-1.50")
3719 """
3720 return a.copy_sign(b)
3721
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003722 def divide(self, a, b):
3723 """Decimal division in a specified context.
3724
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003725 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003726 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003727 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003728 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003729 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003730 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003731 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003732 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003733 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003734 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003735 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003736 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003737 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003738 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003739 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003740 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003741 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003742 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003743 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003744 Decimal("1.20E+6")
3745 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003746 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003747
3748 def divide_int(self, a, b):
3749 """Divides two numbers and returns the integer part of the result.
3750
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003751 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003752 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003753 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003754 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003755 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003756 Decimal("3")
3757 """
3758 return a.__floordiv__(b, context=self)
3759
3760 def divmod(self, a, b):
3761 return a.__divmod__(b, context=self)
3762
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003763 def exp(self, a):
3764 """Returns e ** a.
3765
3766 >>> c = ExtendedContext.copy()
3767 >>> c.Emin = -999
3768 >>> c.Emax = 999
3769 >>> c.exp(Decimal('-Infinity'))
3770 Decimal("0")
3771 >>> c.exp(Decimal('-1'))
3772 Decimal("0.367879441")
3773 >>> c.exp(Decimal('0'))
3774 Decimal("1")
3775 >>> c.exp(Decimal('1'))
3776 Decimal("2.71828183")
3777 >>> c.exp(Decimal('0.693147181'))
3778 Decimal("2.00000000")
3779 >>> c.exp(Decimal('+Infinity'))
3780 Decimal("Infinity")
3781 """
3782 return a.exp(context=self)
3783
3784 def fma(self, a, b, c):
3785 """Returns a multiplied by b, plus c.
3786
3787 The first two operands are multiplied together, using multiply,
3788 the third operand is then added to the result of that
3789 multiplication, using add, all with only one final rounding.
3790
3791 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3792 Decimal("22")
3793 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3794 Decimal("-8")
3795 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3796 Decimal("1.38435736E+12")
3797 """
3798 return a.fma(b, c, context=self)
3799
3800 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003801 """Return True if the operand is canonical; otherwise return False.
3802
3803 Currently, the encoding of a Decimal instance is always
3804 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003805
3806 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003807 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003808 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003809 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003810
3811 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003812 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003813
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003814 A Decimal instance is considered finite if it is neither
3815 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003816
3817 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003818 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003819 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003820 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003821 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003822 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003823 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003824 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003825 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003826 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003827 """
3828 return a.is_finite()
3829
3830 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003831 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003832
3833 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003834 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003835 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003836 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003837 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003838 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003839 """
3840 return a.is_infinite()
3841
3842 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003843 """Return True if the operand is a qNaN or sNaN;
3844 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003845
3846 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003847 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003848 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003849 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003850 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003851 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003852 """
3853 return a.is_nan()
3854
3855 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003856 """Return True if the operand is a normal number;
3857 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003858
3859 >>> c = ExtendedContext.copy()
3860 >>> c.Emin = -999
3861 >>> c.Emax = 999
3862 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003863 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003864 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003865 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003866 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003867 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003868 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003869 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003870 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003871 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003872 """
3873 return a.is_normal(context=self)
3874
3875 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003876 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003877
3878 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003879 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003880 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003881 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003882 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003883 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003884 """
3885 return a.is_qnan()
3886
3887 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003888 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003889
3890 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003891 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003892 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003893 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003894 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003895 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003896 """
3897 return a.is_signed()
3898
3899 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003900 """Return True if the operand is a signaling NaN;
3901 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003902
3903 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003904 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003905 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003906 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003907 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003908 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003909 """
3910 return a.is_snan()
3911
3912 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003913 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003914
3915 >>> c = ExtendedContext.copy()
3916 >>> c.Emin = -999
3917 >>> c.Emax = 999
3918 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003919 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003920 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003921 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003922 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003923 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003924 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003925 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003926 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003927 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003928 """
3929 return a.is_subnormal(context=self)
3930
3931 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003932 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003933
3934 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003935 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003936 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003937 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003938 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003939 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003940 """
3941 return a.is_zero()
3942
3943 def ln(self, a):
3944 """Returns the natural (base e) logarithm of the operand.
3945
3946 >>> c = ExtendedContext.copy()
3947 >>> c.Emin = -999
3948 >>> c.Emax = 999
3949 >>> c.ln(Decimal('0'))
3950 Decimal("-Infinity")
3951 >>> c.ln(Decimal('1.000'))
3952 Decimal("0")
3953 >>> c.ln(Decimal('2.71828183'))
3954 Decimal("1.00000000")
3955 >>> c.ln(Decimal('10'))
3956 Decimal("2.30258509")
3957 >>> c.ln(Decimal('+Infinity'))
3958 Decimal("Infinity")
3959 """
3960 return a.ln(context=self)
3961
3962 def log10(self, a):
3963 """Returns the base 10 logarithm of the operand.
3964
3965 >>> c = ExtendedContext.copy()
3966 >>> c.Emin = -999
3967 >>> c.Emax = 999
3968 >>> c.log10(Decimal('0'))
3969 Decimal("-Infinity")
3970 >>> c.log10(Decimal('0.001'))
3971 Decimal("-3")
3972 >>> c.log10(Decimal('1.000'))
3973 Decimal("0")
3974 >>> c.log10(Decimal('2'))
3975 Decimal("0.301029996")
3976 >>> c.log10(Decimal('10'))
3977 Decimal("1")
3978 >>> c.log10(Decimal('70'))
3979 Decimal("1.84509804")
3980 >>> c.log10(Decimal('+Infinity'))
3981 Decimal("Infinity")
3982 """
3983 return a.log10(context=self)
3984
3985 def logb(self, a):
3986 """ Returns the exponent of the magnitude of the operand's MSD.
3987
3988 The result is the integer which is the exponent of the magnitude
3989 of the most significant digit of the operand (as though the
3990 operand were truncated to a single digit while maintaining the
3991 value of that digit and without limiting the resulting exponent).
3992
3993 >>> ExtendedContext.logb(Decimal('250'))
3994 Decimal("2")
3995 >>> ExtendedContext.logb(Decimal('2.50'))
3996 Decimal("0")
3997 >>> ExtendedContext.logb(Decimal('0.03'))
3998 Decimal("-2")
3999 >>> ExtendedContext.logb(Decimal('0'))
4000 Decimal("-Infinity")
4001 """
4002 return a.logb(context=self)
4003
4004 def logical_and(self, a, b):
4005 """Applies the logical operation 'and' between each operand's digits.
4006
4007 The operands must be both logical numbers.
4008
4009 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4010 Decimal("0")
4011 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4012 Decimal("0")
4013 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4014 Decimal("0")
4015 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4016 Decimal("1")
4017 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4018 Decimal("1000")
4019 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4020 Decimal("10")
4021 """
4022 return a.logical_and(b, context=self)
4023
4024 def logical_invert(self, a):
4025 """Invert all the digits in the operand.
4026
4027 The operand must be a logical number.
4028
4029 >>> ExtendedContext.logical_invert(Decimal('0'))
4030 Decimal("111111111")
4031 >>> ExtendedContext.logical_invert(Decimal('1'))
4032 Decimal("111111110")
4033 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4034 Decimal("0")
4035 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4036 Decimal("10101010")
4037 """
4038 return a.logical_invert(context=self)
4039
4040 def logical_or(self, a, b):
4041 """Applies the logical operation 'or' between each operand's digits.
4042
4043 The operands must be both logical numbers.
4044
4045 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4046 Decimal("0")
4047 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4048 Decimal("1")
4049 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4050 Decimal("1")
4051 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4052 Decimal("1")
4053 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4054 Decimal("1110")
4055 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4056 Decimal("1110")
4057 """
4058 return a.logical_or(b, context=self)
4059
4060 def logical_xor(self, a, b):
4061 """Applies the logical operation 'xor' between each operand's digits.
4062
4063 The operands must be both logical numbers.
4064
4065 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4066 Decimal("0")
4067 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4068 Decimal("1")
4069 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4070 Decimal("1")
4071 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4072 Decimal("0")
4073 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4074 Decimal("110")
4075 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4076 Decimal("1101")
4077 """
4078 return a.logical_xor(b, context=self)
4079
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004080 def max(self, a,b):
4081 """max compares two values numerically and returns the maximum.
4082
4083 If either operand is a NaN then the general rules apply.
4084 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004085 operation. If they are numerically equal then the left-hand operand
4086 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004087 infinity) of the two operands is chosen as the result.
4088
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004089 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004090 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004091 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004092 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004093 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004094 Decimal("1")
4095 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4096 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004097 """
4098 return a.max(b, context=self)
4099
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004100 def max_mag(self, a, b):
4101 """Compares the values numerically with their sign ignored."""
4102 return a.max_mag(b, context=self)
4103
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004104 def min(self, a,b):
4105 """min compares two values numerically and returns the minimum.
4106
4107 If either operand is a NaN then the general rules apply.
4108 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004109 operation. If they are numerically equal then the left-hand operand
4110 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004111 infinity) of the two operands is chosen as the result.
4112
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004113 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004114 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004115 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004116 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004117 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004118 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004119 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4120 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004121 """
4122 return a.min(b, context=self)
4123
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004124 def min_mag(self, a, b):
4125 """Compares the values numerically with their sign ignored."""
4126 return a.min_mag(b, context=self)
4127
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004128 def minus(self, a):
4129 """Minus corresponds to unary prefix minus in Python.
4130
4131 The operation is evaluated using the same rules as subtract; the
4132 operation minus(a) is calculated as subtract('0', a) where the '0'
4133 has the same exponent as the operand.
4134
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004135 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004136 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004137 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004138 Decimal("1.3")
4139 """
4140 return a.__neg__(context=self)
4141
4142 def multiply(self, a, b):
4143 """multiply multiplies two operands.
4144
4145 If either operand is a special value then the general rules apply.
4146 Otherwise, the operands are multiplied together ('long multiplication'),
4147 resulting in a number which may be as long as the sum of the lengths
4148 of the two operands.
4149
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004150 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004151 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004152 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004153 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004154 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004155 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004156 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004157 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004158 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004159 Decimal("4.28135971E+11")
4160 """
4161 return a.__mul__(b, context=self)
4162
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004163 def next_minus(self, a):
4164 """Returns the largest representable number smaller than a.
4165
4166 >>> c = ExtendedContext.copy()
4167 >>> c.Emin = -999
4168 >>> c.Emax = 999
4169 >>> ExtendedContext.next_minus(Decimal('1'))
4170 Decimal("0.999999999")
4171 >>> c.next_minus(Decimal('1E-1007'))
4172 Decimal("0E-1007")
4173 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4174 Decimal("-1.00000004")
4175 >>> c.next_minus(Decimal('Infinity'))
4176 Decimal("9.99999999E+999")
4177 """
4178 return a.next_minus(context=self)
4179
4180 def next_plus(self, a):
4181 """Returns the smallest representable number larger than a.
4182
4183 >>> c = ExtendedContext.copy()
4184 >>> c.Emin = -999
4185 >>> c.Emax = 999
4186 >>> ExtendedContext.next_plus(Decimal('1'))
4187 Decimal("1.00000001")
4188 >>> c.next_plus(Decimal('-1E-1007'))
4189 Decimal("-0E-1007")
4190 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4191 Decimal("-1.00000002")
4192 >>> c.next_plus(Decimal('-Infinity'))
4193 Decimal("-9.99999999E+999")
4194 """
4195 return a.next_plus(context=self)
4196
4197 def next_toward(self, a, b):
4198 """Returns the number closest to a, in direction towards b.
4199
4200 The result is the closest representable number from the first
4201 operand (but not the first operand) that is in the direction
4202 towards the second operand, unless the operands have the same
4203 value.
4204
4205 >>> c = ExtendedContext.copy()
4206 >>> c.Emin = -999
4207 >>> c.Emax = 999
4208 >>> c.next_toward(Decimal('1'), Decimal('2'))
4209 Decimal("1.00000001")
4210 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4211 Decimal("-0E-1007")
4212 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4213 Decimal("-1.00000002")
4214 >>> c.next_toward(Decimal('1'), Decimal('0'))
4215 Decimal("0.999999999")
4216 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4217 Decimal("0E-1007")
4218 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4219 Decimal("-1.00000004")
4220 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4221 Decimal("-0.00")
4222 """
4223 return a.next_toward(b, context=self)
4224
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004225 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004226 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004227
4228 Essentially a plus operation with all trailing zeros removed from the
4229 result.
4230
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004231 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004232 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004233 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004234 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004235 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004236 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004237 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004238 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004239 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004240 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004241 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004242 Decimal("0")
4243 """
4244 return a.normalize(context=self)
4245
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004246 def number_class(self, a):
4247 """Returns an indication of the class of the operand.
4248
4249 The class is one of the following strings:
4250 -sNaN
4251 -NaN
4252 -Infinity
4253 -Normal
4254 -Subnormal
4255 -Zero
4256 +Zero
4257 +Subnormal
4258 +Normal
4259 +Infinity
4260
4261 >>> c = Context(ExtendedContext)
4262 >>> c.Emin = -999
4263 >>> c.Emax = 999
4264 >>> c.number_class(Decimal('Infinity'))
4265 '+Infinity'
4266 >>> c.number_class(Decimal('1E-10'))
4267 '+Normal'
4268 >>> c.number_class(Decimal('2.50'))
4269 '+Normal'
4270 >>> c.number_class(Decimal('0.1E-999'))
4271 '+Subnormal'
4272 >>> c.number_class(Decimal('0'))
4273 '+Zero'
4274 >>> c.number_class(Decimal('-0'))
4275 '-Zero'
4276 >>> c.number_class(Decimal('-0.1E-999'))
4277 '-Subnormal'
4278 >>> c.number_class(Decimal('-1E-10'))
4279 '-Normal'
4280 >>> c.number_class(Decimal('-2.50'))
4281 '-Normal'
4282 >>> c.number_class(Decimal('-Infinity'))
4283 '-Infinity'
4284 >>> c.number_class(Decimal('NaN'))
4285 'NaN'
4286 >>> c.number_class(Decimal('-NaN'))
4287 'NaN'
4288 >>> c.number_class(Decimal('sNaN'))
4289 'sNaN'
4290 """
4291 return a.number_class(context=self)
4292
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004293 def plus(self, a):
4294 """Plus corresponds to unary prefix plus in Python.
4295
4296 The operation is evaluated using the same rules as add; the
4297 operation plus(a) is calculated as add('0', a) where the '0'
4298 has the same exponent as the operand.
4299
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004300 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004301 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004302 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004303 Decimal("-1.3")
4304 """
4305 return a.__pos__(context=self)
4306
4307 def power(self, a, b, modulo=None):
4308 """Raises a to the power of b, to modulo if given.
4309
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004310 With two arguments, compute a**b. If a is negative then b
4311 must be integral. The result will be inexact unless b is
4312 integral and the result is finite and can be expressed exactly
4313 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004314
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004315 With three arguments, compute (a**b) % modulo. For the
4316 three argument form, the following restrictions on the
4317 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004318
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004319 - all three arguments must be integral
4320 - b must be nonnegative
4321 - at least one of a or b must be nonzero
4322 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004323
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004324 The result of pow(a, b, modulo) is identical to the result
4325 that would be obtained by computing (a**b) % modulo with
4326 unbounded precision, but is computed more efficiently. It is
4327 always exact.
4328
4329 >>> c = ExtendedContext.copy()
4330 >>> c.Emin = -999
4331 >>> c.Emax = 999
4332 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004333 Decimal("8")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004334 >>> c.power(Decimal('-2'), Decimal('3'))
4335 Decimal("-8")
4336 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004337 Decimal("0.125")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004338 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004339 Decimal("69.7575744")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004340 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4341 Decimal("2.00000000")
4342 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004343 Decimal("0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004344 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004345 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004346 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004347 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004348 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004349 Decimal("-0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004350 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004351 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004352 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004353 Decimal("-Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004354 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004355 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004356 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004357 Decimal("NaN")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004358
4359 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4360 Decimal("11")
4361 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4362 Decimal("-11")
4363 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4364 Decimal("1")
4365 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4366 Decimal("11")
4367 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4368 Decimal("11729830")
4369 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4370 Decimal("-0")
4371 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4372 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004373 """
4374 return a.__pow__(b, modulo, context=self)
4375
4376 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004377 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004378
4379 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004380 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004381 exponent is being increased), multiplied by a positive power of ten (if
4382 the exponent is being decreased), or is unchanged (if the exponent is
4383 already equal to that of the right-hand operand).
4384
4385 Unlike other operations, if the length of the coefficient after the
4386 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004387 operation condition is raised. This guarantees that, unless there is
4388 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004389 equal to that of the right-hand operand.
4390
4391 Also unlike other operations, quantize will never raise Underflow, even
4392 if the result is subnormal and inexact.
4393
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004394 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004395 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004396 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004397 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004398 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004399 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004400 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004401 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004402 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004403 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004404 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004405 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004406 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004407 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004408 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004409 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004410 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004411 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004412 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004413 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004414 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004415 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004416 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004417 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004418 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004419 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004420 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004421 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004422 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004423 Decimal("2E+2")
4424 """
4425 return a.quantize(b, context=self)
4426
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004427 def radix(self):
4428 """Just returns 10, as this is Decimal, :)
4429
4430 >>> ExtendedContext.radix()
4431 Decimal("10")
4432 """
4433 return Decimal(10)
4434
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004435 def remainder(self, a, b):
4436 """Returns the remainder from integer division.
4437
4438 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004439 calculating integer division as described for divide-integer, rounded
4440 to precision digits if necessary. The sign of the result, if
4441 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004442
4443 This operation will fail under the same conditions as integer division
4444 (that is, if integer division on the same two operands would fail, the
4445 remainder cannot be calculated).
4446
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004447 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004448 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004449 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004450 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004451 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004452 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004453 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004454 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004455 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004456 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004457 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004458 Decimal("1.0")
4459 """
4460 return a.__mod__(b, context=self)
4461
4462 def remainder_near(self, a, b):
4463 """Returns to be "a - b * n", where n is the integer nearest the exact
4464 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004465 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004466 sign of a.
4467
4468 This operation will fail under the same conditions as integer division
4469 (that is, if integer division on the same two operands would fail, the
4470 remainder cannot be calculated).
4471
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004472 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004473 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004474 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004475 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004476 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004477 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004478 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004479 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004480 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004481 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004482 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004483 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004484 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004485 Decimal("-0.3")
4486 """
4487 return a.remainder_near(b, context=self)
4488
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004489 def rotate(self, a, b):
4490 """Returns a rotated copy of a, b times.
4491
4492 The coefficient of the result is a rotated copy of the digits in
4493 the coefficient of the first operand. The number of places of
4494 rotation is taken from the absolute value of the second operand,
4495 with the rotation being to the left if the second operand is
4496 positive or to the right otherwise.
4497
4498 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4499 Decimal("400000003")
4500 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4501 Decimal("12")
4502 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4503 Decimal("891234567")
4504 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4505 Decimal("123456789")
4506 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4507 Decimal("345678912")
4508 """
4509 return a.rotate(b, context=self)
4510
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004511 def same_quantum(self, a, b):
4512 """Returns True if the two operands have the same exponent.
4513
4514 The result is never affected by either the sign or the coefficient of
4515 either operand.
4516
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004517 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004518 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004519 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004520 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004521 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004522 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004523 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004524 True
4525 """
4526 return a.same_quantum(b)
4527
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004528 def scaleb (self, a, b):
4529 """Returns the first operand after adding the second value its exp.
4530
4531 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4532 Decimal("0.0750")
4533 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4534 Decimal("7.50")
4535 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4536 Decimal("7.50E+3")
4537 """
4538 return a.scaleb (b, context=self)
4539
4540 def shift(self, a, b):
4541 """Returns a shifted copy of a, b times.
4542
4543 The coefficient of the result is a shifted copy of the digits
4544 in the coefficient of the first operand. The number of places
4545 to shift is taken from the absolute value of the second operand,
4546 with the shift being to the left if the second operand is
4547 positive or to the right otherwise. Digits shifted into the
4548 coefficient are zeros.
4549
4550 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4551 Decimal("400000000")
4552 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4553 Decimal("0")
4554 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4555 Decimal("1234567")
4556 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4557 Decimal("123456789")
4558 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4559 Decimal("345678900")
4560 """
4561 return a.shift(b, context=self)
4562
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004563 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004564 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004565
4566 If the result must be inexact, it is rounded using the round-half-even
4567 algorithm.
4568
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004569 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004570 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004571 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004572 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004573 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004574 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004575 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004576 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004577 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004578 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004579 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004580 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004581 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004582 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004583 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004584 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004585 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004586 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004587 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004588 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004589 """
4590 return a.sqrt(context=self)
4591
4592 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004593 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004594
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004595 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004596 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004597 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004598 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004599 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004600 Decimal("-0.77")
4601 """
4602 return a.__sub__(b, context=self)
4603
4604 def to_eng_string(self, a):
4605 """Converts a number to a string, using scientific notation.
4606
4607 The operation is not affected by the context.
4608 """
4609 return a.to_eng_string(context=self)
4610
4611 def to_sci_string(self, a):
4612 """Converts a number to a string, using scientific notation.
4613
4614 The operation is not affected by the context.
4615 """
4616 return a.__str__(context=self)
4617
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004618 def to_integral_exact(self, a):
4619 """Rounds to an integer.
4620
4621 When the operand has a negative exponent, the result is the same
4622 as using the quantize() operation using the given operand as the
4623 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4624 of the operand as the precision setting; Inexact and Rounded flags
4625 are allowed in this operation. The rounding mode is taken from the
4626 context.
4627
4628 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4629 Decimal("2")
4630 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4631 Decimal("100")
4632 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4633 Decimal("100")
4634 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4635 Decimal("102")
4636 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4637 Decimal("-102")
4638 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4639 Decimal("1.0E+6")
4640 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4641 Decimal("7.89E+77")
4642 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4643 Decimal("-Infinity")
4644 """
4645 return a.to_integral_exact(context=self)
4646
4647 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004648 """Rounds to an integer.
4649
4650 When the operand has a negative exponent, the result is the same
4651 as using the quantize() operation using the given operand as the
4652 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4653 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004654 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004655
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004656 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004657 Decimal("2")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004658 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004659 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004660 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004661 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004662 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004663 Decimal("102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004664 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004665 Decimal("-102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004666 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004667 Decimal("1.0E+6")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004668 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004669 Decimal("7.89E+77")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004670 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004671 Decimal("-Infinity")
4672 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004673 return a.to_integral_value(context=self)
4674
4675 # the method name changed, but we provide also the old one, for compatibility
4676 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004677
4678class _WorkRep(object):
4679 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004680 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004681 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004682 # exp: None, int, or string
4683
4684 def __init__(self, value=None):
4685 if value is None:
4686 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004687 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004688 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004689 elif isinstance(value, Decimal):
4690 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00004691 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004692 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004693 else:
4694 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004695 self.sign = value[0]
4696 self.int = value[1]
4697 self.exp = value[2]
4698
4699 def __repr__(self):
4700 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4701
4702 __str__ = __repr__
4703
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004704
4705
Christian Heimes2c181612007-12-17 20:04:13 +00004706def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004707 """Normalizes op1, op2 to have the same exp and length of coefficient.
4708
4709 Done during addition.
4710 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004711 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004712 tmp = op2
4713 other = op1
4714 else:
4715 tmp = op1
4716 other = op2
4717
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004718 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4719 # Then adding 10**exp to tmp has the same effect (after rounding)
4720 # as adding any positive quantity smaller than 10**exp; similarly
4721 # for subtraction. So if other is smaller than 10**exp we replace
4722 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00004723 tmp_len = len(str(tmp.int))
4724 other_len = len(str(other.int))
4725 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4726 if other_len + other.exp - 1 < exp:
4727 other.int = 1
4728 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004729
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004730 tmp.int *= 10 ** (tmp.exp - other.exp)
4731 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004732 return op1, op2
4733
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004734##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004735
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004736# This function from Tim Peters was taken from here:
4737# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4738# The correction being in the function definition is for speed, and
4739# the whole function is not resolved with math.log because of avoiding
4740# the use of floats.
4741def _nbits(n, correction = {
4742 '0': 4, '1': 3, '2': 2, '3': 2,
4743 '4': 1, '5': 1, '6': 1, '7': 1,
4744 '8': 0, '9': 0, 'a': 0, 'b': 0,
4745 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4746 """Number of bits in binary representation of the positive integer n,
4747 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004748 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004749 if n < 0:
4750 raise ValueError("The argument to _nbits should be nonnegative.")
4751 hex_n = "%x" % n
4752 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004753
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004754def _sqrt_nearest(n, a):
4755 """Closest integer to the square root of the positive integer n. a is
4756 an initial approximation to the square root. Any positive integer
4757 will do for a, but the closer a is to the square root of n the
4758 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004759
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004760 """
4761 if n <= 0 or a <= 0:
4762 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4763
4764 b=0
4765 while a != b:
4766 b, a = a, a--n//a>>1
4767 return a
4768
4769def _rshift_nearest(x, shift):
4770 """Given an integer x and a nonnegative integer shift, return closest
4771 integer to x / 2**shift; use round-to-even in case of a tie.
4772
4773 """
4774 b, q = 1 << shift, x >> shift
4775 return q + (2*(x & (b-1)) + (q&1) > b)
4776
4777def _div_nearest(a, b):
4778 """Closest integer to a/b, a and b positive integers; rounds to even
4779 in the case of a tie.
4780
4781 """
4782 q, r = divmod(a, b)
4783 return q + (2*r + (q&1) > b)
4784
4785def _ilog(x, M, L = 8):
4786 """Integer approximation to M*log(x/M), with absolute error boundable
4787 in terms only of x/M.
4788
4789 Given positive integers x and M, return an integer approximation to
4790 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4791 between the approximation and the exact result is at most 22. For
4792 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4793 both cases these are upper bounds on the error; it will usually be
4794 much smaller."""
4795
4796 # The basic algorithm is the following: let log1p be the function
4797 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4798 # the reduction
4799 #
4800 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4801 #
4802 # repeatedly until the argument to log1p is small (< 2**-L in
4803 # absolute value). For small y we can use the Taylor series
4804 # expansion
4805 #
4806 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4807 #
4808 # truncating at T such that y**T is small enough. The whole
4809 # computation is carried out in a form of fixed-point arithmetic,
4810 # with a real number z being represented by an integer
4811 # approximation to z*M. To avoid loss of precision, the y below
4812 # is actually an integer approximation to 2**R*y*M, where R is the
4813 # number of reductions performed so far.
4814
4815 y = x-M
4816 # argument reduction; R = number of reductions performed
4817 R = 0
4818 while (R <= L and abs(y) << L-R >= M or
4819 R > L and abs(y) >> R-L >= M):
4820 y = _div_nearest((M*y) << 1,
4821 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4822 R += 1
4823
4824 # Taylor series with T terms
4825 T = -int(-10*len(str(M))//(3*L))
4826 yshift = _rshift_nearest(y, R)
4827 w = _div_nearest(M, T)
4828 for k in range(T-1, 0, -1):
4829 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4830
4831 return _div_nearest(w*y, M)
4832
4833def _dlog10(c, e, p):
4834 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4835 approximation to 10**p * log10(c*10**e), with an absolute error of
4836 at most 1. Assumes that c*10**e is not exactly 1."""
4837
4838 # increase precision by 2; compensate for this by dividing
4839 # final result by 100
4840 p += 2
4841
4842 # write c*10**e as d*10**f with either:
4843 # f >= 0 and 1 <= d <= 10, or
4844 # f <= 0 and 0.1 <= d <= 1.
4845 # Thus for c*10**e close to 1, f = 0
4846 l = len(str(c))
4847 f = e+l - (e+l >= 1)
4848
4849 if p > 0:
4850 M = 10**p
4851 k = e+p-f
4852 if k >= 0:
4853 c *= 10**k
4854 else:
4855 c = _div_nearest(c, 10**-k)
4856
4857 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004858 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004859 log_d = _div_nearest(log_d*M, log_10)
4860 log_tenpower = f*M # exact
4861 else:
4862 log_d = 0 # error < 2.31
4863 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4864
4865 return _div_nearest(log_tenpower+log_d, 100)
4866
4867def _dlog(c, e, p):
4868 """Given integers c, e and p with c > 0, compute an integer
4869 approximation to 10**p * log(c*10**e), with an absolute error of
4870 at most 1. Assumes that c*10**e is not exactly 1."""
4871
4872 # Increase precision by 2. The precision increase is compensated
4873 # for at the end with a division by 100.
4874 p += 2
4875
4876 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4877 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4878 # as 10**p * log(d) + 10**p*f * log(10).
4879 l = len(str(c))
4880 f = e+l - (e+l >= 1)
4881
4882 # compute approximation to 10**p*log(d), with error < 27
4883 if p > 0:
4884 k = e+p-f
4885 if k >= 0:
4886 c *= 10**k
4887 else:
4888 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4889
4890 # _ilog magnifies existing error in c by a factor of at most 10
4891 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4892 else:
4893 # p <= 0: just approximate the whole thing by 0; error < 2.31
4894 log_d = 0
4895
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004896 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004897 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004898 extra = len(str(abs(f)))-1
4899 if p + extra >= 0:
4900 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4901 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4902 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004903 else:
4904 f_log_ten = 0
4905 else:
4906 f_log_ten = 0
4907
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004908 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004909 return _div_nearest(f_log_ten + log_d, 100)
4910
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004911class _Log10Memoize(object):
4912 """Class to compute, store, and allow retrieval of, digits of the
4913 constant log(10) = 2.302585.... This constant is needed by
4914 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4915 def __init__(self):
4916 self.digits = "23025850929940456840179914546843642076011014886"
4917
4918 def getdigits(self, p):
4919 """Given an integer p >= 0, return floor(10**p)*log(10).
4920
4921 For example, self.getdigits(3) returns 2302.
4922 """
4923 # digits are stored as a string, for quick conversion to
4924 # integer in the case that we've already computed enough
4925 # digits; the stored digits should always be correct
4926 # (truncated, not rounded to nearest).
4927 if p < 0:
4928 raise ValueError("p should be nonnegative")
4929
4930 if p >= len(self.digits):
4931 # compute p+3, p+6, p+9, ... digits; continue until at
4932 # least one of the extra digits is nonzero
4933 extra = 3
4934 while True:
4935 # compute p+extra digits, correct to within 1ulp
4936 M = 10**(p+extra+2)
4937 digits = str(_div_nearest(_ilog(10*M, M), 100))
4938 if digits[-extra:] != '0'*extra:
4939 break
4940 extra += 3
4941 # keep all reliable digits so far; remove trailing zeros
4942 # and next nonzero digit
4943 self.digits = digits.rstrip('0')[:-1]
4944 return int(self.digits[:p+1])
4945
4946_log10_digits = _Log10Memoize().getdigits
4947
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004948def _iexp(x, M, L=8):
4949 """Given integers x and M, M > 0, such that x/M is small in absolute
4950 value, compute an integer approximation to M*exp(x/M). For 0 <=
4951 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4952 is usually much smaller)."""
4953
4954 # Algorithm: to compute exp(z) for a real number z, first divide z
4955 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4956 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4957 # series
4958 #
4959 # expm1(x) = x + x**2/2! + x**3/3! + ...
4960 #
4961 # Now use the identity
4962 #
4963 # expm1(2x) = expm1(x)*(expm1(x)+2)
4964 #
4965 # R times to compute the sequence expm1(z/2**R),
4966 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
4967
4968 # Find R such that x/2**R/M <= 2**-L
4969 R = _nbits((x<<L)//M)
4970
4971 # Taylor series. (2**L)**T > M
4972 T = -int(-10*len(str(M))//(3*L))
4973 y = _div_nearest(x, T)
4974 Mshift = M<<R
4975 for i in range(T-1, 0, -1):
4976 y = _div_nearest(x*(Mshift + y), Mshift * i)
4977
4978 # Expansion
4979 for k in range(R-1, -1, -1):
4980 Mshift = M<<(k+2)
4981 y = _div_nearest(y*(y+Mshift), Mshift)
4982
4983 return M+y
4984
4985def _dexp(c, e, p):
4986 """Compute an approximation to exp(c*10**e), with p decimal places of
4987 precision.
4988
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004989 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004990
4991 10**(p-1) <= d <= 10**p, and
4992 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
4993
4994 In other words, d*10**f is an approximation to exp(c*10**e) with p
4995 digits of precision, and with an error in d of at most 1. This is
4996 almost, but not quite, the same as the error being < 1ulp: when d
4997 = 10**(p-1) the error could be up to 10 ulp."""
4998
4999 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5000 p += 2
5001
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005002 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005003 extra = max(0, e + len(str(c)) - 1)
5004 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005005
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005006 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005007 # rounding down
5008 shift = e+q
5009 if shift >= 0:
5010 cshift = c*10**shift
5011 else:
5012 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005013 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005014
5015 # reduce remainder back to original precision
5016 rem = _div_nearest(rem, 10**extra)
5017
5018 # error in result of _iexp < 120; error after division < 0.62
5019 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5020
5021def _dpower(xc, xe, yc, ye, p):
5022 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5023 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5024
5025 10**(p-1) <= c <= 10**p, and
5026 (c-1)*10**e < x**y < (c+1)*10**e
5027
5028 in other words, c*10**e is an approximation to x**y with p digits
5029 of precision, and with an error in c of at most 1. (This is
5030 almost, but not quite, the same as the error being < 1ulp: when c
5031 == 10**(p-1) we can only guarantee error < 10ulp.)
5032
5033 We assume that: x is positive and not equal to 1, and y is nonzero.
5034 """
5035
5036 # Find b such that 10**(b-1) <= |y| <= 10**b
5037 b = len(str(abs(yc))) + ye
5038
5039 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5040 lxc = _dlog(xc, xe, p+b+1)
5041
5042 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5043 shift = ye-b
5044 if shift >= 0:
5045 pc = lxc*yc*10**shift
5046 else:
5047 pc = _div_nearest(lxc*yc, 10**-shift)
5048
5049 if pc == 0:
5050 # we prefer a result that isn't exactly 1; this makes it
5051 # easier to compute a correctly rounded result in __pow__
5052 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5053 coeff, exp = 10**(p-1)+1, 1-p
5054 else:
5055 coeff, exp = 10**p-1, -p
5056 else:
5057 coeff, exp = _dexp(pc, -(p+1), p+1)
5058 coeff = _div_nearest(coeff, 10)
5059 exp += 1
5060
5061 return coeff, exp
5062
5063def _log10_lb(c, correction = {
5064 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5065 '6': 23, '7': 16, '8': 10, '9': 5}):
5066 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5067 if c <= 0:
5068 raise ValueError("The argument to _log10_lb should be nonnegative.")
5069 str_c = str(c)
5070 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005071
Guido van Rossumd8faa362007-04-27 19:54:29 +00005072##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005073
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005074def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005075 """Convert other to Decimal.
5076
5077 Verifies that it's ok to use in an implicit construction.
5078 """
5079 if isinstance(other, Decimal):
5080 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005081 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005082 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005083 if raiseit:
5084 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005085 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005086
Guido van Rossumd8faa362007-04-27 19:54:29 +00005087##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005088
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005089# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005090# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005091
5092DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005093 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005094 traps=[DivisionByZero, Overflow, InvalidOperation],
5095 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005096 Emax=999999999,
5097 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005098 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005099)
5100
5101# Pre-made alternate contexts offered by the specification
5102# Don't change these; the user should be able to select these
5103# contexts and be able to reproduce results from other implementations
5104# of the spec.
5105
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005106BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005107 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005108 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5109 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005110)
5111
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005112ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005113 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005114 traps=[],
5115 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005116)
5117
5118
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005119##### crud for parsing strings #############################################
5120import re
5121
5122# Regular expression used for parsing numeric strings. Additional
5123# comments:
5124#
5125# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5126# whitespace. But note that the specification disallows whitespace in
5127# a numeric string.
5128#
5129# 2. For finite numbers (not infinities and NaNs) the body of the
5130# number between the optional sign and the optional exponent must have
5131# at least one decimal digit, possibly after the decimal point. The
5132# lookahead expression '(?=\d|\.\d)' checks this.
5133#
5134# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5135# other meaning for \d than the numbers [0-9].
5136
5137import re
5138_parser = re.compile(r""" # A numeric string consists of:
5139# \s*
5140 (?P<sign>[-+])? # an optional sign, followed by either...
5141 (
5142 (?=\d|\.\d) # ...a number (with at least one digit)
5143 (?P<int>\d*) # consisting of a (possibly empty) integer part
5144 (\.(?P<frac>\d*))? # followed by an optional fractional part
5145 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5146 |
5147 Inf(inity)? # ...an infinity, or...
5148 |
5149 (?P<signal>s)? # ...an (optionally signaling)
5150 NaN # NaN
5151 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5152 )
5153# \s*
5154 $
5155""", re.VERBOSE | re.IGNORECASE).match
5156
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005157_all_zeros = re.compile('0*$').match
5158_exact_half = re.compile('50*$').match
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005159del re
5160
5161
Guido van Rossumd8faa362007-04-27 19:54:29 +00005162##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005163
Guido van Rossumd8faa362007-04-27 19:54:29 +00005164# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005165Inf = Decimal('Inf')
5166negInf = Decimal('-Inf')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005167NaN = Decimal('NaN')
5168Dec_0 = Decimal(0)
5169Dec_p1 = Decimal(1)
5170Dec_n1 = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005171
Guido van Rossumd8faa362007-04-27 19:54:29 +00005172# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005173Infsign = (Inf, negInf)
5174
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005175
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005176
5177if __name__ == '__main__':
5178 import doctest, sys
5179 doctest.testmod(sys.modules[__name__])