blob: 54e8cb479b090240faf19b09b0f8a7462c74da86 [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
812 # Non-integer decimals are normalized and hashed as strings
Thomas Wouters477c8d52006-05-27 19:21:47 +0000813 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000814 if self._is_special:
815 if self._isnan():
816 raise TypeError('Cannot hash a NaN value.')
817 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000818 if not self:
819 return 0
820 if self._isinteger():
821 op = _WorkRep(self.to_integral_value())
822 # to make computation feasible for Decimals with large
823 # exponent, we use the fact that hash(n) == hash(m) for
824 # any two nonzero integers n and m such that (i) n and m
825 # have the same sign, and (ii) n is congruent to m modulo
826 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
827 # hash((-1)**s*c*pow(10, e, 2**64-1).
828 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000829 return hash(str(self.normalize()))
830
831 def as_tuple(self):
832 """Represents the number as a triple tuple.
833
834 To show the internals exactly as they are.
835 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000836 return (self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000837
838 def __repr__(self):
839 """Represents the number as an instance of Decimal."""
840 # Invariant: eval(repr(d)) == d
841 return 'Decimal("%s")' % str(self)
842
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000843 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000844 """Return string representation of the number in scientific notation.
845
846 Captures all of the information in the underlying representation.
847 """
848
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000849 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000850 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000851 if self._exp == 'F':
852 return sign + 'Infinity'
853 elif self._exp == 'n':
854 return sign + 'NaN' + self._int
855 else: # self._exp == 'N'
856 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000857
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000858 # number of digits of self._int to left of decimal point
859 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000860
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000861 # dotplace is number of digits of self._int to the left of the
862 # decimal point in the mantissa of the output string (that is,
863 # after adjusting the exponent)
864 if self._exp <= 0 and leftdigits > -6:
865 # no exponent required
866 dotplace = leftdigits
867 elif not eng:
868 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000869 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000870 elif self._int == '0':
871 # engineering notation, zero
872 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000873 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000874 # engineering notation, nonzero
875 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000876
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000877 if dotplace <= 0:
878 intpart = '0'
879 fracpart = '.' + '0'*(-dotplace) + self._int
880 elif dotplace >= len(self._int):
881 intpart = self._int+'0'*(dotplace-len(self._int))
882 fracpart = ''
883 else:
884 intpart = self._int[:dotplace]
885 fracpart = '.' + self._int[dotplace:]
886 if leftdigits == dotplace:
887 exp = ''
888 else:
889 if context is None:
890 context = getcontext()
891 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
892
893 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000894
895 def to_eng_string(self, context=None):
896 """Convert to engineering-type string.
897
898 Engineering notation has an exponent which is a multiple of 3, so there
899 are up to 3 digits left of the decimal place.
900
901 Same rules for when in exponential and when as a value as in __str__.
902 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000903 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000904
905 def __neg__(self, context=None):
906 """Returns a copy with the sign switched.
907
908 Rounds, if it has reason.
909 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000910 if self._is_special:
911 ans = self._check_nans(context=context)
912 if ans:
913 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000914
915 if not self:
916 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000917 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000918 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000919 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000920
921 if context is None:
922 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +0000923 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000924
925 def __pos__(self, context=None):
926 """Returns a copy, unless it is a sNaN.
927
928 Rounds the number (if more then precision digits)
929 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000930 if self._is_special:
931 ans = self._check_nans(context=context)
932 if ans:
933 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000934
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000935 if not self:
936 # + (-0) = 0
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000937 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000938 else:
939 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000940
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000941 if context is None:
942 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +0000943 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000944
Christian Heimes2c181612007-12-17 20:04:13 +0000945 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000946 """Returns the absolute value of self.
947
Christian Heimes2c181612007-12-17 20:04:13 +0000948 If the keyword argument 'round' is false, do not round. The
949 expression self.__abs__(round=False) is equivalent to
950 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000951 """
Christian Heimes2c181612007-12-17 20:04:13 +0000952 if not round:
953 return self.copy_abs()
954
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000955 if self._is_special:
956 ans = self._check_nans(context=context)
957 if ans:
958 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000959
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000960 if self._sign:
961 ans = self.__neg__(context=context)
962 else:
963 ans = self.__pos__(context=context)
964
965 return ans
966
967 def __add__(self, other, context=None):
968 """Returns self + other.
969
970 -INF + INF (or the reverse) cause InvalidOperation errors.
971 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000972 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000973 if other is NotImplemented:
974 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000975
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000976 if context is None:
977 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000978
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000979 if self._is_special or other._is_special:
980 ans = self._check_nans(other, context)
981 if ans:
982 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000983
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000984 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000985 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000986 if self._sign != other._sign and other._isinfinity():
987 return context._raise_error(InvalidOperation, '-INF + INF')
988 return Decimal(self)
989 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000990 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000991
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000992 exp = min(self._exp, other._exp)
993 negativezero = 0
994 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000995 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000996 negativezero = 1
997
998 if not self and not other:
999 sign = min(self._sign, other._sign)
1000 if negativezero:
1001 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001002 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001003 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001004 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001005 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001006 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001007 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001008 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009 return ans
1010 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001011 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001012 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001013 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001014 return ans
1015
1016 op1 = _WorkRep(self)
1017 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001018 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001019
1020 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001021 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001022 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001023 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001024 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001025 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001026 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001027 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001028 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001029 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001030 if op1.sign == 1:
1031 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001032 op1.sign, op2.sign = op2.sign, op1.sign
1033 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001034 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001035 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001036 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001037 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001038 op1.sign, op2.sign = (0, 0)
1039 else:
1040 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001041 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001042
Raymond Hettinger17931de2004-10-27 06:21:46 +00001043 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001044 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001045 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001046 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001047
1048 result.exp = op1.exp
1049 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001050 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001051 return ans
1052
1053 __radd__ = __add__
1054
1055 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001056 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001057 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001058 if other is NotImplemented:
1059 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001060
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001061 if self._is_special or other._is_special:
1062 ans = self._check_nans(other, context=context)
1063 if ans:
1064 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001065
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001066 # self - other is computed as self + other.copy_negate()
1067 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001068
1069 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001070 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001071 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001072 if other is NotImplemented:
1073 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001074
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001075 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001076
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001077 def __mul__(self, other, context=None):
1078 """Return self * other.
1079
1080 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1081 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001082 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001083 if other is NotImplemented:
1084 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001085
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001086 if context is None:
1087 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001088
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001089 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001090
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001091 if self._is_special or other._is_special:
1092 ans = self._check_nans(other, context)
1093 if ans:
1094 return ans
1095
1096 if self._isinfinity():
1097 if not other:
1098 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1099 return Infsign[resultsign]
1100
1101 if other._isinfinity():
1102 if not self:
1103 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1104 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001105
1106 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001107
1108 # Special case for multiplying by zero
1109 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001110 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001111 # Fixing in case the exponent is out of bounds
1112 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001113 return ans
1114
1115 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001116 if self._int == '1':
1117 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001118 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001119 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001120 if other._int == '1':
1121 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001122 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001123 return ans
1124
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001125 op1 = _WorkRep(self)
1126 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001127
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001128 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001129 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001130
1131 return ans
1132 __rmul__ = __mul__
1133
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001134 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001135 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001136 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001137 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001138 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001139
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001140 if context is None:
1141 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001142
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001143 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001144
1145 if self._is_special or other._is_special:
1146 ans = self._check_nans(other, context)
1147 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001148 return ans
1149
1150 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001151 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001152
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001153 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001154 return Infsign[sign]
1155
1156 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001157 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001158 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001159
1160 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001161 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001162 if not self:
1163 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001164 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001165
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001166 if not self:
1167 exp = self._exp - other._exp
1168 coeff = 0
1169 else:
1170 # OK, so neither = 0, INF or NaN
1171 shift = len(other._int) - len(self._int) + context.prec + 1
1172 exp = self._exp - other._exp - shift
1173 op1 = _WorkRep(self)
1174 op2 = _WorkRep(other)
1175 if shift >= 0:
1176 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1177 else:
1178 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1179 if remainder:
1180 # result is not exact; adjust to ensure correct rounding
1181 if coeff % 5 == 0:
1182 coeff += 1
1183 else:
1184 # result is exact; get as close to ideal exponent as possible
1185 ideal_exp = self._exp - other._exp
1186 while exp < ideal_exp and coeff % 10 == 0:
1187 coeff //= 10
1188 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001189
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001190 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001191 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001192
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001193 def _divide(self, other, context):
1194 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001195
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001196 Assumes that neither self nor other is a NaN, that self is not
1197 infinite and that other is nonzero.
1198 """
1199 sign = self._sign ^ other._sign
1200 if other._isinfinity():
1201 ideal_exp = self._exp
1202 else:
1203 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001204
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001205 expdiff = self.adjusted() - other.adjusted()
1206 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001207 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001208 self._rescale(ideal_exp, context.rounding))
1209 if expdiff <= context.prec:
1210 op1 = _WorkRep(self)
1211 op2 = _WorkRep(other)
1212 if op1.exp >= op2.exp:
1213 op1.int *= 10**(op1.exp - op2.exp)
1214 else:
1215 op2.int *= 10**(op2.exp - op1.exp)
1216 q, r = divmod(op1.int, op2.int)
1217 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001218 return (_dec_from_triple(sign, str(q), 0),
1219 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001220
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001221 # Here the quotient is too large to be representable
1222 ans = context._raise_error(DivisionImpossible,
1223 'quotient too large in //, % or divmod')
1224 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001225
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001226 def __rtruediv__(self, other, context=None):
1227 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001228 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001229 if other is NotImplemented:
1230 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001231 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001232
1233 def __divmod__(self, other, context=None):
1234 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001235 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001236 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001237 other = _convert_other(other)
1238 if other is NotImplemented:
1239 return other
1240
1241 if context is None:
1242 context = getcontext()
1243
1244 ans = self._check_nans(other, context)
1245 if ans:
1246 return (ans, ans)
1247
1248 sign = self._sign ^ other._sign
1249 if self._isinfinity():
1250 if other._isinfinity():
1251 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1252 return ans, ans
1253 else:
1254 return (Infsign[sign],
1255 context._raise_error(InvalidOperation, 'INF % x'))
1256
1257 if not other:
1258 if not self:
1259 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1260 return ans, ans
1261 else:
1262 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1263 context._raise_error(InvalidOperation, 'x % 0'))
1264
1265 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001266 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001267 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001268
1269 def __rdivmod__(self, other, context=None):
1270 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001271 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001272 if other is NotImplemented:
1273 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001274 return other.__divmod__(self, context=context)
1275
1276 def __mod__(self, other, context=None):
1277 """
1278 self % other
1279 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001280 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001281 if other is NotImplemented:
1282 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001283
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001284 if context is None:
1285 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001286
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001287 ans = self._check_nans(other, context)
1288 if ans:
1289 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001290
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001291 if self._isinfinity():
1292 return context._raise_error(InvalidOperation, 'INF % x')
1293 elif not other:
1294 if self:
1295 return context._raise_error(InvalidOperation, 'x % 0')
1296 else:
1297 return context._raise_error(DivisionUndefined, '0 % 0')
1298
1299 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001300 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001301 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001302
1303 def __rmod__(self, other, context=None):
1304 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001305 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001306 if other is NotImplemented:
1307 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001308 return other.__mod__(self, context=context)
1309
1310 def remainder_near(self, other, context=None):
1311 """
1312 Remainder nearest to 0- abs(remainder-near) <= other/2
1313 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001314 if context is None:
1315 context = getcontext()
1316
1317 other = _convert_other(other, raiseit=True)
1318
1319 ans = self._check_nans(other, context)
1320 if ans:
1321 return ans
1322
1323 # self == +/-infinity -> InvalidOperation
1324 if self._isinfinity():
1325 return context._raise_error(InvalidOperation,
1326 'remainder_near(infinity, x)')
1327
1328 # other == 0 -> either InvalidOperation or DivisionUndefined
1329 if not other:
1330 if self:
1331 return context._raise_error(InvalidOperation,
1332 'remainder_near(x, 0)')
1333 else:
1334 return context._raise_error(DivisionUndefined,
1335 'remainder_near(0, 0)')
1336
1337 # other = +/-infinity -> remainder = self
1338 if other._isinfinity():
1339 ans = Decimal(self)
1340 return ans._fix(context)
1341
1342 # self = 0 -> remainder = self, with ideal exponent
1343 ideal_exponent = min(self._exp, other._exp)
1344 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001345 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001346 return ans._fix(context)
1347
1348 # catch most cases of large or small quotient
1349 expdiff = self.adjusted() - other.adjusted()
1350 if expdiff >= context.prec + 1:
1351 # expdiff >= prec+1 => abs(self/other) > 10**prec
1352 return context._raise_error(DivisionImpossible)
1353 if expdiff <= -2:
1354 # expdiff <= -2 => abs(self/other) < 0.1
1355 ans = self._rescale(ideal_exponent, context.rounding)
1356 return ans._fix(context)
1357
1358 # adjust both arguments to have the same exponent, then divide
1359 op1 = _WorkRep(self)
1360 op2 = _WorkRep(other)
1361 if op1.exp >= op2.exp:
1362 op1.int *= 10**(op1.exp - op2.exp)
1363 else:
1364 op2.int *= 10**(op2.exp - op1.exp)
1365 q, r = divmod(op1.int, op2.int)
1366 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1367 # 10**ideal_exponent. Apply correction to ensure that
1368 # abs(remainder) <= abs(other)/2
1369 if 2*r + (q&1) > op2.int:
1370 r -= op2.int
1371 q += 1
1372
1373 if q >= 10**context.prec:
1374 return context._raise_error(DivisionImpossible)
1375
1376 # result has same sign as self unless r is negative
1377 sign = self._sign
1378 if r < 0:
1379 sign = 1-sign
1380 r = -r
1381
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001382 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001383 return ans._fix(context)
1384
1385 def __floordiv__(self, other, context=None):
1386 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001387 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001388 if other is NotImplemented:
1389 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001390
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001391 if context is None:
1392 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001393
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001394 ans = self._check_nans(other, context)
1395 if ans:
1396 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001397
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001398 if self._isinfinity():
1399 if other._isinfinity():
1400 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001401 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001402 return Infsign[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001403
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001404 if not other:
1405 if self:
1406 return context._raise_error(DivisionByZero, 'x // 0',
1407 self._sign ^ other._sign)
1408 else:
1409 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001410
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001411 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001412
1413 def __rfloordiv__(self, other, context=None):
1414 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001415 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001416 if other is NotImplemented:
1417 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001418 return other.__floordiv__(self, context=context)
1419
1420 def __float__(self):
1421 """Float representation."""
1422 return float(str(self))
1423
1424 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001425 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001426 if self._is_special:
1427 if self._isnan():
1428 context = getcontext()
1429 return context._raise_error(InvalidContext)
1430 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001431 raise OverflowError("Cannot convert infinity to int")
1432 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001433 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001434 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001435 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001436 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001437
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001438 def _fix_nan(self, context):
1439 """Decapitate the payload of a NaN to fit the context"""
1440 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001441
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001442 # maximum length of payload is precision if _clamp=0,
1443 # precision-1 if _clamp=1.
1444 max_payload_len = context.prec - context._clamp
1445 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001446 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1447 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001448 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001449
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001450 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001451 """Round if it is necessary to keep self within prec precision.
1452
1453 Rounds and fixes the exponent. Does not raise on a sNaN.
1454
1455 Arguments:
1456 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001457 context - context used.
1458 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001459
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001460 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001461 if self._isnan():
1462 # decapitate payload if necessary
1463 return self._fix_nan(context)
1464 else:
1465 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001466 return Decimal(self)
1467
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001468 # if self is zero then exponent should be between Etiny and
1469 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1470 Etiny = context.Etiny()
1471 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001472 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001473 exp_max = [context.Emax, Etop][context._clamp]
1474 new_exp = min(max(self._exp, Etiny), exp_max)
1475 if new_exp != self._exp:
1476 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001477 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001478 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001479 return Decimal(self)
1480
1481 # exp_min is the smallest allowable exponent of the result,
1482 # equal to max(self.adjusted()-context.prec+1, Etiny)
1483 exp_min = len(self._int) + self._exp - context.prec
1484 if exp_min > Etop:
1485 # overflow: exp_min > Etop iff self.adjusted() > Emax
1486 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001487 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001488 return context._raise_error(Overflow, 'above Emax', self._sign)
1489 self_is_subnormal = exp_min < Etiny
1490 if self_is_subnormal:
1491 context._raise_error(Subnormal)
1492 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001493
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001494 # round if self has too many digits
1495 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001496 context._raise_error(Rounded)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001497 digits = len(self._int) + self._exp - exp_min
1498 if digits < 0:
1499 self = _dec_from_triple(self._sign, '1', exp_min-1)
1500 digits = 0
1501 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1502 changed = this_function(digits)
1503 coeff = self._int[:digits] or '0'
1504 if changed == 1:
1505 coeff = str(int(coeff)+1)
1506 ans = _dec_from_triple(self._sign, coeff, exp_min)
1507
1508 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001509 context._raise_error(Inexact)
1510 if self_is_subnormal:
1511 context._raise_error(Underflow)
1512 if not ans:
1513 # raise Clamped on underflow to 0
1514 context._raise_error(Clamped)
1515 elif len(ans._int) == context.prec+1:
1516 # we get here only if rescaling rounds the
1517 # cofficient up to exactly 10**context.prec
1518 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001519 ans = _dec_from_triple(ans._sign,
1520 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001521 else:
1522 # Inexact and Rounded have already been raised
1523 ans = context._raise_error(Overflow, 'above Emax',
1524 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001525 return ans
1526
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001527 # fold down if _clamp == 1 and self has too few digits
1528 if context._clamp == 1 and self._exp > Etop:
1529 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001530 self_padded = self._int + '0'*(self._exp - Etop)
1531 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001532
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001533 # here self was representable to begin with; return unchanged
1534 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001535
1536 _pick_rounding_function = {}
1537
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001538 # for each of the rounding functions below:
1539 # self is a finite, nonzero Decimal
1540 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001541 #
1542 # each function returns either -1, 0, or 1, as follows:
1543 # 1 indicates that self should be rounded up (away from zero)
1544 # 0 indicates that self should be truncated, and that all the
1545 # digits to be truncated are zeros (so the value is unchanged)
1546 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001547
1548 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001549 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001550 if _all_zeros(self._int, prec):
1551 return 0
1552 else:
1553 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001554
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001555 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001556 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001557 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001558
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001559 def _round_half_up(self, prec):
1560 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001561 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001562 return 1
1563 elif _all_zeros(self._int, prec):
1564 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001565 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001566 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001567
1568 def _round_half_down(self, prec):
1569 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001570 if _exact_half(self._int, prec):
1571 return -1
1572 else:
1573 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001574
1575 def _round_half_even(self, prec):
1576 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001577 if _exact_half(self._int, prec) and \
1578 (prec == 0 or self._int[prec-1] in '02468'):
1579 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001580 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001581 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001582
1583 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001584 """Rounds up (not away from 0 if negative.)"""
1585 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001586 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001587 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001588 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001589
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001590 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001591 """Rounds down (not towards 0 if negative)"""
1592 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001593 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001594 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001595 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001596
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001597 def _round_05up(self, prec):
1598 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001599 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001600 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001601 else:
1602 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001603
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001604 def fma(self, other, third, context=None):
1605 """Fused multiply-add.
1606
1607 Returns self*other+third with no rounding of the intermediate
1608 product self*other.
1609
1610 self and other are multiplied together, with no rounding of
1611 the result. The third operand is then added to the result,
1612 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001613 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001614
1615 other = _convert_other(other, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001616
1617 # compute product; raise InvalidOperation if either operand is
1618 # a signaling NaN or if the product is zero times infinity.
1619 if self._is_special or other._is_special:
1620 if context is None:
1621 context = getcontext()
1622 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001623 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001624 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001625 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001626 if self._exp == 'n':
1627 product = self
1628 elif other._exp == 'n':
1629 product = other
1630 elif self._exp == 'F':
1631 if not other:
1632 return context._raise_error(InvalidOperation,
1633 'INF * 0 in fma')
1634 product = Infsign[self._sign ^ other._sign]
1635 elif other._exp == 'F':
1636 if not self:
1637 return context._raise_error(InvalidOperation,
1638 '0 * INF in fma')
1639 product = Infsign[self._sign ^ other._sign]
1640 else:
1641 product = _dec_from_triple(self._sign ^ other._sign,
1642 str(int(self._int) * int(other._int)),
1643 self._exp + other._exp)
1644
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001645 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001646 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001647
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001648 def _power_modulo(self, other, modulo, context=None):
1649 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001650
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001651 # if can't convert other and modulo to Decimal, raise
1652 # TypeError; there's no point returning NotImplemented (no
1653 # equivalent of __rpow__ for three argument pow)
1654 other = _convert_other(other, raiseit=True)
1655 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001656
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001657 if context is None:
1658 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001659
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001660 # deal with NaNs: if there are any sNaNs then first one wins,
1661 # (i.e. behaviour for NaNs is identical to that of fma)
1662 self_is_nan = self._isnan()
1663 other_is_nan = other._isnan()
1664 modulo_is_nan = modulo._isnan()
1665 if self_is_nan or other_is_nan or modulo_is_nan:
1666 if self_is_nan == 2:
1667 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001668 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001669 if other_is_nan == 2:
1670 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001671 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001672 if modulo_is_nan == 2:
1673 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001674 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001675 if self_is_nan:
1676 return self._fix_nan(context)
1677 if other_is_nan:
1678 return other._fix_nan(context)
1679 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001680
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001681 # check inputs: we apply same restrictions as Python's pow()
1682 if not (self._isinteger() and
1683 other._isinteger() and
1684 modulo._isinteger()):
1685 return context._raise_error(InvalidOperation,
1686 'pow() 3rd argument not allowed '
1687 'unless all arguments are integers')
1688 if other < 0:
1689 return context._raise_error(InvalidOperation,
1690 'pow() 2nd argument cannot be '
1691 'negative when 3rd argument specified')
1692 if not modulo:
1693 return context._raise_error(InvalidOperation,
1694 'pow() 3rd argument cannot be 0')
1695
1696 # additional restriction for decimal: the modulus must be less
1697 # than 10**prec in absolute value
1698 if modulo.adjusted() >= context.prec:
1699 return context._raise_error(InvalidOperation,
1700 'insufficient precision: pow() 3rd '
1701 'argument must not have more than '
1702 'precision digits')
1703
1704 # define 0**0 == NaN, for consistency with two-argument pow
1705 # (even though it hurts!)
1706 if not other and not self:
1707 return context._raise_error(InvalidOperation,
1708 'at least one of pow() 1st argument '
1709 'and 2nd argument must be nonzero ;'
1710 '0**0 is not defined')
1711
1712 # compute sign of result
1713 if other._iseven():
1714 sign = 0
1715 else:
1716 sign = self._sign
1717
1718 # convert modulo to a Python integer, and self and other to
1719 # Decimal integers (i.e. force their exponents to be >= 0)
1720 modulo = abs(int(modulo))
1721 base = _WorkRep(self.to_integral_value())
1722 exponent = _WorkRep(other.to_integral_value())
1723
1724 # compute result using integer pow()
1725 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1726 for i in range(exponent.exp):
1727 base = pow(base, 10, modulo)
1728 base = pow(base, exponent.int, modulo)
1729
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001730 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001731
1732 def _power_exact(self, other, p):
1733 """Attempt to compute self**other exactly.
1734
1735 Given Decimals self and other and an integer p, attempt to
1736 compute an exact result for the power self**other, with p
1737 digits of precision. Return None if self**other is not
1738 exactly representable in p digits.
1739
1740 Assumes that elimination of special cases has already been
1741 performed: self and other must both be nonspecial; self must
1742 be positive and not numerically equal to 1; other must be
1743 nonzero. For efficiency, other._exp should not be too large,
1744 so that 10**abs(other._exp) is a feasible calculation."""
1745
1746 # In the comments below, we write x for the value of self and
1747 # y for the value of other. Write x = xc*10**xe and y =
1748 # yc*10**ye.
1749
1750 # The main purpose of this method is to identify the *failure*
1751 # of x**y to be exactly representable with as little effort as
1752 # possible. So we look for cheap and easy tests that
1753 # eliminate the possibility of x**y being exact. Only if all
1754 # these tests are passed do we go on to actually compute x**y.
1755
1756 # Here's the main idea. First normalize both x and y. We
1757 # express y as a rational m/n, with m and n relatively prime
1758 # and n>0. Then for x**y to be exactly representable (at
1759 # *any* precision), xc must be the nth power of a positive
1760 # integer and xe must be divisible by n. If m is negative
1761 # then additionally xc must be a power of either 2 or 5, hence
1762 # a power of 2**n or 5**n.
1763 #
1764 # There's a limit to how small |y| can be: if y=m/n as above
1765 # then:
1766 #
1767 # (1) if xc != 1 then for the result to be representable we
1768 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1769 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1770 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1771 # representable.
1772 #
1773 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1774 # |y| < 1/|xe| then the result is not representable.
1775 #
1776 # Note that since x is not equal to 1, at least one of (1) and
1777 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1778 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1779 #
1780 # There's also a limit to how large y can be, at least if it's
1781 # positive: the normalized result will have coefficient xc**y,
1782 # so if it's representable then xc**y < 10**p, and y <
1783 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1784 # not exactly representable.
1785
1786 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1787 # so |y| < 1/xe and the result is not representable.
1788 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1789 # < 1/nbits(xc).
1790
1791 x = _WorkRep(self)
1792 xc, xe = x.int, x.exp
1793 while xc % 10 == 0:
1794 xc //= 10
1795 xe += 1
1796
1797 y = _WorkRep(other)
1798 yc, ye = y.int, y.exp
1799 while yc % 10 == 0:
1800 yc //= 10
1801 ye += 1
1802
1803 # case where xc == 1: result is 10**(xe*y), with xe*y
1804 # required to be an integer
1805 if xc == 1:
1806 if ye >= 0:
1807 exponent = xe*yc*10**ye
1808 else:
1809 exponent, remainder = divmod(xe*yc, 10**-ye)
1810 if remainder:
1811 return None
1812 if y.sign == 1:
1813 exponent = -exponent
1814 # if other is a nonnegative integer, use ideal exponent
1815 if other._isinteger() and other._sign == 0:
1816 ideal_exponent = self._exp*int(other)
1817 zeros = min(exponent-ideal_exponent, p-1)
1818 else:
1819 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001820 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001821
1822 # case where y is negative: xc must be either a power
1823 # of 2 or a power of 5.
1824 if y.sign == 1:
1825 last_digit = xc % 10
1826 if last_digit in (2,4,6,8):
1827 # quick test for power of 2
1828 if xc & -xc != xc:
1829 return None
1830 # now xc is a power of 2; e is its exponent
1831 e = _nbits(xc)-1
1832 # find e*y and xe*y; both must be integers
1833 if ye >= 0:
1834 y_as_int = yc*10**ye
1835 e = e*y_as_int
1836 xe = xe*y_as_int
1837 else:
1838 ten_pow = 10**-ye
1839 e, remainder = divmod(e*yc, ten_pow)
1840 if remainder:
1841 return None
1842 xe, remainder = divmod(xe*yc, ten_pow)
1843 if remainder:
1844 return None
1845
1846 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1847 return None
1848 xc = 5**e
1849
1850 elif last_digit == 5:
1851 # e >= log_5(xc) if xc is a power of 5; we have
1852 # equality all the way up to xc=5**2658
1853 e = _nbits(xc)*28//65
1854 xc, remainder = divmod(5**e, xc)
1855 if remainder:
1856 return None
1857 while xc % 5 == 0:
1858 xc //= 5
1859 e -= 1
1860 if ye >= 0:
1861 y_as_integer = yc*10**ye
1862 e = e*y_as_integer
1863 xe = xe*y_as_integer
1864 else:
1865 ten_pow = 10**-ye
1866 e, remainder = divmod(e*yc, ten_pow)
1867 if remainder:
1868 return None
1869 xe, remainder = divmod(xe*yc, ten_pow)
1870 if remainder:
1871 return None
1872 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1873 return None
1874 xc = 2**e
1875 else:
1876 return None
1877
1878 if xc >= 10**p:
1879 return None
1880 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001881 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001882
1883 # now y is positive; find m and n such that y = m/n
1884 if ye >= 0:
1885 m, n = yc*10**ye, 1
1886 else:
1887 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1888 return None
1889 xc_bits = _nbits(xc)
1890 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1891 return None
1892 m, n = yc, 10**(-ye)
1893 while m % 2 == n % 2 == 0:
1894 m //= 2
1895 n //= 2
1896 while m % 5 == n % 5 == 0:
1897 m //= 5
1898 n //= 5
1899
1900 # compute nth root of xc*10**xe
1901 if n > 1:
1902 # if 1 < xc < 2**n then xc isn't an nth power
1903 if xc != 1 and xc_bits <= n:
1904 return None
1905
1906 xe, rem = divmod(xe, n)
1907 if rem != 0:
1908 return None
1909
1910 # compute nth root of xc using Newton's method
1911 a = 1 << -(-_nbits(xc)//n) # initial estimate
1912 while True:
1913 q, r = divmod(xc, a**(n-1))
1914 if a <= q:
1915 break
1916 else:
1917 a = (a*(n-1) + q)//n
1918 if not (a == q and r == 0):
1919 return None
1920 xc = a
1921
1922 # now xc*10**xe is the nth root of the original xc*10**xe
1923 # compute mth power of xc*10**xe
1924
1925 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1926 # 10**p and the result is not representable.
1927 if xc > 1 and m > p*100//_log10_lb(xc):
1928 return None
1929 xc = xc**m
1930 xe *= m
1931 if xc > 10**p:
1932 return None
1933
1934 # by this point the result *is* exactly representable
1935 # adjust the exponent to get as close as possible to the ideal
1936 # exponent, if necessary
1937 str_xc = str(xc)
1938 if other._isinteger() and other._sign == 0:
1939 ideal_exponent = self._exp*int(other)
1940 zeros = min(xe-ideal_exponent, p-len(str_xc))
1941 else:
1942 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001943 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001944
1945 def __pow__(self, other, modulo=None, context=None):
1946 """Return self ** other [ % modulo].
1947
1948 With two arguments, compute self**other.
1949
1950 With three arguments, compute (self**other) % modulo. For the
1951 three argument form, the following restrictions on the
1952 arguments hold:
1953
1954 - all three arguments must be integral
1955 - other must be nonnegative
1956 - either self or other (or both) must be nonzero
1957 - modulo must be nonzero and must have at most p digits,
1958 where p is the context precision.
1959
1960 If any of these restrictions is violated the InvalidOperation
1961 flag is raised.
1962
1963 The result of pow(self, other, modulo) is identical to the
1964 result that would be obtained by computing (self**other) %
1965 modulo with unbounded precision, but is computed more
1966 efficiently. It is always exact.
1967 """
1968
1969 if modulo is not None:
1970 return self._power_modulo(other, modulo, context)
1971
1972 other = _convert_other(other)
1973 if other is NotImplemented:
1974 return other
1975
1976 if context is None:
1977 context = getcontext()
1978
1979 # either argument is a NaN => result is NaN
1980 ans = self._check_nans(other, context)
1981 if ans:
1982 return ans
1983
1984 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1985 if not other:
1986 if not self:
1987 return context._raise_error(InvalidOperation, '0 ** 0')
1988 else:
1989 return Dec_p1
1990
1991 # result has sign 1 iff self._sign is 1 and other is an odd integer
1992 result_sign = 0
1993 if self._sign == 1:
1994 if other._isinteger():
1995 if not other._iseven():
1996 result_sign = 1
1997 else:
1998 # -ve**noninteger = NaN
1999 # (-0)**noninteger = 0**noninteger
2000 if self:
2001 return context._raise_error(InvalidOperation,
2002 'x ** y with x negative and y not an integer')
2003 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002004 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002005
2006 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2007 if not self:
2008 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002009 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002010 else:
2011 return Infsign[result_sign]
2012
2013 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002014 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002015 if other._sign == 0:
2016 return Infsign[result_sign]
2017 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002018 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002019
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002020 # 1**other = 1, but the choice of exponent and the flags
2021 # depend on the exponent of self, and on whether other is a
2022 # positive integer, a negative integer, or neither
2023 if self == Dec_p1:
2024 if other._isinteger():
2025 # exp = max(self._exp*max(int(other), 0),
2026 # 1-context.prec) but evaluating int(other) directly
2027 # is dangerous until we know other is small (other
2028 # could be 1e999999999)
2029 if other._sign == 1:
2030 multiplier = 0
2031 elif other > context.prec:
2032 multiplier = context.prec
2033 else:
2034 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002035
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002036 exp = self._exp * multiplier
2037 if exp < 1-context.prec:
2038 exp = 1-context.prec
2039 context._raise_error(Rounded)
2040 else:
2041 context._raise_error(Inexact)
2042 context._raise_error(Rounded)
2043 exp = 1-context.prec
2044
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002045 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002046
2047 # compute adjusted exponent of self
2048 self_adj = self.adjusted()
2049
2050 # self ** infinity is infinity if self > 1, 0 if self < 1
2051 # self ** -infinity is infinity if self < 1, 0 if self > 1
2052 if other._isinfinity():
2053 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002054 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002055 else:
2056 return Infsign[result_sign]
2057
2058 # from here on, the result always goes through the call
2059 # to _fix at the end of this function.
2060 ans = None
2061
2062 # crude test to catch cases of extreme overflow/underflow. If
2063 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2064 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2065 # self**other >= 10**(Emax+1), so overflow occurs. The test
2066 # for underflow is similar.
2067 bound = self._log10_exp_bound() + other.adjusted()
2068 if (self_adj >= 0) == (other._sign == 0):
2069 # self > 1 and other +ve, or self < 1 and other -ve
2070 # possibility of overflow
2071 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002072 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002073 else:
2074 # self > 1 and other -ve, or self < 1 and other +ve
2075 # possibility of underflow to 0
2076 Etiny = context.Etiny()
2077 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002078 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002079
2080 # try for an exact result with precision +1
2081 if ans is None:
2082 ans = self._power_exact(other, context.prec + 1)
2083 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002084 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002085
2086 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2087 if ans is None:
2088 p = context.prec
2089 x = _WorkRep(self)
2090 xc, xe = x.int, x.exp
2091 y = _WorkRep(other)
2092 yc, ye = y.int, y.exp
2093 if y.sign == 1:
2094 yc = -yc
2095
2096 # compute correctly rounded result: start with precision +3,
2097 # then increase precision until result is unambiguously roundable
2098 extra = 3
2099 while True:
2100 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2101 if coeff % (5*10**(len(str(coeff))-p-1)):
2102 break
2103 extra += 3
2104
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002105 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002106
2107 # the specification says that for non-integer other we need to
2108 # raise Inexact, even when the result is actually exact. In
2109 # the same way, we need to raise Underflow here if the result
2110 # is subnormal. (The call to _fix will take care of raising
2111 # Rounded and Subnormal, as usual.)
2112 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002113 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002114 # pad with zeros up to length context.prec+1 if necessary
2115 if len(ans._int) <= context.prec:
2116 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002117 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2118 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002119 if ans.adjusted() < context.Emin:
2120 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002121
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002122 # unlike exp, ln and log10, the power function respects the
2123 # rounding mode; no need to use ROUND_HALF_EVEN here
2124 ans = ans._fix(context)
2125 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002126
2127 def __rpow__(self, other, context=None):
2128 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002129 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002130 if other is NotImplemented:
2131 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002132 return other.__pow__(self, context=context)
2133
2134 def normalize(self, context=None):
2135 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002136
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002137 if context is None:
2138 context = getcontext()
2139
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002140 if self._is_special:
2141 ans = self._check_nans(context=context)
2142 if ans:
2143 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002144
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002145 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002146 if dup._isinfinity():
2147 return dup
2148
2149 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002150 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002151 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002152 end = len(dup._int)
2153 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002154 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002155 exp += 1
2156 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002157 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002158
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002159 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002160 """Quantize self so its exponent is the same as that of exp.
2161
2162 Similar to self._rescale(exp._exp) but with error checking.
2163 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002164 exp = _convert_other(exp, raiseit=True)
2165
2166 if context is None:
2167 context = getcontext()
2168 if rounding is None:
2169 rounding = context.rounding
2170
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002171 if self._is_special or exp._is_special:
2172 ans = self._check_nans(exp, context)
2173 if ans:
2174 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002175
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002176 if exp._isinfinity() or self._isinfinity():
2177 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002178 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002179 return context._raise_error(InvalidOperation,
2180 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002181
2182 # if we're not watching exponents, do a simple rescale
2183 if not watchexp:
2184 ans = self._rescale(exp._exp, rounding)
2185 # raise Inexact and Rounded where appropriate
2186 if ans._exp > self._exp:
2187 context._raise_error(Rounded)
2188 if ans != self:
2189 context._raise_error(Inexact)
2190 return ans
2191
2192 # exp._exp should be between Etiny and Emax
2193 if not (context.Etiny() <= exp._exp <= context.Emax):
2194 return context._raise_error(InvalidOperation,
2195 'target exponent out of bounds in quantize')
2196
2197 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002198 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002199 return ans._fix(context)
2200
2201 self_adjusted = self.adjusted()
2202 if self_adjusted > context.Emax:
2203 return context._raise_error(InvalidOperation,
2204 'exponent of quantize result too large for current context')
2205 if self_adjusted - exp._exp + 1 > context.prec:
2206 return context._raise_error(InvalidOperation,
2207 'quantize result has too many digits for current context')
2208
2209 ans = self._rescale(exp._exp, rounding)
2210 if ans.adjusted() > context.Emax:
2211 return context._raise_error(InvalidOperation,
2212 'exponent of quantize result too large for current context')
2213 if len(ans._int) > context.prec:
2214 return context._raise_error(InvalidOperation,
2215 'quantize result has too many digits for current context')
2216
2217 # raise appropriate flags
2218 if ans._exp > self._exp:
2219 context._raise_error(Rounded)
2220 if ans != self:
2221 context._raise_error(Inexact)
2222 if ans and ans.adjusted() < context.Emin:
2223 context._raise_error(Subnormal)
2224
2225 # call to fix takes care of any necessary folddown
2226 ans = ans._fix(context)
2227 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002228
2229 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002230 """Return True if self and other have the same exponent; otherwise
2231 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002232
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002233 If either operand is a special value, the following rules are used:
2234 * return True if both operands are infinities
2235 * return True if both operands are NaNs
2236 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002237 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002238 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002239 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002240 return (self.is_nan() and other.is_nan() or
2241 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002242 return self._exp == other._exp
2243
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002244 def _rescale(self, exp, rounding):
2245 """Rescale self so that the exponent is exp, either by padding with zeros
2246 or by truncating digits, using the given rounding mode.
2247
2248 Specials are returned without change. This operation is
2249 quiet: it raises no flags, and uses no information from the
2250 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002251
2252 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002253 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002254 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002255 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002256 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002257 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002258 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002259
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002260 if self._exp >= exp:
2261 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002262 return _dec_from_triple(self._sign,
2263 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002264
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002265 # too many digits; round and lose data. If self.adjusted() <
2266 # exp-1, replace self by 10**(exp-1) before rounding
2267 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002268 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002269 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002270 digits = 0
2271 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002272 changed = this_function(digits)
2273 coeff = self._int[:digits] or '0'
2274 if changed == 1:
2275 coeff = str(int(coeff)+1)
2276 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002277
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002278 def to_integral_exact(self, rounding=None, context=None):
2279 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002280
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002281 If no rounding mode is specified, take the rounding mode from
2282 the context. This method raises the Rounded and Inexact flags
2283 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002284
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002285 See also: to_integral_value, which does exactly the same as
2286 this method except that it doesn't raise Inexact or Rounded.
2287 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002288 if self._is_special:
2289 ans = self._check_nans(context=context)
2290 if ans:
2291 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002292 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002293 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002294 return Decimal(self)
2295 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002296 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002297 if context is None:
2298 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002299 if rounding is None:
2300 rounding = context.rounding
2301 context._raise_error(Rounded)
2302 ans = self._rescale(0, rounding)
2303 if ans != self:
2304 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002305 return ans
2306
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002307 def to_integral_value(self, rounding=None, context=None):
2308 """Rounds to the nearest integer, without raising inexact, rounded."""
2309 if context is None:
2310 context = getcontext()
2311 if rounding is None:
2312 rounding = context.rounding
2313 if self._is_special:
2314 ans = self._check_nans(context=context)
2315 if ans:
2316 return ans
2317 return Decimal(self)
2318 if self._exp >= 0:
2319 return Decimal(self)
2320 else:
2321 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002322
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002323 # the method name changed, but we provide also the old one, for compatibility
2324 to_integral = to_integral_value
2325
2326 def sqrt(self, context=None):
2327 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002328 if self._is_special:
2329 ans = self._check_nans(context=context)
2330 if ans:
2331 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002332
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002333 if self._isinfinity() and self._sign == 0:
2334 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002335
2336 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002337 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002338 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002339 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002340
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002341 if context is None:
2342 context = getcontext()
2343
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002344 if self._sign == 1:
2345 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2346
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002347 # At this point self represents a positive number. Let p be
2348 # the desired precision and express self in the form c*100**e
2349 # with c a positive real number and e an integer, c and e
2350 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2351 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2352 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2353 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2354 # the closest integer to sqrt(c) with the even integer chosen
2355 # in the case of a tie.
2356 #
2357 # To ensure correct rounding in all cases, we use the
2358 # following trick: we compute the square root to an extra
2359 # place (precision p+1 instead of precision p), rounding down.
2360 # Then, if the result is inexact and its last digit is 0 or 5,
2361 # we increase the last digit to 1 or 6 respectively; if it's
2362 # exact we leave the last digit alone. Now the final round to
2363 # p places (or fewer in the case of underflow) will round
2364 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002365
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002366 # use an extra digit of precision
2367 prec = context.prec+1
2368
2369 # write argument in the form c*100**e where e = self._exp//2
2370 # is the 'ideal' exponent, to be used if the square root is
2371 # exactly representable. l is the number of 'digits' of c in
2372 # base 100, so that 100**(l-1) <= c < 100**l.
2373 op = _WorkRep(self)
2374 e = op.exp >> 1
2375 if op.exp & 1:
2376 c = op.int * 10
2377 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002378 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002379 c = op.int
2380 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002381
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002382 # rescale so that c has exactly prec base 100 'digits'
2383 shift = prec-l
2384 if shift >= 0:
2385 c *= 100**shift
2386 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002387 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002388 c, remainder = divmod(c, 100**-shift)
2389 exact = not remainder
2390 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002391
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002392 # find n = floor(sqrt(c)) using Newton's method
2393 n = 10**prec
2394 while True:
2395 q = c//n
2396 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002397 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002398 else:
2399 n = n + q >> 1
2400 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002401
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002402 if exact:
2403 # result is exact; rescale to use ideal exponent e
2404 if shift >= 0:
2405 # assert n % 10**shift == 0
2406 n //= 10**shift
2407 else:
2408 n *= 10**-shift
2409 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002410 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002411 # result is not exact; fix last digit as described above
2412 if n % 5 == 0:
2413 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002414
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002415 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002416
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002417 # round, and fit to current context
2418 context = context._shallow_copy()
2419 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002420 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002421 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002422
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002423 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002424
2425 def max(self, other, context=None):
2426 """Returns the larger value.
2427
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002428 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002429 NaN (and signals if one is sNaN). Also rounds.
2430 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002431 other = _convert_other(other, raiseit=True)
2432
2433 if context is None:
2434 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002435
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002436 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002437 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002438 # number is always returned
2439 sn = self._isnan()
2440 on = other._isnan()
2441 if sn or on:
2442 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002443 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002444 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002445 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002446 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002447
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002448 c = self.__cmp__(other)
2449 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002450 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002451 # then an ordering is applied:
2452 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002453 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002454 # positive sign and min returns the operand with the negative sign
2455 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002456 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002457 # the result. This is exactly the ordering used in compare_total.
2458 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002459
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002460 if c == -1:
2461 ans = other
2462 else:
2463 ans = self
2464
Christian Heimes2c181612007-12-17 20:04:13 +00002465 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002466
2467 def min(self, other, context=None):
2468 """Returns the smaller value.
2469
Guido van Rossumd8faa362007-04-27 19:54:29 +00002470 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002471 NaN (and signals if one is sNaN). Also rounds.
2472 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002473 other = _convert_other(other, raiseit=True)
2474
2475 if context is None:
2476 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002477
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002478 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002479 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002480 # number is always returned
2481 sn = self._isnan()
2482 on = other._isnan()
2483 if sn or on:
2484 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002485 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002486 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002487 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002488 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002489
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002490 c = self.__cmp__(other)
2491 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002492 c = self.compare_total(other)
2493
2494 if c == -1:
2495 ans = self
2496 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002497 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002498
Christian Heimes2c181612007-12-17 20:04:13 +00002499 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002500
2501 def _isinteger(self):
2502 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002503 if self._is_special:
2504 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002505 if self._exp >= 0:
2506 return True
2507 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002508 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002509
2510 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002511 """Returns True if self is even. Assumes self is an integer."""
2512 if not self or self._exp > 0:
2513 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002514 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002515
2516 def adjusted(self):
2517 """Return the adjusted exponent of self"""
2518 try:
2519 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002520 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002521 except TypeError:
2522 return 0
2523
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002524 def canonical(self, context=None):
2525 """Returns the same Decimal object.
2526
2527 As we do not have different encodings for the same number, the
2528 received object already is in its canonical form.
2529 """
2530 return self
2531
2532 def compare_signal(self, other, context=None):
2533 """Compares self to the other operand numerically.
2534
2535 It's pretty much like compare(), but all NaNs signal, with signaling
2536 NaNs taking precedence over quiet NaNs.
2537 """
2538 if context is None:
2539 context = getcontext()
2540
2541 self_is_nan = self._isnan()
2542 other_is_nan = other._isnan()
2543 if self_is_nan == 2:
2544 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002545 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002546 if other_is_nan == 2:
2547 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002548 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002549 if self_is_nan:
2550 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002551 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002552 if other_is_nan:
2553 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002554 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002555 return self.compare(other, context=context)
2556
2557 def compare_total(self, other):
2558 """Compares self to other using the abstract representations.
2559
2560 This is not like the standard compare, which use their numerical
2561 value. Note that a total ordering is defined for all possible abstract
2562 representations.
2563 """
2564 # if one is negative and the other is positive, it's easy
2565 if self._sign and not other._sign:
2566 return Dec_n1
2567 if not self._sign and other._sign:
2568 return Dec_p1
2569 sign = self._sign
2570
2571 # let's handle both NaN types
2572 self_nan = self._isnan()
2573 other_nan = other._isnan()
2574 if self_nan or other_nan:
2575 if self_nan == other_nan:
2576 if self._int < other._int:
2577 if sign:
2578 return Dec_p1
2579 else:
2580 return Dec_n1
2581 if self._int > other._int:
2582 if sign:
2583 return Dec_n1
2584 else:
2585 return Dec_p1
2586 return Dec_0
2587
2588 if sign:
2589 if self_nan == 1:
2590 return Dec_n1
2591 if other_nan == 1:
2592 return Dec_p1
2593 if self_nan == 2:
2594 return Dec_n1
2595 if other_nan == 2:
2596 return Dec_p1
2597 else:
2598 if self_nan == 1:
2599 return Dec_p1
2600 if other_nan == 1:
2601 return Dec_n1
2602 if self_nan == 2:
2603 return Dec_p1
2604 if other_nan == 2:
2605 return Dec_n1
2606
2607 if self < other:
2608 return Dec_n1
2609 if self > other:
2610 return Dec_p1
2611
2612 if self._exp < other._exp:
2613 if sign:
2614 return Dec_p1
2615 else:
2616 return Dec_n1
2617 if self._exp > other._exp:
2618 if sign:
2619 return Dec_n1
2620 else:
2621 return Dec_p1
2622 return Dec_0
2623
2624
2625 def compare_total_mag(self, other):
2626 """Compares self to other using abstract repr., ignoring sign.
2627
2628 Like compare_total, but with operand's sign ignored and assumed to be 0.
2629 """
2630 s = self.copy_abs()
2631 o = other.copy_abs()
2632 return s.compare_total(o)
2633
2634 def copy_abs(self):
2635 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002636 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002637
2638 def copy_negate(self):
2639 """Returns a copy with the sign inverted."""
2640 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002641 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002642 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002643 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002644
2645 def copy_sign(self, other):
2646 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002647 return _dec_from_triple(other._sign, self._int,
2648 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002649
2650 def exp(self, context=None):
2651 """Returns e ** self."""
2652
2653 if context is None:
2654 context = getcontext()
2655
2656 # exp(NaN) = NaN
2657 ans = self._check_nans(context=context)
2658 if ans:
2659 return ans
2660
2661 # exp(-Infinity) = 0
2662 if self._isinfinity() == -1:
2663 return Dec_0
2664
2665 # exp(0) = 1
2666 if not self:
2667 return Dec_p1
2668
2669 # exp(Infinity) = Infinity
2670 if self._isinfinity() == 1:
2671 return Decimal(self)
2672
2673 # the result is now guaranteed to be inexact (the true
2674 # mathematical result is transcendental). There's no need to
2675 # raise Rounded and Inexact here---they'll always be raised as
2676 # a result of the call to _fix.
2677 p = context.prec
2678 adj = self.adjusted()
2679
2680 # we only need to do any computation for quite a small range
2681 # of adjusted exponents---for example, -29 <= adj <= 10 for
2682 # the default context. For smaller exponent the result is
2683 # indistinguishable from 1 at the given precision, while for
2684 # larger exponent the result either overflows or underflows.
2685 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2686 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002687 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002688 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2689 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002690 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002691 elif self._sign == 0 and adj < -p:
2692 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002693 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002694 elif self._sign == 1 and adj < -p-1:
2695 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002696 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002697 # general case
2698 else:
2699 op = _WorkRep(self)
2700 c, e = op.int, op.exp
2701 if op.sign == 1:
2702 c = -c
2703
2704 # compute correctly rounded result: increase precision by
2705 # 3 digits at a time until we get an unambiguously
2706 # roundable result
2707 extra = 3
2708 while True:
2709 coeff, exp = _dexp(c, e, p+extra)
2710 if coeff % (5*10**(len(str(coeff))-p-1)):
2711 break
2712 extra += 3
2713
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002714 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002715
2716 # at this stage, ans should round correctly with *any*
2717 # rounding mode, not just with ROUND_HALF_EVEN
2718 context = context._shallow_copy()
2719 rounding = context._set_rounding(ROUND_HALF_EVEN)
2720 ans = ans._fix(context)
2721 context.rounding = rounding
2722
2723 return ans
2724
2725 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002726 """Return True if self is canonical; otherwise return False.
2727
2728 Currently, the encoding of a Decimal instance is always
2729 canonical, so this method returns True for any Decimal.
2730 """
2731 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002732
2733 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002734 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002735
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002736 A Decimal instance is considered finite if it is neither
2737 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002738 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002739 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002740
2741 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002742 """Return True if self is infinite; otherwise return False."""
2743 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002744
2745 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002746 """Return True if self is a qNaN or sNaN; otherwise return False."""
2747 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002748
2749 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002750 """Return True if self is a normal number; otherwise return False."""
2751 if self._is_special or not self:
2752 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002753 if context is None:
2754 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002755 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002756
2757 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002758 """Return True if self is a quiet NaN; otherwise return False."""
2759 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002760
2761 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002762 """Return True if self is negative; otherwise return False."""
2763 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002764
2765 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002766 """Return True if self is a signaling NaN; otherwise return False."""
2767 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002768
2769 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002770 """Return True if self is subnormal; otherwise return False."""
2771 if self._is_special or not self:
2772 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002773 if context is None:
2774 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002775 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002776
2777 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002778 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002779 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002780
2781 def _ln_exp_bound(self):
2782 """Compute a lower bound for the adjusted exponent of self.ln().
2783 In other words, compute r such that self.ln() >= 10**r. Assumes
2784 that self is finite and positive and that self != 1.
2785 """
2786
2787 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2788 adj = self._exp + len(self._int) - 1
2789 if adj >= 1:
2790 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2791 return len(str(adj*23//10)) - 1
2792 if adj <= -2:
2793 # argument <= 0.1
2794 return len(str((-1-adj)*23//10)) - 1
2795 op = _WorkRep(self)
2796 c, e = op.int, op.exp
2797 if adj == 0:
2798 # 1 < self < 10
2799 num = str(c-10**-e)
2800 den = str(c)
2801 return len(num) - len(den) - (num < den)
2802 # adj == -1, 0.1 <= self < 1
2803 return e + len(str(10**-e - c)) - 1
2804
2805
2806 def ln(self, context=None):
2807 """Returns the natural (base e) logarithm of self."""
2808
2809 if context is None:
2810 context = getcontext()
2811
2812 # ln(NaN) = NaN
2813 ans = self._check_nans(context=context)
2814 if ans:
2815 return ans
2816
2817 # ln(0.0) == -Infinity
2818 if not self:
2819 return negInf
2820
2821 # ln(Infinity) = Infinity
2822 if self._isinfinity() == 1:
2823 return Inf
2824
2825 # ln(1.0) == 0.0
2826 if self == Dec_p1:
2827 return Dec_0
2828
2829 # ln(negative) raises InvalidOperation
2830 if self._sign == 1:
2831 return context._raise_error(InvalidOperation,
2832 'ln of a negative value')
2833
2834 # result is irrational, so necessarily inexact
2835 op = _WorkRep(self)
2836 c, e = op.int, op.exp
2837 p = context.prec
2838
2839 # correctly rounded result: repeatedly increase precision by 3
2840 # until we get an unambiguously roundable result
2841 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2842 while True:
2843 coeff = _dlog(c, e, places)
2844 # assert len(str(abs(coeff)))-p >= 1
2845 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2846 break
2847 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002848 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002849
2850 context = context._shallow_copy()
2851 rounding = context._set_rounding(ROUND_HALF_EVEN)
2852 ans = ans._fix(context)
2853 context.rounding = rounding
2854 return ans
2855
2856 def _log10_exp_bound(self):
2857 """Compute a lower bound for the adjusted exponent of self.log10().
2858 In other words, find r such that self.log10() >= 10**r.
2859 Assumes that self is finite and positive and that self != 1.
2860 """
2861
2862 # For x >= 10 or x < 0.1 we only need a bound on the integer
2863 # part of log10(self), and this comes directly from the
2864 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2865 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2866 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2867
2868 adj = self._exp + len(self._int) - 1
2869 if adj >= 1:
2870 # self >= 10
2871 return len(str(adj))-1
2872 if adj <= -2:
2873 # self < 0.1
2874 return len(str(-1-adj))-1
2875 op = _WorkRep(self)
2876 c, e = op.int, op.exp
2877 if adj == 0:
2878 # 1 < self < 10
2879 num = str(c-10**-e)
2880 den = str(231*c)
2881 return len(num) - len(den) - (num < den) + 2
2882 # adj == -1, 0.1 <= self < 1
2883 num = str(10**-e-c)
2884 return len(num) + e - (num < "231") - 1
2885
2886 def log10(self, context=None):
2887 """Returns the base 10 logarithm of self."""
2888
2889 if context is None:
2890 context = getcontext()
2891
2892 # log10(NaN) = NaN
2893 ans = self._check_nans(context=context)
2894 if ans:
2895 return ans
2896
2897 # log10(0.0) == -Infinity
2898 if not self:
2899 return negInf
2900
2901 # log10(Infinity) = Infinity
2902 if self._isinfinity() == 1:
2903 return Inf
2904
2905 # log10(negative or -Infinity) raises InvalidOperation
2906 if self._sign == 1:
2907 return context._raise_error(InvalidOperation,
2908 'log10 of a negative value')
2909
2910 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002911 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002912 # answer may need rounding
2913 ans = Decimal(self._exp + len(self._int) - 1)
2914 else:
2915 # result is irrational, so necessarily inexact
2916 op = _WorkRep(self)
2917 c, e = op.int, op.exp
2918 p = context.prec
2919
2920 # correctly rounded result: repeatedly increase precision
2921 # until result is unambiguously roundable
2922 places = p-self._log10_exp_bound()+2
2923 while True:
2924 coeff = _dlog10(c, e, places)
2925 # assert len(str(abs(coeff)))-p >= 1
2926 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2927 break
2928 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002929 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002930
2931 context = context._shallow_copy()
2932 rounding = context._set_rounding(ROUND_HALF_EVEN)
2933 ans = ans._fix(context)
2934 context.rounding = rounding
2935 return ans
2936
2937 def logb(self, context=None):
2938 """ Returns the exponent of the magnitude of self's MSD.
2939
2940 The result is the integer which is the exponent of the magnitude
2941 of the most significant digit of self (as though it were truncated
2942 to a single digit while maintaining the value of that digit and
2943 without limiting the resulting exponent).
2944 """
2945 # logb(NaN) = NaN
2946 ans = self._check_nans(context=context)
2947 if ans:
2948 return ans
2949
2950 if context is None:
2951 context = getcontext()
2952
2953 # logb(+/-Inf) = +Inf
2954 if self._isinfinity():
2955 return Inf
2956
2957 # logb(0) = -Inf, DivisionByZero
2958 if not self:
2959 return context._raise_error(DivisionByZero, 'logb(0)', 1)
2960
2961 # otherwise, simply return the adjusted exponent of self, as a
2962 # Decimal. Note that no attempt is made to fit the result
2963 # into the current context.
2964 return Decimal(self.adjusted())
2965
2966 def _islogical(self):
2967 """Return True if self is a logical operand.
2968
2969 For being logical, it must be a finite numbers with a sign of 0,
2970 an exponent of 0, and a coefficient whose digits must all be
2971 either 0 or 1.
2972 """
2973 if self._sign != 0 or self._exp != 0:
2974 return False
2975 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002976 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002977 return False
2978 return True
2979
2980 def _fill_logical(self, context, opa, opb):
2981 dif = context.prec - len(opa)
2982 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002983 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002984 elif dif < 0:
2985 opa = opa[-context.prec:]
2986 dif = context.prec - len(opb)
2987 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002988 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002989 elif dif < 0:
2990 opb = opb[-context.prec:]
2991 return opa, opb
2992
2993 def logical_and(self, other, context=None):
2994 """Applies an 'and' operation between self and other's digits."""
2995 if context is None:
2996 context = getcontext()
2997 if not self._islogical() or not other._islogical():
2998 return context._raise_error(InvalidOperation)
2999
3000 # fill to context.prec
3001 (opa, opb) = self._fill_logical(context, self._int, other._int)
3002
3003 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003004 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3005 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003006
3007 def logical_invert(self, context=None):
3008 """Invert all its digits."""
3009 if context is None:
3010 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003011 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3012 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003013
3014 def logical_or(self, other, context=None):
3015 """Applies an 'or' operation between self and other's digits."""
3016 if context is None:
3017 context = getcontext()
3018 if not self._islogical() or not other._islogical():
3019 return context._raise_error(InvalidOperation)
3020
3021 # fill to context.prec
3022 (opa, opb) = self._fill_logical(context, self._int, other._int)
3023
3024 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003025 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3026 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003027
3028 def logical_xor(self, other, context=None):
3029 """Applies an 'xor' operation between self and other's digits."""
3030 if context is None:
3031 context = getcontext()
3032 if not self._islogical() or not other._islogical():
3033 return context._raise_error(InvalidOperation)
3034
3035 # fill to context.prec
3036 (opa, opb) = self._fill_logical(context, self._int, other._int)
3037
3038 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003039 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3040 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003041
3042 def max_mag(self, other, context=None):
3043 """Compares the values numerically with their sign ignored."""
3044 other = _convert_other(other, raiseit=True)
3045
3046 if context is None:
3047 context = getcontext()
3048
3049 if self._is_special or other._is_special:
3050 # If one operand is a quiet NaN and the other is number, then the
3051 # number is always returned
3052 sn = self._isnan()
3053 on = other._isnan()
3054 if sn or on:
3055 if on == 1 and sn != 2:
3056 return self._fix_nan(context)
3057 if sn == 1 and on != 2:
3058 return other._fix_nan(context)
3059 return self._check_nans(other, context)
3060
3061 c = self.copy_abs().__cmp__(other.copy_abs())
3062 if c == 0:
3063 c = self.compare_total(other)
3064
3065 if c == -1:
3066 ans = other
3067 else:
3068 ans = self
3069
Christian Heimes2c181612007-12-17 20:04:13 +00003070 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003071
3072 def min_mag(self, other, context=None):
3073 """Compares the values numerically with their sign ignored."""
3074 other = _convert_other(other, raiseit=True)
3075
3076 if context is None:
3077 context = getcontext()
3078
3079 if self._is_special or other._is_special:
3080 # If one operand is a quiet NaN and the other is number, then the
3081 # number is always returned
3082 sn = self._isnan()
3083 on = other._isnan()
3084 if sn or on:
3085 if on == 1 and sn != 2:
3086 return self._fix_nan(context)
3087 if sn == 1 and on != 2:
3088 return other._fix_nan(context)
3089 return self._check_nans(other, context)
3090
3091 c = self.copy_abs().__cmp__(other.copy_abs())
3092 if c == 0:
3093 c = self.compare_total(other)
3094
3095 if c == -1:
3096 ans = self
3097 else:
3098 ans = other
3099
Christian Heimes2c181612007-12-17 20:04:13 +00003100 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003101
3102 def next_minus(self, context=None):
3103 """Returns the largest representable number smaller than itself."""
3104 if context is None:
3105 context = getcontext()
3106
3107 ans = self._check_nans(context=context)
3108 if ans:
3109 return ans
3110
3111 if self._isinfinity() == -1:
3112 return negInf
3113 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003114 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003115
3116 context = context.copy()
3117 context._set_rounding(ROUND_FLOOR)
3118 context._ignore_all_flags()
3119 new_self = self._fix(context)
3120 if new_self != self:
3121 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003122 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3123 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003124
3125 def next_plus(self, context=None):
3126 """Returns the smallest representable number larger than itself."""
3127 if context is None:
3128 context = getcontext()
3129
3130 ans = self._check_nans(context=context)
3131 if ans:
3132 return ans
3133
3134 if self._isinfinity() == 1:
3135 return Inf
3136 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003137 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003138
3139 context = context.copy()
3140 context._set_rounding(ROUND_CEILING)
3141 context._ignore_all_flags()
3142 new_self = self._fix(context)
3143 if new_self != self:
3144 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003145 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3146 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003147
3148 def next_toward(self, other, context=None):
3149 """Returns the number closest to self, in the direction towards other.
3150
3151 The result is the closest representable number to self
3152 (excluding self) that is in the direction towards other,
3153 unless both have the same value. If the two operands are
3154 numerically equal, then the result is a copy of self with the
3155 sign set to be the same as the sign of other.
3156 """
3157 other = _convert_other(other, raiseit=True)
3158
3159 if context is None:
3160 context = getcontext()
3161
3162 ans = self._check_nans(other, context)
3163 if ans:
3164 return ans
3165
3166 comparison = self.__cmp__(other)
3167 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003168 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003169
3170 if comparison == -1:
3171 ans = self.next_plus(context)
3172 else: # comparison == 1
3173 ans = self.next_minus(context)
3174
3175 # decide which flags to raise using value of ans
3176 if ans._isinfinity():
3177 context._raise_error(Overflow,
3178 'Infinite result from next_toward',
3179 ans._sign)
3180 context._raise_error(Rounded)
3181 context._raise_error(Inexact)
3182 elif ans.adjusted() < context.Emin:
3183 context._raise_error(Underflow)
3184 context._raise_error(Subnormal)
3185 context._raise_error(Rounded)
3186 context._raise_error(Inexact)
3187 # if precision == 1 then we don't raise Clamped for a
3188 # result 0E-Etiny.
3189 if not ans:
3190 context._raise_error(Clamped)
3191
3192 return ans
3193
3194 def number_class(self, context=None):
3195 """Returns an indication of the class of self.
3196
3197 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003198 sNaN
3199 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003200 -Infinity
3201 -Normal
3202 -Subnormal
3203 -Zero
3204 +Zero
3205 +Subnormal
3206 +Normal
3207 +Infinity
3208 """
3209 if self.is_snan():
3210 return "sNaN"
3211 if self.is_qnan():
3212 return "NaN"
3213 inf = self._isinfinity()
3214 if inf == 1:
3215 return "+Infinity"
3216 if inf == -1:
3217 return "-Infinity"
3218 if self.is_zero():
3219 if self._sign:
3220 return "-Zero"
3221 else:
3222 return "+Zero"
3223 if context is None:
3224 context = getcontext()
3225 if self.is_subnormal(context=context):
3226 if self._sign:
3227 return "-Subnormal"
3228 else:
3229 return "+Subnormal"
3230 # just a normal, regular, boring number, :)
3231 if self._sign:
3232 return "-Normal"
3233 else:
3234 return "+Normal"
3235
3236 def radix(self):
3237 """Just returns 10, as this is Decimal, :)"""
3238 return Decimal(10)
3239
3240 def rotate(self, other, context=None):
3241 """Returns a rotated copy of self, value-of-other times."""
3242 if context is None:
3243 context = getcontext()
3244
3245 ans = self._check_nans(other, context)
3246 if ans:
3247 return ans
3248
3249 if other._exp != 0:
3250 return context._raise_error(InvalidOperation)
3251 if not (-context.prec <= int(other) <= context.prec):
3252 return context._raise_error(InvalidOperation)
3253
3254 if self._isinfinity():
3255 return Decimal(self)
3256
3257 # get values, pad if necessary
3258 torot = int(other)
3259 rotdig = self._int
3260 topad = context.prec - len(rotdig)
3261 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003262 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003263
3264 # let's rotate!
3265 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003266 return _dec_from_triple(self._sign,
3267 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003268
3269 def scaleb (self, other, context=None):
3270 """Returns self operand after adding the second value to its exp."""
3271 if context is None:
3272 context = getcontext()
3273
3274 ans = self._check_nans(other, context)
3275 if ans:
3276 return ans
3277
3278 if other._exp != 0:
3279 return context._raise_error(InvalidOperation)
3280 liminf = -2 * (context.Emax + context.prec)
3281 limsup = 2 * (context.Emax + context.prec)
3282 if not (liminf <= int(other) <= limsup):
3283 return context._raise_error(InvalidOperation)
3284
3285 if self._isinfinity():
3286 return Decimal(self)
3287
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003288 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003289 d = d._fix(context)
3290 return d
3291
3292 def shift(self, other, context=None):
3293 """Returns a shifted copy of self, value-of-other times."""
3294 if context is None:
3295 context = getcontext()
3296
3297 ans = self._check_nans(other, context)
3298 if ans:
3299 return ans
3300
3301 if other._exp != 0:
3302 return context._raise_error(InvalidOperation)
3303 if not (-context.prec <= int(other) <= context.prec):
3304 return context._raise_error(InvalidOperation)
3305
3306 if self._isinfinity():
3307 return Decimal(self)
3308
3309 # get values, pad if necessary
3310 torot = int(other)
3311 if not torot:
3312 return Decimal(self)
3313 rotdig = self._int
3314 topad = context.prec - len(rotdig)
3315 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003316 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003317
3318 # let's shift!
3319 if torot < 0:
3320 rotated = rotdig[:torot]
3321 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003322 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003323 rotated = rotated[-context.prec:]
3324
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003325 return _dec_from_triple(self._sign,
3326 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003327
Guido van Rossumd8faa362007-04-27 19:54:29 +00003328 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003329 def __reduce__(self):
3330 return (self.__class__, (str(self),))
3331
3332 def __copy__(self):
3333 if type(self) == Decimal:
3334 return self # I'm immutable; therefore I am my own clone
3335 return self.__class__(str(self))
3336
3337 def __deepcopy__(self, memo):
3338 if type(self) == Decimal:
3339 return self # My components are also immutable
3340 return self.__class__(str(self))
3341
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003342def _dec_from_triple(sign, coefficient, exponent, special=False):
3343 """Create a decimal instance directly, without any validation,
3344 normalization (e.g. removal of leading zeros) or argument
3345 conversion.
3346
3347 This function is for *internal use only*.
3348 """
3349
3350 self = object.__new__(Decimal)
3351 self._sign = sign
3352 self._int = coefficient
3353 self._exp = exponent
3354 self._is_special = special
3355
3356 return self
3357
Guido van Rossumd8faa362007-04-27 19:54:29 +00003358##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003359
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003360
3361# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003362rounding_functions = [name for name in Decimal.__dict__.keys()
3363 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003364for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003365 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003366 globalname = name[1:].upper()
3367 val = globals()[globalname]
3368 Decimal._pick_rounding_function[val] = name
3369
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003370del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003371
Thomas Wouters89f507f2006-12-13 04:49:30 +00003372class _ContextManager(object):
3373 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003374
Thomas Wouters89f507f2006-12-13 04:49:30 +00003375 Sets a copy of the supplied context in __enter__() and restores
3376 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003377 """
3378 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003379 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003380 def __enter__(self):
3381 self.saved_context = getcontext()
3382 setcontext(self.new_context)
3383 return self.new_context
3384 def __exit__(self, t, v, tb):
3385 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003386
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003387class Context(object):
3388 """Contains the context for a Decimal instance.
3389
3390 Contains:
3391 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003392 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003393 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003394 raised when it is caused. Otherwise, a value is
3395 substituted in.
3396 flags - When an exception is caused, flags[exception] is incremented.
3397 (Whether or not the trap_enabler is set)
3398 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003399 Emin - Minimum exponent
3400 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003401 capitals - If 1, 1*10^1 is printed as 1E+1.
3402 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003403 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003404 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003405
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003406 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003407 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003408 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003409 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003410 _ignored_flags=None):
3411 if flags is None:
3412 flags = []
3413 if _ignored_flags is None:
3414 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003415 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003416 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003417 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003418 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003419 for name, val in locals().items():
3420 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003421 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003422 else:
3423 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003424 del self.self
3425
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003426 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003427 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003428 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003429 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3430 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3431 % vars(self))
3432 names = [f.__name__ for f, v in self.flags.items() if v]
3433 s.append('flags=[' + ', '.join(names) + ']')
3434 names = [t.__name__ for t, v in self.traps.items() if v]
3435 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003436 return ', '.join(s) + ')'
3437
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003438 def clear_flags(self):
3439 """Reset all flags to zero"""
3440 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003441 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003442
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003443 def _shallow_copy(self):
3444 """Returns a shallow copy from self."""
Christian Heimes2c181612007-12-17 20:04:13 +00003445 nc = Context(self.prec, self.rounding, self.traps,
3446 self.flags, self.Emin, self.Emax,
3447 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003448 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003449
3450 def copy(self):
3451 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003452 nc = Context(self.prec, self.rounding, self.traps.copy(),
Christian Heimes2c181612007-12-17 20:04:13 +00003453 self.flags.copy(), self.Emin, self.Emax,
3454 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003455 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003456 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003457
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003458 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003459 """Handles an error
3460
3461 If the flag is in _ignored_flags, returns the default response.
3462 Otherwise, it increments the flag, then, if the corresponding
3463 trap_enabler is set, it reaises the exception. Otherwise, it returns
3464 the default value after incrementing the flag.
3465 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003466 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003467 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003468 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003469 return error().handle(self, *args)
3470
3471 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003472 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003473 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003474 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003475
3476 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003477 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003478 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003479
3480 def _ignore_all_flags(self):
3481 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003482 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003483
3484 def _ignore_flags(self, *flags):
3485 """Ignore the flags, if they are raised"""
3486 # Do not mutate-- This way, copies of a context leave the original
3487 # alone.
3488 self._ignored_flags = (self._ignored_flags + list(flags))
3489 return list(flags)
3490
3491 def _regard_flags(self, *flags):
3492 """Stop ignoring the flags, if they are raised"""
3493 if flags and isinstance(flags[0], (tuple,list)):
3494 flags = flags[0]
3495 for flag in flags:
3496 self._ignored_flags.remove(flag)
3497
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003498 def __hash__(self):
3499 """A Context cannot be hashed."""
3500 # We inherit object.__hash__, so we must deny this explicitly
Guido van Rossumd8faa362007-04-27 19:54:29 +00003501 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003502
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003503 def Etiny(self):
3504 """Returns Etiny (= Emin - prec + 1)"""
3505 return int(self.Emin - self.prec + 1)
3506
3507 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003508 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003509 return int(self.Emax - self.prec + 1)
3510
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003511 def _set_rounding(self, type):
3512 """Sets the rounding type.
3513
3514 Sets the rounding type, and returns the current (previous)
3515 rounding type. Often used like:
3516
3517 context = context.copy()
3518 # so you don't change the calling context
3519 # if an error occurs in the middle.
3520 rounding = context._set_rounding(ROUND_UP)
3521 val = self.__sub__(other, context=context)
3522 context._set_rounding(rounding)
3523
3524 This will make it round up for that operation.
3525 """
3526 rounding = self.rounding
3527 self.rounding= type
3528 return rounding
3529
Raymond Hettingerfed52962004-07-14 15:41:57 +00003530 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003531 """Creates a new Decimal instance but using self as context."""
3532 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003533 if d._isnan() and len(d._int) > self.prec - self._clamp:
3534 return self._raise_error(ConversionSyntax,
3535 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003536 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003537
Guido van Rossumd8faa362007-04-27 19:54:29 +00003538 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003539 def abs(self, a):
3540 """Returns the absolute value of the operand.
3541
3542 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003543 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003544 the plus operation on the operand.
3545
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003546 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003547 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003548 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003549 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003550 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003551 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003552 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003553 Decimal("101.5")
3554 """
3555 return a.__abs__(context=self)
3556
3557 def add(self, a, b):
3558 """Return the sum of the two operands.
3559
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003560 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003561 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003562 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003563 Decimal("1.02E+4")
3564 """
3565 return a.__add__(b, context=self)
3566
3567 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003568 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003569
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003570 def canonical(self, a):
3571 """Returns the same Decimal object.
3572
3573 As we do not have different encodings for the same number, the
3574 received object already is in its canonical form.
3575
3576 >>> ExtendedContext.canonical(Decimal('2.50'))
3577 Decimal("2.50")
3578 """
3579 return a.canonical(context=self)
3580
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003581 def compare(self, a, b):
3582 """Compares values numerically.
3583
3584 If the signs of the operands differ, a value representing each operand
3585 ('-1' if the operand is less than zero, '0' if the operand is zero or
3586 negative zero, or '1' if the operand is greater than zero) is used in
3587 place of that operand for the comparison instead of the actual
3588 operand.
3589
3590 The comparison is then effected by subtracting the second operand from
3591 the first and then returning a value according to the result of the
3592 subtraction: '-1' if the result is less than zero, '0' if the result is
3593 zero or negative zero, or '1' if the result is greater than zero.
3594
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003595 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003596 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003597 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003598 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003599 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003600 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003601 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003602 Decimal("1")
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('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003606 Decimal("-1")
3607 """
3608 return a.compare(b, context=self)
3609
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003610 def compare_signal(self, a, b):
3611 """Compares the values of the two operands numerically.
3612
3613 It's pretty much like compare(), but all NaNs signal, with signaling
3614 NaNs taking precedence over quiet NaNs.
3615
3616 >>> c = ExtendedContext
3617 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3618 Decimal("-1")
3619 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3620 Decimal("0")
3621 >>> c.flags[InvalidOperation] = 0
3622 >>> print(c.flags[InvalidOperation])
3623 0
3624 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3625 Decimal("NaN")
3626 >>> print(c.flags[InvalidOperation])
3627 1
3628 >>> c.flags[InvalidOperation] = 0
3629 >>> print(c.flags[InvalidOperation])
3630 0
3631 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3632 Decimal("NaN")
3633 >>> print(c.flags[InvalidOperation])
3634 1
3635 """
3636 return a.compare_signal(b, context=self)
3637
3638 def compare_total(self, a, b):
3639 """Compares two operands using their abstract representation.
3640
3641 This is not like the standard compare, which use their numerical
3642 value. Note that a total ordering is defined for all possible abstract
3643 representations.
3644
3645 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3646 Decimal("-1")
3647 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3648 Decimal("-1")
3649 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3650 Decimal("-1")
3651 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3652 Decimal("0")
3653 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3654 Decimal("1")
3655 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3656 Decimal("-1")
3657 """
3658 return a.compare_total(b)
3659
3660 def compare_total_mag(self, a, b):
3661 """Compares two operands using their abstract representation ignoring sign.
3662
3663 Like compare_total, but with operand's sign ignored and assumed to be 0.
3664 """
3665 return a.compare_total_mag(b)
3666
3667 def copy_abs(self, a):
3668 """Returns a copy of the operand with the sign set to 0.
3669
3670 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3671 Decimal("2.1")
3672 >>> ExtendedContext.copy_abs(Decimal('-100'))
3673 Decimal("100")
3674 """
3675 return a.copy_abs()
3676
3677 def copy_decimal(self, a):
3678 """Returns a copy of the decimal objet.
3679
3680 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3681 Decimal("2.1")
3682 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3683 Decimal("-1.00")
3684 """
3685 return Decimal(a)
3686
3687 def copy_negate(self, a):
3688 """Returns a copy of the operand with the sign inverted.
3689
3690 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3691 Decimal("-101.5")
3692 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3693 Decimal("101.5")
3694 """
3695 return a.copy_negate()
3696
3697 def copy_sign(self, a, b):
3698 """Copies the second operand's sign to the first one.
3699
3700 In detail, it returns a copy of the first operand with the sign
3701 equal to the sign of the second operand.
3702
3703 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3704 Decimal("1.50")
3705 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3706 Decimal("1.50")
3707 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3708 Decimal("-1.50")
3709 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3710 Decimal("-1.50")
3711 """
3712 return a.copy_sign(b)
3713
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003714 def divide(self, a, b):
3715 """Decimal division in a specified context.
3716
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003717 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003718 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003719 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003720 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003721 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003722 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003723 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003724 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003725 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003726 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003727 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003728 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003729 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003730 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003731 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003732 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003733 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003734 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003735 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003736 Decimal("1.20E+6")
3737 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003738 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003739
3740 def divide_int(self, a, b):
3741 """Divides two numbers and returns the integer part of the result.
3742
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003743 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003744 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003745 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003746 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003747 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003748 Decimal("3")
3749 """
3750 return a.__floordiv__(b, context=self)
3751
3752 def divmod(self, a, b):
3753 return a.__divmod__(b, context=self)
3754
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003755 def exp(self, a):
3756 """Returns e ** a.
3757
3758 >>> c = ExtendedContext.copy()
3759 >>> c.Emin = -999
3760 >>> c.Emax = 999
3761 >>> c.exp(Decimal('-Infinity'))
3762 Decimal("0")
3763 >>> c.exp(Decimal('-1'))
3764 Decimal("0.367879441")
3765 >>> c.exp(Decimal('0'))
3766 Decimal("1")
3767 >>> c.exp(Decimal('1'))
3768 Decimal("2.71828183")
3769 >>> c.exp(Decimal('0.693147181'))
3770 Decimal("2.00000000")
3771 >>> c.exp(Decimal('+Infinity'))
3772 Decimal("Infinity")
3773 """
3774 return a.exp(context=self)
3775
3776 def fma(self, a, b, c):
3777 """Returns a multiplied by b, plus c.
3778
3779 The first two operands are multiplied together, using multiply,
3780 the third operand is then added to the result of that
3781 multiplication, using add, all with only one final rounding.
3782
3783 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3784 Decimal("22")
3785 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3786 Decimal("-8")
3787 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3788 Decimal("1.38435736E+12")
3789 """
3790 return a.fma(b, c, context=self)
3791
3792 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003793 """Return True if the operand is canonical; otherwise return False.
3794
3795 Currently, the encoding of a Decimal instance is always
3796 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003797
3798 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003799 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003800 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003801 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003802
3803 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003804 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003805
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003806 A Decimal instance is considered finite if it is neither
3807 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003808
3809 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003810 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003811 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003812 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003813 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003814 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003815 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003816 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003817 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003818 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003819 """
3820 return a.is_finite()
3821
3822 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003823 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003824
3825 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003826 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003827 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003828 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003829 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003830 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003831 """
3832 return a.is_infinite()
3833
3834 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003835 """Return True if the operand is a qNaN or sNaN;
3836 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003837
3838 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003839 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003840 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003841 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003842 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003843 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003844 """
3845 return a.is_nan()
3846
3847 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003848 """Return True if the operand is a normal number;
3849 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003850
3851 >>> c = ExtendedContext.copy()
3852 >>> c.Emin = -999
3853 >>> c.Emax = 999
3854 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003855 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003856 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003857 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003858 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003859 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003860 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003861 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003862 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003863 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003864 """
3865 return a.is_normal(context=self)
3866
3867 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003868 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003869
3870 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003871 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003872 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003873 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003874 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003875 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003876 """
3877 return a.is_qnan()
3878
3879 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003880 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003881
3882 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003883 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003884 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003885 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003886 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003887 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003888 """
3889 return a.is_signed()
3890
3891 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003892 """Return True if the operand is a signaling NaN;
3893 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003894
3895 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003896 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003897 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003898 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003899 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003900 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003901 """
3902 return a.is_snan()
3903
3904 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003905 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003906
3907 >>> c = ExtendedContext.copy()
3908 >>> c.Emin = -999
3909 >>> c.Emax = 999
3910 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003911 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003912 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003913 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003914 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003915 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003916 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003917 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003918 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003919 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003920 """
3921 return a.is_subnormal(context=self)
3922
3923 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003924 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003925
3926 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003927 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003928 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003929 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003930 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003931 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003932 """
3933 return a.is_zero()
3934
3935 def ln(self, a):
3936 """Returns the natural (base e) logarithm of the operand.
3937
3938 >>> c = ExtendedContext.copy()
3939 >>> c.Emin = -999
3940 >>> c.Emax = 999
3941 >>> c.ln(Decimal('0'))
3942 Decimal("-Infinity")
3943 >>> c.ln(Decimal('1.000'))
3944 Decimal("0")
3945 >>> c.ln(Decimal('2.71828183'))
3946 Decimal("1.00000000")
3947 >>> c.ln(Decimal('10'))
3948 Decimal("2.30258509")
3949 >>> c.ln(Decimal('+Infinity'))
3950 Decimal("Infinity")
3951 """
3952 return a.ln(context=self)
3953
3954 def log10(self, a):
3955 """Returns the base 10 logarithm of the operand.
3956
3957 >>> c = ExtendedContext.copy()
3958 >>> c.Emin = -999
3959 >>> c.Emax = 999
3960 >>> c.log10(Decimal('0'))
3961 Decimal("-Infinity")
3962 >>> c.log10(Decimal('0.001'))
3963 Decimal("-3")
3964 >>> c.log10(Decimal('1.000'))
3965 Decimal("0")
3966 >>> c.log10(Decimal('2'))
3967 Decimal("0.301029996")
3968 >>> c.log10(Decimal('10'))
3969 Decimal("1")
3970 >>> c.log10(Decimal('70'))
3971 Decimal("1.84509804")
3972 >>> c.log10(Decimal('+Infinity'))
3973 Decimal("Infinity")
3974 """
3975 return a.log10(context=self)
3976
3977 def logb(self, a):
3978 """ Returns the exponent of the magnitude of the operand's MSD.
3979
3980 The result is the integer which is the exponent of the magnitude
3981 of the most significant digit of the operand (as though the
3982 operand were truncated to a single digit while maintaining the
3983 value of that digit and without limiting the resulting exponent).
3984
3985 >>> ExtendedContext.logb(Decimal('250'))
3986 Decimal("2")
3987 >>> ExtendedContext.logb(Decimal('2.50'))
3988 Decimal("0")
3989 >>> ExtendedContext.logb(Decimal('0.03'))
3990 Decimal("-2")
3991 >>> ExtendedContext.logb(Decimal('0'))
3992 Decimal("-Infinity")
3993 """
3994 return a.logb(context=self)
3995
3996 def logical_and(self, a, b):
3997 """Applies the logical operation 'and' between each operand's digits.
3998
3999 The operands must be both logical numbers.
4000
4001 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4002 Decimal("0")
4003 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4004 Decimal("0")
4005 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4006 Decimal("0")
4007 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4008 Decimal("1")
4009 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4010 Decimal("1000")
4011 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4012 Decimal("10")
4013 """
4014 return a.logical_and(b, context=self)
4015
4016 def logical_invert(self, a):
4017 """Invert all the digits in the operand.
4018
4019 The operand must be a logical number.
4020
4021 >>> ExtendedContext.logical_invert(Decimal('0'))
4022 Decimal("111111111")
4023 >>> ExtendedContext.logical_invert(Decimal('1'))
4024 Decimal("111111110")
4025 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4026 Decimal("0")
4027 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4028 Decimal("10101010")
4029 """
4030 return a.logical_invert(context=self)
4031
4032 def logical_or(self, a, b):
4033 """Applies the logical operation 'or' between each operand's digits.
4034
4035 The operands must be both logical numbers.
4036
4037 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4038 Decimal("0")
4039 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4040 Decimal("1")
4041 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4042 Decimal("1")
4043 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4044 Decimal("1")
4045 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4046 Decimal("1110")
4047 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4048 Decimal("1110")
4049 """
4050 return a.logical_or(b, context=self)
4051
4052 def logical_xor(self, a, b):
4053 """Applies the logical operation 'xor' between each operand's digits.
4054
4055 The operands must be both logical numbers.
4056
4057 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4058 Decimal("0")
4059 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4060 Decimal("1")
4061 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4062 Decimal("1")
4063 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4064 Decimal("0")
4065 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4066 Decimal("110")
4067 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4068 Decimal("1101")
4069 """
4070 return a.logical_xor(b, context=self)
4071
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004072 def max(self, a,b):
4073 """max compares two values numerically and returns the maximum.
4074
4075 If either operand is a NaN then the general rules apply.
4076 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004077 operation. If they are numerically equal then the left-hand operand
4078 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004079 infinity) of the two operands is chosen as the result.
4080
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004081 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004082 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004083 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004084 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004085 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004086 Decimal("1")
4087 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4088 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004089 """
4090 return a.max(b, context=self)
4091
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004092 def max_mag(self, a, b):
4093 """Compares the values numerically with their sign ignored."""
4094 return a.max_mag(b, context=self)
4095
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004096 def min(self, a,b):
4097 """min compares two values numerically and returns the minimum.
4098
4099 If either operand is a NaN then the general rules apply.
4100 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004101 operation. If they are numerically equal then the left-hand operand
4102 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004103 infinity) of the two operands is chosen as the result.
4104
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004105 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004106 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004107 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004108 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004109 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004110 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004111 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4112 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004113 """
4114 return a.min(b, context=self)
4115
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004116 def min_mag(self, a, b):
4117 """Compares the values numerically with their sign ignored."""
4118 return a.min_mag(b, context=self)
4119
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004120 def minus(self, a):
4121 """Minus corresponds to unary prefix minus in Python.
4122
4123 The operation is evaluated using the same rules as subtract; the
4124 operation minus(a) is calculated as subtract('0', a) where the '0'
4125 has the same exponent as the operand.
4126
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004127 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004128 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004129 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004130 Decimal("1.3")
4131 """
4132 return a.__neg__(context=self)
4133
4134 def multiply(self, a, b):
4135 """multiply multiplies two operands.
4136
4137 If either operand is a special value then the general rules apply.
4138 Otherwise, the operands are multiplied together ('long multiplication'),
4139 resulting in a number which may be as long as the sum of the lengths
4140 of the two operands.
4141
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004142 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004143 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004144 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004145 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004146 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004147 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004148 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004149 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004150 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004151 Decimal("4.28135971E+11")
4152 """
4153 return a.__mul__(b, context=self)
4154
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004155 def next_minus(self, a):
4156 """Returns the largest representable number smaller than a.
4157
4158 >>> c = ExtendedContext.copy()
4159 >>> c.Emin = -999
4160 >>> c.Emax = 999
4161 >>> ExtendedContext.next_minus(Decimal('1'))
4162 Decimal("0.999999999")
4163 >>> c.next_minus(Decimal('1E-1007'))
4164 Decimal("0E-1007")
4165 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4166 Decimal("-1.00000004")
4167 >>> c.next_minus(Decimal('Infinity'))
4168 Decimal("9.99999999E+999")
4169 """
4170 return a.next_minus(context=self)
4171
4172 def next_plus(self, a):
4173 """Returns the smallest representable number larger than a.
4174
4175 >>> c = ExtendedContext.copy()
4176 >>> c.Emin = -999
4177 >>> c.Emax = 999
4178 >>> ExtendedContext.next_plus(Decimal('1'))
4179 Decimal("1.00000001")
4180 >>> c.next_plus(Decimal('-1E-1007'))
4181 Decimal("-0E-1007")
4182 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4183 Decimal("-1.00000002")
4184 >>> c.next_plus(Decimal('-Infinity'))
4185 Decimal("-9.99999999E+999")
4186 """
4187 return a.next_plus(context=self)
4188
4189 def next_toward(self, a, b):
4190 """Returns the number closest to a, in direction towards b.
4191
4192 The result is the closest representable number from the first
4193 operand (but not the first operand) that is in the direction
4194 towards the second operand, unless the operands have the same
4195 value.
4196
4197 >>> c = ExtendedContext.copy()
4198 >>> c.Emin = -999
4199 >>> c.Emax = 999
4200 >>> c.next_toward(Decimal('1'), Decimal('2'))
4201 Decimal("1.00000001")
4202 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4203 Decimal("-0E-1007")
4204 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4205 Decimal("-1.00000002")
4206 >>> c.next_toward(Decimal('1'), Decimal('0'))
4207 Decimal("0.999999999")
4208 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4209 Decimal("0E-1007")
4210 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4211 Decimal("-1.00000004")
4212 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4213 Decimal("-0.00")
4214 """
4215 return a.next_toward(b, context=self)
4216
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004217 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004218 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004219
4220 Essentially a plus operation with all trailing zeros removed from the
4221 result.
4222
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004223 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004224 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004225 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004226 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004227 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004228 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004229 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004230 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004231 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004232 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004233 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004234 Decimal("0")
4235 """
4236 return a.normalize(context=self)
4237
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004238 def number_class(self, a):
4239 """Returns an indication of the class of the operand.
4240
4241 The class is one of the following strings:
4242 -sNaN
4243 -NaN
4244 -Infinity
4245 -Normal
4246 -Subnormal
4247 -Zero
4248 +Zero
4249 +Subnormal
4250 +Normal
4251 +Infinity
4252
4253 >>> c = Context(ExtendedContext)
4254 >>> c.Emin = -999
4255 >>> c.Emax = 999
4256 >>> c.number_class(Decimal('Infinity'))
4257 '+Infinity'
4258 >>> c.number_class(Decimal('1E-10'))
4259 '+Normal'
4260 >>> c.number_class(Decimal('2.50'))
4261 '+Normal'
4262 >>> c.number_class(Decimal('0.1E-999'))
4263 '+Subnormal'
4264 >>> c.number_class(Decimal('0'))
4265 '+Zero'
4266 >>> c.number_class(Decimal('-0'))
4267 '-Zero'
4268 >>> c.number_class(Decimal('-0.1E-999'))
4269 '-Subnormal'
4270 >>> c.number_class(Decimal('-1E-10'))
4271 '-Normal'
4272 >>> c.number_class(Decimal('-2.50'))
4273 '-Normal'
4274 >>> c.number_class(Decimal('-Infinity'))
4275 '-Infinity'
4276 >>> c.number_class(Decimal('NaN'))
4277 'NaN'
4278 >>> c.number_class(Decimal('-NaN'))
4279 'NaN'
4280 >>> c.number_class(Decimal('sNaN'))
4281 'sNaN'
4282 """
4283 return a.number_class(context=self)
4284
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004285 def plus(self, a):
4286 """Plus corresponds to unary prefix plus in Python.
4287
4288 The operation is evaluated using the same rules as add; the
4289 operation plus(a) is calculated as add('0', a) where the '0'
4290 has the same exponent as the operand.
4291
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004292 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004293 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004294 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004295 Decimal("-1.3")
4296 """
4297 return a.__pos__(context=self)
4298
4299 def power(self, a, b, modulo=None):
4300 """Raises a to the power of b, to modulo if given.
4301
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004302 With two arguments, compute a**b. If a is negative then b
4303 must be integral. The result will be inexact unless b is
4304 integral and the result is finite and can be expressed exactly
4305 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004306
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004307 With three arguments, compute (a**b) % modulo. For the
4308 three argument form, the following restrictions on the
4309 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004310
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004311 - all three arguments must be integral
4312 - b must be nonnegative
4313 - at least one of a or b must be nonzero
4314 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004315
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004316 The result of pow(a, b, modulo) is identical to the result
4317 that would be obtained by computing (a**b) % modulo with
4318 unbounded precision, but is computed more efficiently. It is
4319 always exact.
4320
4321 >>> c = ExtendedContext.copy()
4322 >>> c.Emin = -999
4323 >>> c.Emax = 999
4324 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004325 Decimal("8")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004326 >>> c.power(Decimal('-2'), Decimal('3'))
4327 Decimal("-8")
4328 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004329 Decimal("0.125")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004330 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004331 Decimal("69.7575744")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004332 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4333 Decimal("2.00000000")
4334 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004335 Decimal("0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004336 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004337 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004338 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004339 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004340 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004341 Decimal("-0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004342 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004343 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004344 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004345 Decimal("-Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004346 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004347 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004348 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004349 Decimal("NaN")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004350
4351 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4352 Decimal("11")
4353 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4354 Decimal("-11")
4355 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4356 Decimal("1")
4357 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4358 Decimal("11")
4359 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4360 Decimal("11729830")
4361 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4362 Decimal("-0")
4363 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4364 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004365 """
4366 return a.__pow__(b, modulo, context=self)
4367
4368 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004369 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004370
4371 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004372 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004373 exponent is being increased), multiplied by a positive power of ten (if
4374 the exponent is being decreased), or is unchanged (if the exponent is
4375 already equal to that of the right-hand operand).
4376
4377 Unlike other operations, if the length of the coefficient after the
4378 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004379 operation condition is raised. This guarantees that, unless there is
4380 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004381 equal to that of the right-hand operand.
4382
4383 Also unlike other operations, quantize will never raise Underflow, even
4384 if the result is subnormal and inexact.
4385
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004386 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004387 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004388 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004389 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004390 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004391 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004392 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004393 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004394 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004395 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004396 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004397 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004398 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004399 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004400 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004401 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004402 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004403 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004404 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004405 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004406 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004407 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004408 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004409 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004410 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004411 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004412 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004413 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004414 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004415 Decimal("2E+2")
4416 """
4417 return a.quantize(b, context=self)
4418
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004419 def radix(self):
4420 """Just returns 10, as this is Decimal, :)
4421
4422 >>> ExtendedContext.radix()
4423 Decimal("10")
4424 """
4425 return Decimal(10)
4426
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004427 def remainder(self, a, b):
4428 """Returns the remainder from integer division.
4429
4430 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004431 calculating integer division as described for divide-integer, rounded
4432 to precision digits if necessary. The sign of the result, if
4433 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004434
4435 This operation will fail under the same conditions as integer division
4436 (that is, if integer division on the same two operands would fail, the
4437 remainder cannot be calculated).
4438
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004439 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004440 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004441 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004442 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004443 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004444 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004445 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004446 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004447 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004448 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004449 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004450 Decimal("1.0")
4451 """
4452 return a.__mod__(b, context=self)
4453
4454 def remainder_near(self, a, b):
4455 """Returns to be "a - b * n", where n is the integer nearest the exact
4456 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004457 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004458 sign of a.
4459
4460 This operation will fail under the same conditions as integer division
4461 (that is, if integer division on the same two operands would fail, the
4462 remainder cannot be calculated).
4463
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004464 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004465 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004466 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004467 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004468 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004469 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004470 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004471 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004472 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004473 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004474 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004475 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004476 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004477 Decimal("-0.3")
4478 """
4479 return a.remainder_near(b, context=self)
4480
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004481 def rotate(self, a, b):
4482 """Returns a rotated copy of a, b times.
4483
4484 The coefficient of the result is a rotated copy of the digits in
4485 the coefficient of the first operand. The number of places of
4486 rotation is taken from the absolute value of the second operand,
4487 with the rotation being to the left if the second operand is
4488 positive or to the right otherwise.
4489
4490 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4491 Decimal("400000003")
4492 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4493 Decimal("12")
4494 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4495 Decimal("891234567")
4496 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4497 Decimal("123456789")
4498 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4499 Decimal("345678912")
4500 """
4501 return a.rotate(b, context=self)
4502
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004503 def same_quantum(self, a, b):
4504 """Returns True if the two operands have the same exponent.
4505
4506 The result is never affected by either the sign or the coefficient of
4507 either operand.
4508
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004509 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004510 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004511 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004512 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004513 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004514 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004515 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004516 True
4517 """
4518 return a.same_quantum(b)
4519
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004520 def scaleb (self, a, b):
4521 """Returns the first operand after adding the second value its exp.
4522
4523 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4524 Decimal("0.0750")
4525 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4526 Decimal("7.50")
4527 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4528 Decimal("7.50E+3")
4529 """
4530 return a.scaleb (b, context=self)
4531
4532 def shift(self, a, b):
4533 """Returns a shifted copy of a, b times.
4534
4535 The coefficient of the result is a shifted copy of the digits
4536 in the coefficient of the first operand. The number of places
4537 to shift is taken from the absolute value of the second operand,
4538 with the shift being to the left if the second operand is
4539 positive or to the right otherwise. Digits shifted into the
4540 coefficient are zeros.
4541
4542 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4543 Decimal("400000000")
4544 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4545 Decimal("0")
4546 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4547 Decimal("1234567")
4548 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4549 Decimal("123456789")
4550 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4551 Decimal("345678900")
4552 """
4553 return a.shift(b, context=self)
4554
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004555 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004556 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004557
4558 If the result must be inexact, it is rounded using the round-half-even
4559 algorithm.
4560
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004561 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004562 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004563 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004564 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004565 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004566 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004567 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004568 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004569 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004570 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004571 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004572 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004573 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004574 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004575 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004576 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004577 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004578 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004579 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004580 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004581 """
4582 return a.sqrt(context=self)
4583
4584 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004585 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004586
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004587 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004588 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004589 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004590 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004591 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004592 Decimal("-0.77")
4593 """
4594 return a.__sub__(b, context=self)
4595
4596 def to_eng_string(self, a):
4597 """Converts a number to a string, using scientific notation.
4598
4599 The operation is not affected by the context.
4600 """
4601 return a.to_eng_string(context=self)
4602
4603 def to_sci_string(self, a):
4604 """Converts a number to a string, using scientific notation.
4605
4606 The operation is not affected by the context.
4607 """
4608 return a.__str__(context=self)
4609
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004610 def to_integral_exact(self, a):
4611 """Rounds to an integer.
4612
4613 When the operand has a negative exponent, the result is the same
4614 as using the quantize() operation using the given operand as the
4615 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4616 of the operand as the precision setting; Inexact and Rounded flags
4617 are allowed in this operation. The rounding mode is taken from the
4618 context.
4619
4620 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4621 Decimal("2")
4622 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4623 Decimal("100")
4624 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4625 Decimal("100")
4626 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4627 Decimal("102")
4628 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4629 Decimal("-102")
4630 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4631 Decimal("1.0E+6")
4632 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4633 Decimal("7.89E+77")
4634 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4635 Decimal("-Infinity")
4636 """
4637 return a.to_integral_exact(context=self)
4638
4639 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004640 """Rounds to an integer.
4641
4642 When the operand has a negative exponent, the result is the same
4643 as using the quantize() operation using the given operand as the
4644 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4645 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004646 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004647
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004648 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004649 Decimal("2")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004650 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004651 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004652 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004653 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004654 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004655 Decimal("102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004656 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004657 Decimal("-102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004658 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004659 Decimal("1.0E+6")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004660 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004661 Decimal("7.89E+77")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004662 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004663 Decimal("-Infinity")
4664 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004665 return a.to_integral_value(context=self)
4666
4667 # the method name changed, but we provide also the old one, for compatibility
4668 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004669
4670class _WorkRep(object):
4671 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004672 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004673 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004674 # exp: None, int, or string
4675
4676 def __init__(self, value=None):
4677 if value is None:
4678 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004679 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004680 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004681 elif isinstance(value, Decimal):
4682 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00004683 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004684 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004685 else:
4686 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004687 self.sign = value[0]
4688 self.int = value[1]
4689 self.exp = value[2]
4690
4691 def __repr__(self):
4692 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4693
4694 __str__ = __repr__
4695
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004696
4697
Christian Heimes2c181612007-12-17 20:04:13 +00004698def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004699 """Normalizes op1, op2 to have the same exp and length of coefficient.
4700
4701 Done during addition.
4702 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004703 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004704 tmp = op2
4705 other = op1
4706 else:
4707 tmp = op1
4708 other = op2
4709
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004710 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4711 # Then adding 10**exp to tmp has the same effect (after rounding)
4712 # as adding any positive quantity smaller than 10**exp; similarly
4713 # for subtraction. So if other is smaller than 10**exp we replace
4714 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00004715 tmp_len = len(str(tmp.int))
4716 other_len = len(str(other.int))
4717 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4718 if other_len + other.exp - 1 < exp:
4719 other.int = 1
4720 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004721
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004722 tmp.int *= 10 ** (tmp.exp - other.exp)
4723 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004724 return op1, op2
4725
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004726##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004727
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004728# This function from Tim Peters was taken from here:
4729# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4730# The correction being in the function definition is for speed, and
4731# the whole function is not resolved with math.log because of avoiding
4732# the use of floats.
4733def _nbits(n, correction = {
4734 '0': 4, '1': 3, '2': 2, '3': 2,
4735 '4': 1, '5': 1, '6': 1, '7': 1,
4736 '8': 0, '9': 0, 'a': 0, 'b': 0,
4737 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4738 """Number of bits in binary representation of the positive integer n,
4739 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004740 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004741 if n < 0:
4742 raise ValueError("The argument to _nbits should be nonnegative.")
4743 hex_n = "%x" % n
4744 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004745
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004746def _sqrt_nearest(n, a):
4747 """Closest integer to the square root of the positive integer n. a is
4748 an initial approximation to the square root. Any positive integer
4749 will do for a, but the closer a is to the square root of n the
4750 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004751
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004752 """
4753 if n <= 0 or a <= 0:
4754 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4755
4756 b=0
4757 while a != b:
4758 b, a = a, a--n//a>>1
4759 return a
4760
4761def _rshift_nearest(x, shift):
4762 """Given an integer x and a nonnegative integer shift, return closest
4763 integer to x / 2**shift; use round-to-even in case of a tie.
4764
4765 """
4766 b, q = 1 << shift, x >> shift
4767 return q + (2*(x & (b-1)) + (q&1) > b)
4768
4769def _div_nearest(a, b):
4770 """Closest integer to a/b, a and b positive integers; rounds to even
4771 in the case of a tie.
4772
4773 """
4774 q, r = divmod(a, b)
4775 return q + (2*r + (q&1) > b)
4776
4777def _ilog(x, M, L = 8):
4778 """Integer approximation to M*log(x/M), with absolute error boundable
4779 in terms only of x/M.
4780
4781 Given positive integers x and M, return an integer approximation to
4782 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4783 between the approximation and the exact result is at most 22. For
4784 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4785 both cases these are upper bounds on the error; it will usually be
4786 much smaller."""
4787
4788 # The basic algorithm is the following: let log1p be the function
4789 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4790 # the reduction
4791 #
4792 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4793 #
4794 # repeatedly until the argument to log1p is small (< 2**-L in
4795 # absolute value). For small y we can use the Taylor series
4796 # expansion
4797 #
4798 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4799 #
4800 # truncating at T such that y**T is small enough. The whole
4801 # computation is carried out in a form of fixed-point arithmetic,
4802 # with a real number z being represented by an integer
4803 # approximation to z*M. To avoid loss of precision, the y below
4804 # is actually an integer approximation to 2**R*y*M, where R is the
4805 # number of reductions performed so far.
4806
4807 y = x-M
4808 # argument reduction; R = number of reductions performed
4809 R = 0
4810 while (R <= L and abs(y) << L-R >= M or
4811 R > L and abs(y) >> R-L >= M):
4812 y = _div_nearest((M*y) << 1,
4813 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4814 R += 1
4815
4816 # Taylor series with T terms
4817 T = -int(-10*len(str(M))//(3*L))
4818 yshift = _rshift_nearest(y, R)
4819 w = _div_nearest(M, T)
4820 for k in range(T-1, 0, -1):
4821 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4822
4823 return _div_nearest(w*y, M)
4824
4825def _dlog10(c, e, p):
4826 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4827 approximation to 10**p * log10(c*10**e), with an absolute error of
4828 at most 1. Assumes that c*10**e is not exactly 1."""
4829
4830 # increase precision by 2; compensate for this by dividing
4831 # final result by 100
4832 p += 2
4833
4834 # write c*10**e as d*10**f with either:
4835 # f >= 0 and 1 <= d <= 10, or
4836 # f <= 0 and 0.1 <= d <= 1.
4837 # Thus for c*10**e close to 1, f = 0
4838 l = len(str(c))
4839 f = e+l - (e+l >= 1)
4840
4841 if p > 0:
4842 M = 10**p
4843 k = e+p-f
4844 if k >= 0:
4845 c *= 10**k
4846 else:
4847 c = _div_nearest(c, 10**-k)
4848
4849 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004850 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004851 log_d = _div_nearest(log_d*M, log_10)
4852 log_tenpower = f*M # exact
4853 else:
4854 log_d = 0 # error < 2.31
4855 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4856
4857 return _div_nearest(log_tenpower+log_d, 100)
4858
4859def _dlog(c, e, p):
4860 """Given integers c, e and p with c > 0, compute an integer
4861 approximation to 10**p * log(c*10**e), with an absolute error of
4862 at most 1. Assumes that c*10**e is not exactly 1."""
4863
4864 # Increase precision by 2. The precision increase is compensated
4865 # for at the end with a division by 100.
4866 p += 2
4867
4868 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4869 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4870 # as 10**p * log(d) + 10**p*f * log(10).
4871 l = len(str(c))
4872 f = e+l - (e+l >= 1)
4873
4874 # compute approximation to 10**p*log(d), with error < 27
4875 if p > 0:
4876 k = e+p-f
4877 if k >= 0:
4878 c *= 10**k
4879 else:
4880 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4881
4882 # _ilog magnifies existing error in c by a factor of at most 10
4883 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4884 else:
4885 # p <= 0: just approximate the whole thing by 0; error < 2.31
4886 log_d = 0
4887
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004888 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004889 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004890 extra = len(str(abs(f)))-1
4891 if p + extra >= 0:
4892 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4893 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4894 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004895 else:
4896 f_log_ten = 0
4897 else:
4898 f_log_ten = 0
4899
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004900 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004901 return _div_nearest(f_log_ten + log_d, 100)
4902
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004903class _Log10Memoize(object):
4904 """Class to compute, store, and allow retrieval of, digits of the
4905 constant log(10) = 2.302585.... This constant is needed by
4906 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4907 def __init__(self):
4908 self.digits = "23025850929940456840179914546843642076011014886"
4909
4910 def getdigits(self, p):
4911 """Given an integer p >= 0, return floor(10**p)*log(10).
4912
4913 For example, self.getdigits(3) returns 2302.
4914 """
4915 # digits are stored as a string, for quick conversion to
4916 # integer in the case that we've already computed enough
4917 # digits; the stored digits should always be correct
4918 # (truncated, not rounded to nearest).
4919 if p < 0:
4920 raise ValueError("p should be nonnegative")
4921
4922 if p >= len(self.digits):
4923 # compute p+3, p+6, p+9, ... digits; continue until at
4924 # least one of the extra digits is nonzero
4925 extra = 3
4926 while True:
4927 # compute p+extra digits, correct to within 1ulp
4928 M = 10**(p+extra+2)
4929 digits = str(_div_nearest(_ilog(10*M, M), 100))
4930 if digits[-extra:] != '0'*extra:
4931 break
4932 extra += 3
4933 # keep all reliable digits so far; remove trailing zeros
4934 # and next nonzero digit
4935 self.digits = digits.rstrip('0')[:-1]
4936 return int(self.digits[:p+1])
4937
4938_log10_digits = _Log10Memoize().getdigits
4939
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004940def _iexp(x, M, L=8):
4941 """Given integers x and M, M > 0, such that x/M is small in absolute
4942 value, compute an integer approximation to M*exp(x/M). For 0 <=
4943 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4944 is usually much smaller)."""
4945
4946 # Algorithm: to compute exp(z) for a real number z, first divide z
4947 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4948 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4949 # series
4950 #
4951 # expm1(x) = x + x**2/2! + x**3/3! + ...
4952 #
4953 # Now use the identity
4954 #
4955 # expm1(2x) = expm1(x)*(expm1(x)+2)
4956 #
4957 # R times to compute the sequence expm1(z/2**R),
4958 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
4959
4960 # Find R such that x/2**R/M <= 2**-L
4961 R = _nbits((x<<L)//M)
4962
4963 # Taylor series. (2**L)**T > M
4964 T = -int(-10*len(str(M))//(3*L))
4965 y = _div_nearest(x, T)
4966 Mshift = M<<R
4967 for i in range(T-1, 0, -1):
4968 y = _div_nearest(x*(Mshift + y), Mshift * i)
4969
4970 # Expansion
4971 for k in range(R-1, -1, -1):
4972 Mshift = M<<(k+2)
4973 y = _div_nearest(y*(y+Mshift), Mshift)
4974
4975 return M+y
4976
4977def _dexp(c, e, p):
4978 """Compute an approximation to exp(c*10**e), with p decimal places of
4979 precision.
4980
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004981 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004982
4983 10**(p-1) <= d <= 10**p, and
4984 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
4985
4986 In other words, d*10**f is an approximation to exp(c*10**e) with p
4987 digits of precision, and with an error in d of at most 1. This is
4988 almost, but not quite, the same as the error being < 1ulp: when d
4989 = 10**(p-1) the error could be up to 10 ulp."""
4990
4991 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
4992 p += 2
4993
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004994 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004995 extra = max(0, e + len(str(c)) - 1)
4996 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004997
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004998 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004999 # rounding down
5000 shift = e+q
5001 if shift >= 0:
5002 cshift = c*10**shift
5003 else:
5004 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005005 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005006
5007 # reduce remainder back to original precision
5008 rem = _div_nearest(rem, 10**extra)
5009
5010 # error in result of _iexp < 120; error after division < 0.62
5011 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5012
5013def _dpower(xc, xe, yc, ye, p):
5014 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5015 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5016
5017 10**(p-1) <= c <= 10**p, and
5018 (c-1)*10**e < x**y < (c+1)*10**e
5019
5020 in other words, c*10**e is an approximation to x**y with p digits
5021 of precision, and with an error in c of at most 1. (This is
5022 almost, but not quite, the same as the error being < 1ulp: when c
5023 == 10**(p-1) we can only guarantee error < 10ulp.)
5024
5025 We assume that: x is positive and not equal to 1, and y is nonzero.
5026 """
5027
5028 # Find b such that 10**(b-1) <= |y| <= 10**b
5029 b = len(str(abs(yc))) + ye
5030
5031 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5032 lxc = _dlog(xc, xe, p+b+1)
5033
5034 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5035 shift = ye-b
5036 if shift >= 0:
5037 pc = lxc*yc*10**shift
5038 else:
5039 pc = _div_nearest(lxc*yc, 10**-shift)
5040
5041 if pc == 0:
5042 # we prefer a result that isn't exactly 1; this makes it
5043 # easier to compute a correctly rounded result in __pow__
5044 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5045 coeff, exp = 10**(p-1)+1, 1-p
5046 else:
5047 coeff, exp = 10**p-1, -p
5048 else:
5049 coeff, exp = _dexp(pc, -(p+1), p+1)
5050 coeff = _div_nearest(coeff, 10)
5051 exp += 1
5052
5053 return coeff, exp
5054
5055def _log10_lb(c, correction = {
5056 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5057 '6': 23, '7': 16, '8': 10, '9': 5}):
5058 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5059 if c <= 0:
5060 raise ValueError("The argument to _log10_lb should be nonnegative.")
5061 str_c = str(c)
5062 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005063
Guido van Rossumd8faa362007-04-27 19:54:29 +00005064##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005065
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005066def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005067 """Convert other to Decimal.
5068
5069 Verifies that it's ok to use in an implicit construction.
5070 """
5071 if isinstance(other, Decimal):
5072 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005073 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005074 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005075 if raiseit:
5076 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005077 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005078
Guido van Rossumd8faa362007-04-27 19:54:29 +00005079##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005080
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005081# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005082# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005083
5084DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005085 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005086 traps=[DivisionByZero, Overflow, InvalidOperation],
5087 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005088 Emax=999999999,
5089 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005090 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005091)
5092
5093# Pre-made alternate contexts offered by the specification
5094# Don't change these; the user should be able to select these
5095# contexts and be able to reproduce results from other implementations
5096# of the spec.
5097
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005098BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005099 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005100 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5101 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005102)
5103
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005104ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005105 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005106 traps=[],
5107 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005108)
5109
5110
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005111##### crud for parsing strings #############################################
5112import re
5113
5114# Regular expression used for parsing numeric strings. Additional
5115# comments:
5116#
5117# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5118# whitespace. But note that the specification disallows whitespace in
5119# a numeric string.
5120#
5121# 2. For finite numbers (not infinities and NaNs) the body of the
5122# number between the optional sign and the optional exponent must have
5123# at least one decimal digit, possibly after the decimal point. The
5124# lookahead expression '(?=\d|\.\d)' checks this.
5125#
5126# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5127# other meaning for \d than the numbers [0-9].
5128
5129import re
5130_parser = re.compile(r""" # A numeric string consists of:
5131# \s*
5132 (?P<sign>[-+])? # an optional sign, followed by either...
5133 (
5134 (?=\d|\.\d) # ...a number (with at least one digit)
5135 (?P<int>\d*) # consisting of a (possibly empty) integer part
5136 (\.(?P<frac>\d*))? # followed by an optional fractional part
5137 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5138 |
5139 Inf(inity)? # ...an infinity, or...
5140 |
5141 (?P<signal>s)? # ...an (optionally signaling)
5142 NaN # NaN
5143 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5144 )
5145# \s*
5146 $
5147""", re.VERBOSE | re.IGNORECASE).match
5148
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005149_all_zeros = re.compile('0*$').match
5150_exact_half = re.compile('50*$').match
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005151del re
5152
5153
Guido van Rossumd8faa362007-04-27 19:54:29 +00005154##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005155
Guido van Rossumd8faa362007-04-27 19:54:29 +00005156# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005157Inf = Decimal('Inf')
5158negInf = Decimal('-Inf')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005159NaN = Decimal('NaN')
5160Dec_0 = Decimal(0)
5161Dec_p1 = Decimal(1)
5162Dec_n1 = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005163
Guido van Rossumd8faa362007-04-27 19:54:29 +00005164# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005165Infsign = (Inf, negInf)
5166
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005167
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005168
5169if __name__ == '__main__':
5170 import doctest, sys
5171 doctest.testmod(sys.modules[__name__])