blob: 2c97dbd0b325a3c6db84d6af3a0af60f0f06c09a [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
Raymond Hettingereb260842005-06-07 18:52:34 +0000137import copy as _copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000138
Guido van Rossumd8faa362007-04-27 19:54:29 +0000139# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000140ROUND_DOWN = 'ROUND_DOWN'
141ROUND_HALF_UP = 'ROUND_HALF_UP'
142ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
143ROUND_CEILING = 'ROUND_CEILING'
144ROUND_FLOOR = 'ROUND_FLOOR'
145ROUND_UP = 'ROUND_UP'
146ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000147ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000148
Guido van Rossumd8faa362007-04-27 19:54:29 +0000149# Rounding decision (not part of the public API)
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000150NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY
151ALWAYS_ROUND = 'ALWAYS_ROUND' # Every operation rounds at end.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000152
Guido van Rossumd8faa362007-04-27 19:54:29 +0000153# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000154
155class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000156 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000157
158 Used exceptions derive from this.
159 If an exception derives from another exception besides this (such as
160 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
161 called if the others are present. This isn't actually used for
162 anything, though.
163
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000164 handle -- Called when context._raise_error is called and the
165 trap_enabler is set. First argument is self, second is the
166 context. More arguments can be given, those being after
167 the explanation in _raise_error (For example,
168 context._raise_error(NewError, '(-x)!', self._sign) would
169 call NewError().handle(context, self._sign).)
170
171 To define a new exception, it should be sufficient to have it derive
172 from DecimalException.
173 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000174 def handle(self, context, *args):
175 pass
176
177
178class Clamped(DecimalException):
179 """Exponent of a 0 changed to fit bounds.
180
181 This occurs and signals clamped if the exponent of a result has been
182 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000183 representation. This may occur when the exponent of a zero result would
184 be outside the bounds of a representation, or when a large normal
185 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000186 this latter case, the exponent is reduced to fit and the corresponding
187 number of zero digits are appended to the coefficient ("fold-down").
188 """
189
190
191class InvalidOperation(DecimalException):
192 """An invalid operation was performed.
193
194 Various bad things cause this:
195
196 Something creates a signaling NaN
197 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000198 0 * (+-)INF
199 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000200 x % 0
201 (+-)INF % x
202 x._rescale( non-integer )
203 sqrt(-x) , x > 0
204 0 ** 0
205 x ** (non-integer)
206 x ** (+-)INF
207 An operand is invalid
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000208
209 The result of the operation after these is a quiet positive NaN,
210 except when the cause is a signaling NaN, in which case the result is
211 also a quiet NaN, but with the original sign, and an optional
212 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000213 """
214 def handle(self, context, *args):
215 if args:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000216 if args[0] == 1: # sNaN, must drop 's' but keep diagnostics
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000217 ans = _dec_from_triple(args[1]._sign, args[1]._int, 'n', True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000218 return ans._fix_nan(context)
219 elif args[0] == 2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000220 return _dec_from_triple(args[1], args[2], 'n', True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000221 return NaN
222
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000223
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000224class ConversionSyntax(InvalidOperation):
225 """Trying to convert badly formed string.
226
227 This occurs and signals invalid-operation if an string is being
228 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000229 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000230 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000231 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000232 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000233
234class DivisionByZero(DecimalException, ZeroDivisionError):
235 """Division by 0.
236
237 This occurs and signals division-by-zero if division of a finite number
238 by zero was attempted (during a divide-integer or divide operation, or a
239 power operation with negative right-hand operand), and the dividend was
240 not zero.
241
242 The result of the operation is [sign,inf], where sign is the exclusive
243 or of the signs of the operands for divide, or is 1 for an odd power of
244 -0, for power.
245 """
246
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000247 def handle(self, context, sign, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000248 return Infsign[sign]
249
250class DivisionImpossible(InvalidOperation):
251 """Cannot perform the division adequately.
252
253 This occurs and signals invalid-operation if the integer result of a
254 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000255 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000256 """
257
258 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000259 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000260
261class DivisionUndefined(InvalidOperation, ZeroDivisionError):
262 """Undefined result of division.
263
264 This occurs and signals invalid-operation if division by zero was
265 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000266 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000267 """
268
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000269 def handle(self, context, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000270 return NaN
271
272class Inexact(DecimalException):
273 """Had to round, losing information.
274
275 This occurs and signals inexact whenever the result of an operation is
276 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000277 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000278 result in all cases is unchanged.
279
280 The inexact signal may be tested (or trapped) to determine if a given
281 operation (or sequence of operations) was inexact.
282 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000283 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000284
285class InvalidContext(InvalidOperation):
286 """Invalid context. Unknown rounding, for example.
287
288 This occurs and signals invalid-operation if an invalid context was
Guido van Rossumd8faa362007-04-27 19:54:29 +0000289 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000290 on creation and either the precision exceeds the capability of the
291 underlying concrete representation or an unknown or unsupported rounding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000292 was specified. These aspects of the context need only be checked when
293 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000294 """
295
296 def handle(self, context, *args):
297 return NaN
298
299class Rounded(DecimalException):
300 """Number got rounded (not necessarily changed during rounding).
301
302 This occurs and signals rounded whenever the result of an operation is
303 rounded (that is, some zero or non-zero digits were discarded from the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000304 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000305 result in all cases is unchanged.
306
307 The rounded signal may be tested (or trapped) to determine if a given
308 operation (or sequence of operations) caused a loss of precision.
309 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000310 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000311
312class Subnormal(DecimalException):
313 """Exponent < Emin before rounding.
314
315 This occurs and signals subnormal whenever the result of a conversion or
316 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000317 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000318
319 The subnormal signal may be tested (or trapped) to determine if a given
320 or operation (or sequence of operations) yielded a subnormal result.
321 """
322 pass
323
324class Overflow(Inexact, Rounded):
325 """Numerical overflow.
326
327 This occurs and signals overflow if the adjusted exponent of a result
328 (from a conversion or from an operation that is not an attempt to divide
329 by zero), after rounding, would be greater than the largest value that
330 can be handled by the implementation (the value Emax).
331
332 The result depends on the rounding mode:
333
334 For round-half-up and round-half-even (and for round-half-down and
335 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000336 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000338 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000339 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000340 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000341 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000342 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000343 will also be raised.
344 """
345
346 def handle(self, context, sign, *args):
347 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000348 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000349 return Infsign[sign]
350 if sign == 0:
351 if context.rounding == ROUND_CEILING:
352 return Infsign[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000353 return _dec_from_triple(sign, '9'*context.prec,
354 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000355 if sign == 1:
356 if context.rounding == ROUND_FLOOR:
357 return Infsign[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000358 return _dec_from_triple(sign, '9'*context.prec,
359 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000360
361
362class Underflow(Inexact, Rounded, Subnormal):
363 """Numerical underflow with result rounded to 0.
364
365 This occurs and signals underflow if a result is inexact and the
366 adjusted exponent of the result would be smaller (more negative) than
367 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000368 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000369
370 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000371 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000372 in 0 with the sign of the intermediate result and an exponent of Etiny.
373
374 In all cases, Inexact, Rounded, and Subnormal will also be raised.
375 """
376
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000377# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000378_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000379 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000380
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000381# Map conditions (per the spec) to signals
382_condition_map = {ConversionSyntax:InvalidOperation,
383 DivisionImpossible:InvalidOperation,
384 DivisionUndefined:InvalidOperation,
385 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000386
Guido van Rossumd8faa362007-04-27 19:54:29 +0000387##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000388
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000389# The getcontext() and setcontext() function manage access to a thread-local
390# current context. Py2.4 offers direct support for thread locals. If that
391# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000392# work for older Pythons. If threads are not part of the build, create a
393# mock threading object with threading.local() returning the module namespace.
394
395try:
396 import threading
397except ImportError:
398 # Python was compiled without threads; create a mock object instead
399 import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +0000400 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000401 def local(self, sys=sys):
402 return sys.modules[__name__]
403 threading = MockThreading()
404 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000405
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000406try:
407 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000408
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000409except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000410
Guido van Rossumd8faa362007-04-27 19:54:29 +0000411 # To fix reloading, force it to create a new context
412 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000413 if hasattr(threading.currentThread(), '__decimal_context__'):
414 del threading.currentThread().__decimal_context__
415
416 def setcontext(context):
417 """Set this thread's context to context."""
418 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000419 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000420 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000421 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000422
423 def getcontext():
424 """Returns this thread's context.
425
426 If this thread does not yet have a context, returns
427 a new context and sets this thread's context.
428 New contexts are copies of DefaultContext.
429 """
430 try:
431 return threading.currentThread().__decimal_context__
432 except AttributeError:
433 context = Context()
434 threading.currentThread().__decimal_context__ = context
435 return context
436
437else:
438
439 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000440 if hasattr(local, '__decimal_context__'):
441 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000442
443 def getcontext(_local=local):
444 """Returns this thread's context.
445
446 If this thread does not yet have a context, returns
447 a new context and sets this thread's context.
448 New contexts are copies of DefaultContext.
449 """
450 try:
451 return _local.__decimal_context__
452 except AttributeError:
453 context = Context()
454 _local.__decimal_context__ = context
455 return context
456
457 def setcontext(context, _local=local):
458 """Set this thread's context to context."""
459 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000460 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000461 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000462 _local.__decimal_context__ = context
463
464 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000465
Thomas Wouters89f507f2006-12-13 04:49:30 +0000466def localcontext(ctx=None):
467 """Return a context manager for a copy of the supplied context
468
469 Uses a copy of the current context if no context is specified
470 The returned context manager creates a local decimal context
471 in a with statement:
472 def sin(x):
473 with localcontext() as ctx:
474 ctx.prec += 2
475 # Rest of sin calculation algorithm
476 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000477 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000478
479 def sin(x):
480 with localcontext(ExtendedContext):
481 # Rest of sin calculation algorithm
482 # uses the Extended Context from the
483 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000484 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000485
486 """
487 # The string below can't be included in the docstring until Python 2.6
488 # as the doctest module doesn't understand __future__ statements
489 """
490 >>> from __future__ import with_statement
Guido van Rossum7131f842007-02-09 20:13:25 +0000491 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000492 28
493 >>> with localcontext():
494 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000495 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000496 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000497 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000498 30
499 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000500 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000501 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000502 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000503 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000504 28
505 """
506 if ctx is None: ctx = getcontext()
507 return _ContextManager(ctx)
508
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000509
Guido van Rossumd8faa362007-04-27 19:54:29 +0000510##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000511
512class Decimal(object):
513 """Floating point class for decimal arithmetic."""
514
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000515 __slots__ = ('_exp','_int','_sign', '_is_special')
516 # Generally, the value of the Decimal instance is given by
517 # (-1)**_sign * _int * 10**_exp
518 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000519
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000520 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000521 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000522 """Create a decimal point instance.
523
524 >>> Decimal('3.14') # string input
525 Decimal("3.14")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000526 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000527 Decimal("3.14")
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000528 >>> Decimal(314) # int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000529 Decimal("314")
530 >>> Decimal(Decimal(314)) # another decimal instance
531 Decimal("314")
532 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000533
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000534 # Note that the coefficient, self._int, is actually stored as
535 # a string rather than as a tuple of digits. This speeds up
536 # the "digits to integer" and "integer to digits" conversions
537 # that are used in almost every arithmetic operation on
538 # Decimals. This is an internal detail: the as_tuple function
539 # and the Decimal constructor still deal with tuples of
540 # digits.
541
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000542 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000543
Christian Heimesd59c64c2007-11-30 19:27:20 +0000544 # From a string
545 # REs insist on real strings, so we can too.
546 if isinstance(value, str):
547 m = _parser(value)
548 if m is None:
549 if context is None:
550 context = getcontext()
551 return context._raise_error(ConversionSyntax,
552 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000553
Christian Heimesd59c64c2007-11-30 19:27:20 +0000554 if m.group('sign') == "-":
555 self._sign = 1
556 else:
557 self._sign = 0
558 intpart = m.group('int')
559 if intpart is not None:
560 # finite number
561 fracpart = m.group('frac')
562 exp = int(m.group('exp') or '0')
563 if fracpart is not None:
564 self._int = (intpart+fracpart).lstrip('0') or '0'
565 self._exp = exp - len(fracpart)
566 else:
567 self._int = intpart.lstrip('0') or '0'
568 self._exp = exp
569 self._is_special = False
570 else:
571 diag = m.group('diag')
572 if diag is not None:
573 # NaN
574 self._int = diag.lstrip('0')
575 if m.group('signal'):
576 self._exp = 'N'
577 else:
578 self._exp = 'n'
579 else:
580 # infinity
581 self._int = '0'
582 self._exp = 'F'
583 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000584 return self
585
586 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000587 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000588 if value >= 0:
589 self._sign = 0
590 else:
591 self._sign = 1
592 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000593 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000594 self._is_special = False
595 return self
596
597 # From another decimal
598 if isinstance(value, Decimal):
599 self._exp = value._exp
600 self._sign = value._sign
601 self._int = value._int
602 self._is_special = value._is_special
603 return self
604
605 # From an internal working value
606 if isinstance(value, _WorkRep):
607 self._sign = value.sign
608 self._int = str(value.int)
609 self._exp = int(value.exp)
610 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000611 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000612
613 # tuple/list conversion (possibly from as_tuple())
614 if isinstance(value, (list,tuple)):
615 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000616 raise ValueError('Invalid tuple size in creation of Decimal '
617 'from list or tuple. The list or tuple '
618 'should have exactly three elements.')
619 # process sign. The isinstance test rejects floats
620 if not (isinstance(value[0], int) and value[0] in (0,1)):
621 raise ValueError("Invalid sign. The first value in the tuple "
622 "should be an integer; either 0 for a "
623 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000624 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000625 if value[2] == 'F':
626 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000627 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000628 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000629 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000630 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000631 # process and validate the digits in value[1]
632 digits = []
633 for digit in value[1]:
634 if isinstance(digit, int) and 0 <= digit <= 9:
635 # skip leading zeros
636 if digits or digit != 0:
637 digits.append(digit)
638 else:
639 raise ValueError("The second value in the tuple must "
640 "be composed of integers in the range "
641 "0 through 9.")
642 if value[2] in ('n', 'N'):
643 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000644 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000645 self._exp = value[2]
646 self._is_special = True
647 elif isinstance(value[2], int):
648 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000649 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000650 self._exp = value[2]
651 self._is_special = False
652 else:
653 raise ValueError("The third value in the tuple must "
654 "be an integer, or one of the "
655 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000656 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000657
Raymond Hettingerbf440692004-07-10 14:14:37 +0000658 if isinstance(value, float):
659 raise TypeError("Cannot convert float to Decimal. " +
660 "First convert the float to a string")
661
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000662 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000663
664 def _isnan(self):
665 """Returns whether the number is not actually one.
666
667 0 if a number
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000668 1 if NaN (it could be a normal quiet NaN or a phantom one)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000669 2 if sNaN
670 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000671 if self._is_special:
672 exp = self._exp
673 if exp == 'n':
674 return 1
675 elif exp == 'N':
676 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000677 return 0
678
679 def _isinfinity(self):
680 """Returns whether the number is infinite
681
682 0 if finite or not a number
683 1 if +INF
684 -1 if -INF
685 """
686 if self._exp == 'F':
687 if self._sign:
688 return -1
689 return 1
690 return 0
691
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000692 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000693 """Returns whether the number is not actually one.
694
695 if self, other are sNaN, signal
696 if self, other are NaN return nan
697 return 0
698
699 Done before operations.
700 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000701
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000702 self_is_nan = self._isnan()
703 if other is None:
704 other_is_nan = False
705 else:
706 other_is_nan = other._isnan()
707
708 if self_is_nan or other_is_nan:
709 if context is None:
710 context = getcontext()
711
712 if self_is_nan == 2:
713 return context._raise_error(InvalidOperation, 'sNaN',
714 1, self)
715 if other_is_nan == 2:
716 return context._raise_error(InvalidOperation, 'sNaN',
717 1, other)
718 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000719 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000720
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000721 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000722 return 0
723
Jack Diederich4dafcc42006-11-28 19:15:13 +0000724 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000725 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000726
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000727 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000728 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000729 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000730
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000731 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000732 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000733 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000734 # Never return NotImplemented
735 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000736
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000737 if self._is_special or other._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000738 # check for nans, without raising on a signaling nan
739 if self._isnan() or other._isnan():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000740 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000741
742 # INF = INF
743 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000744
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000745 # check for zeros; note that cmp(0, -0) should return 0
746 if not self:
747 if not other:
748 return 0
749 else:
750 return -((-1)**other._sign)
751 if not other:
752 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000753
Guido van Rossumd8faa362007-04-27 19:54:29 +0000754 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000755 if other._sign < self._sign:
756 return -1
757 if self._sign < other._sign:
758 return 1
759
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000760 self_adjusted = self.adjusted()
761 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000762 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000763 self_padded = self._int + '0'*(self._exp - other._exp)
764 other_padded = other._int + '0'*(other._exp - self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000765 return cmp(self_padded, other_padded) * (-1)**self._sign
766 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000767 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000768 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000769 return -((-1)**self._sign)
770
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000771 def __eq__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000772 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000773 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000774 return self.__cmp__(other) == 0
775
776 def __ne__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000777 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000778 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000779 return self.__cmp__(other) != 0
780
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000781 def __lt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000782 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000783 return NotImplemented
784 return self.__cmp__(other) < 0
785
786 def __le__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000787 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000788 return NotImplemented
789 return self.__cmp__(other) <= 0
790
791 def __gt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000792 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000793 return NotImplemented
794 return self.__cmp__(other) > 0
795
796 def __ge__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000797 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000798 return NotImplemented
799 return self.__cmp__(other) >= 0
800
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000801 def compare(self, other, context=None):
802 """Compares one to another.
803
804 -1 => a < b
805 0 => a = b
806 1 => a > b
807 NaN => one is NaN
808 Like __cmp__, but returns Decimal instances.
809 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000810 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000811
Guido van Rossumd8faa362007-04-27 19:54:29 +0000812 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000813 if (self._is_special or other and other._is_special):
814 ans = self._check_nans(other, context)
815 if ans:
816 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000817
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000818 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000819
820 def __hash__(self):
821 """x.__hash__() <==> hash(x)"""
822 # Decimal integers must hash the same as the ints
823 # Non-integer decimals are normalized and hashed as strings
Thomas Wouters477c8d52006-05-27 19:21:47 +0000824 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000825 if self._is_special:
826 if self._isnan():
827 raise TypeError('Cannot hash a NaN value.')
828 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000829 if not self:
830 return 0
831 if self._isinteger():
832 op = _WorkRep(self.to_integral_value())
833 # to make computation feasible for Decimals with large
834 # exponent, we use the fact that hash(n) == hash(m) for
835 # any two nonzero integers n and m such that (i) n and m
836 # have the same sign, and (ii) n is congruent to m modulo
837 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
838 # hash((-1)**s*c*pow(10, e, 2**64-1).
839 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000840 return hash(str(self.normalize()))
841
842 def as_tuple(self):
843 """Represents the number as a triple tuple.
844
845 To show the internals exactly as they are.
846 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000847 return (self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000848
849 def __repr__(self):
850 """Represents the number as an instance of Decimal."""
851 # Invariant: eval(repr(d)) == d
852 return 'Decimal("%s")' % str(self)
853
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000854 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000855 """Return string representation of the number in scientific notation.
856
857 Captures all of the information in the underlying representation.
858 """
859
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000860 if self._is_special:
861 if self._isnan():
862 minus = '-'*self._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000863 if self._int == '0':
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000864 info = ''
865 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000866 info = self._int
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000867 if self._isnan() == 2:
868 return minus + 'sNaN' + info
869 return minus + 'NaN' + info
870 if self._isinfinity():
871 minus = '-'*self._sign
872 return minus + 'Infinity'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000873
874 if context is None:
875 context = getcontext()
876
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000877 tmp = list(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000878 numdigits = len(self._int)
879 leftdigits = self._exp + numdigits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000880 if eng and not self: # self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
881 if self._exp < 0 and self._exp >= -6: # short, no need for e/E
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000882 s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
883 return s
Guido van Rossumd8faa362007-04-27 19:54:29 +0000884 # exp is closest mult. of 3 >= self._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000885 exp = ((self._exp - 1)// 3 + 1) * 3
886 if exp != self._exp:
887 s = '0.'+'0'*(exp - self._exp)
888 else:
889 s = '0'
890 if exp != 0:
891 if context.capitals:
892 s += 'E'
893 else:
894 s += 'e'
895 if exp > 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000896 s += '+' # 0.0e+3, not 0.0e3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000897 s += str(exp)
898 s = '-'*self._sign + s
899 return s
900 if eng:
901 dotplace = (leftdigits-1)%3+1
902 adjexp = leftdigits -1 - (leftdigits-1)%3
903 else:
904 adjexp = leftdigits-1
905 dotplace = 1
906 if self._exp == 0:
907 pass
908 elif self._exp < 0 and adjexp >= 0:
909 tmp.insert(leftdigits, '.')
910 elif self._exp < 0 and adjexp >= -6:
911 tmp[0:0] = ['0'] * int(-leftdigits)
912 tmp.insert(0, '0.')
913 else:
914 if numdigits > dotplace:
915 tmp.insert(dotplace, '.')
916 elif numdigits < dotplace:
917 tmp.extend(['0']*(dotplace-numdigits))
918 if adjexp:
919 if not context.capitals:
920 tmp.append('e')
921 else:
922 tmp.append('E')
923 if adjexp > 0:
924 tmp.append('+')
925 tmp.append(str(adjexp))
926 if eng:
927 while tmp[0:1] == ['0']:
928 tmp[0:1] = []
929 if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
930 tmp[0:0] = ['0']
931 if self._sign:
932 tmp.insert(0, '-')
933
934 return ''.join(tmp)
935
936 def to_eng_string(self, context=None):
937 """Convert to engineering-type string.
938
939 Engineering notation has an exponent which is a multiple of 3, so there
940 are up to 3 digits left of the decimal place.
941
942 Same rules for when in exponential and when as a value as in __str__.
943 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000944 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000945
946 def __neg__(self, context=None):
947 """Returns a copy with the sign switched.
948
949 Rounds, if it has reason.
950 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000951 if self._is_special:
952 ans = self._check_nans(context=context)
953 if ans:
954 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000955
956 if not self:
957 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000958 ans = self.copy_sign(Dec_0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000959 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000960 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000961
962 if context is None:
963 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000964 if context._rounding_decision == ALWAYS_ROUND:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000965 return ans._fix(context)
966 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000967
968 def __pos__(self, context=None):
969 """Returns a copy, unless it is a sNaN.
970
971 Rounds the number (if more then precision digits)
972 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000973 if self._is_special:
974 ans = self._check_nans(context=context)
975 if ans:
976 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000977
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000978 if not self:
979 # + (-0) = 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000980 ans = self.copy_sign(Dec_0)
981 else:
982 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000983
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000984 if context is None:
985 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000986 if context._rounding_decision == ALWAYS_ROUND:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000987 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000988 return ans
989
990 def __abs__(self, round=1, context=None):
991 """Returns the absolute value of self.
992
993 If the second argument is 0, do not round.
994 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000995 if self._is_special:
996 ans = self._check_nans(context=context)
997 if ans:
998 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000999
1000 if not round:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001001 if context is None:
1002 context = getcontext()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00001003 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001004 context._set_rounding_decision(NEVER_ROUND)
1005
1006 if self._sign:
1007 ans = self.__neg__(context=context)
1008 else:
1009 ans = self.__pos__(context=context)
1010
1011 return ans
1012
1013 def __add__(self, other, context=None):
1014 """Returns self + other.
1015
1016 -INF + INF (or the reverse) cause InvalidOperation errors.
1017 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001018 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001019 if other is NotImplemented:
1020 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001021
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001022 if context is None:
1023 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001024
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001025 if self._is_special or other._is_special:
1026 ans = self._check_nans(other, context)
1027 if ans:
1028 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001029
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001030 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001031 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001032 if self._sign != other._sign and other._isinfinity():
1033 return context._raise_error(InvalidOperation, '-INF + INF')
1034 return Decimal(self)
1035 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001036 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001037
1038 shouldround = context._rounding_decision == ALWAYS_ROUND
1039
1040 exp = min(self._exp, other._exp)
1041 negativezero = 0
1042 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001043 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001044 negativezero = 1
1045
1046 if not self and not other:
1047 sign = min(self._sign, other._sign)
1048 if negativezero:
1049 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001050 ans = _dec_from_triple(sign, '0', exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001051 if shouldround:
1052 ans = ans._fix(context)
1053 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001054 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001055 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001056 ans = other._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001057 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001058 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001059 return ans
1060 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001061 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001062 ans = self._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001063 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001064 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001065 return ans
1066
1067 op1 = _WorkRep(self)
1068 op2 = _WorkRep(other)
1069 op1, op2 = _normalize(op1, op2, shouldround, context.prec)
1070
1071 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001072 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001073 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001074 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001075 ans = _dec_from_triple(negativezero, '0', exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001076 if shouldround:
1077 ans = ans._fix(context)
1078 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001079 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001080 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001081 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001082 if op1.sign == 1:
1083 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001084 op1.sign, op2.sign = op2.sign, op1.sign
1085 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001086 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001087 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001088 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001089 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001090 op1.sign, op2.sign = (0, 0)
1091 else:
1092 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001093 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001094
Raymond Hettinger17931de2004-10-27 06:21:46 +00001095 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001096 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001097 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001098 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001099
1100 result.exp = op1.exp
1101 ans = Decimal(result)
1102 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001103 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001104 return ans
1105
1106 __radd__ = __add__
1107
1108 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001109 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001110 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001111 if other is NotImplemented:
1112 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001113
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001114 if self._is_special or other._is_special:
1115 ans = self._check_nans(other, context=context)
1116 if ans:
1117 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001118
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001119 # self - other is computed as self + other.copy_negate()
1120 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001121
1122 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001123 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001124 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001125 if other is NotImplemented:
1126 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001127
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001128 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001129
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001130 def _increment(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001131 """Special case of add, adding 1eExponent
1132
1133 Since it is common, (rounding, for example) this adds
1134 (sign)*one E self._exp to the number more efficiently than add.
1135
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136 Assumes that self is nonspecial.
1137
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001138 For example:
1139 Decimal('5.624e10')._increment() == Decimal('5.625e10')
1140 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001141 L = list(map(int, self._int))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001142 L[-1] += 1
1143 spot = len(L)-1
1144 while L[spot] == 10:
1145 L[spot] = 0
1146 if spot == 0:
1147 L[0:0] = [1]
1148 break
1149 L[spot-1] += 1
1150 spot -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001151 return _dec_from_triple(self._sign, "".join(map(str, L)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001152
1153 def __mul__(self, other, context=None):
1154 """Return self * other.
1155
1156 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1157 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001158 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001159 if other is NotImplemented:
1160 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001161
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001162 if context is None:
1163 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001164
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001165 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001166
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001167 if self._is_special or other._is_special:
1168 ans = self._check_nans(other, context)
1169 if ans:
1170 return ans
1171
1172 if self._isinfinity():
1173 if not other:
1174 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1175 return Infsign[resultsign]
1176
1177 if other._isinfinity():
1178 if not self:
1179 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1180 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001181
1182 resultexp = self._exp + other._exp
1183 shouldround = context._rounding_decision == ALWAYS_ROUND
1184
1185 # Special case for multiplying by zero
1186 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001187 ans = _dec_from_triple(resultsign, '0', resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001188 if shouldround:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001189 # Fixing in case the exponent is out of bounds
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001190 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001191 return ans
1192
1193 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001194 if self._int == '1':
1195 ans = _dec_from_triple(resultsign, other._int, resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001196 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001197 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001198 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001199 if other._int == '1':
1200 ans = _dec_from_triple(resultsign, self._int, resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001201 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001202 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001203 return ans
1204
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001205 op1 = _WorkRep(self)
1206 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001207
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001208 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001209 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001210 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001211
1212 return ans
1213 __rmul__ = __mul__
1214
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001215 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001216 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001217 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001218 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001219 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001220
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001221 if context is None:
1222 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001223
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001224 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001225
1226 if self._is_special or other._is_special:
1227 ans = self._check_nans(other, context)
1228 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001229 return ans
1230
1231 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001232 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001233
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001234 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001235 return Infsign[sign]
1236
1237 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001238 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001239 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001240
1241 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001242 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001243 if not self:
1244 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001245 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001246
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001247 if not self:
1248 exp = self._exp - other._exp
1249 coeff = 0
1250 else:
1251 # OK, so neither = 0, INF or NaN
1252 shift = len(other._int) - len(self._int) + context.prec + 1
1253 exp = self._exp - other._exp - shift
1254 op1 = _WorkRep(self)
1255 op2 = _WorkRep(other)
1256 if shift >= 0:
1257 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1258 else:
1259 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1260 if remainder:
1261 # result is not exact; adjust to ensure correct rounding
1262 if coeff % 5 == 0:
1263 coeff += 1
1264 else:
1265 # result is exact; get as close to ideal exponent as possible
1266 ideal_exp = self._exp - other._exp
1267 while exp < ideal_exp and coeff % 10 == 0:
1268 coeff //= 10
1269 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001270
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001271 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001272 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001273
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001274 def _divide(self, other, context):
1275 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001276
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001277 Assumes that neither self nor other is a NaN, that self is not
1278 infinite and that other is nonzero.
1279 """
1280 sign = self._sign ^ other._sign
1281 if other._isinfinity():
1282 ideal_exp = self._exp
1283 else:
1284 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001285
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001286 expdiff = self.adjusted() - other.adjusted()
1287 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001288 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001289 self._rescale(ideal_exp, context.rounding))
1290 if expdiff <= context.prec:
1291 op1 = _WorkRep(self)
1292 op2 = _WorkRep(other)
1293 if op1.exp >= op2.exp:
1294 op1.int *= 10**(op1.exp - op2.exp)
1295 else:
1296 op2.int *= 10**(op2.exp - op1.exp)
1297 q, r = divmod(op1.int, op2.int)
1298 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001299 return (_dec_from_triple(sign, str(q), 0),
1300 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001301
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001302 # Here the quotient is too large to be representable
1303 ans = context._raise_error(DivisionImpossible,
1304 'quotient too large in //, % or divmod')
1305 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001306
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001307 def __rtruediv__(self, other, context=None):
1308 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001309 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001310 if other is NotImplemented:
1311 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001312 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001313
1314 def __divmod__(self, other, context=None):
1315 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001316 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001317 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001318 other = _convert_other(other)
1319 if other is NotImplemented:
1320 return other
1321
1322 if context is None:
1323 context = getcontext()
1324
1325 ans = self._check_nans(other, context)
1326 if ans:
1327 return (ans, ans)
1328
1329 sign = self._sign ^ other._sign
1330 if self._isinfinity():
1331 if other._isinfinity():
1332 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1333 return ans, ans
1334 else:
1335 return (Infsign[sign],
1336 context._raise_error(InvalidOperation, 'INF % x'))
1337
1338 if not other:
1339 if not self:
1340 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1341 return ans, ans
1342 else:
1343 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1344 context._raise_error(InvalidOperation, 'x % 0'))
1345
1346 quotient, remainder = self._divide(other, context)
1347 if context._rounding_decision == ALWAYS_ROUND:
1348 remainder = remainder._fix(context)
1349 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001350
1351 def __rdivmod__(self, other, context=None):
1352 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001353 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001354 if other is NotImplemented:
1355 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001356 return other.__divmod__(self, context=context)
1357
1358 def __mod__(self, other, context=None):
1359 """
1360 self % other
1361 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001362 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001363 if other is NotImplemented:
1364 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001365
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001366 if context is None:
1367 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001368
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001369 ans = self._check_nans(other, context)
1370 if ans:
1371 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001372
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001373 if self._isinfinity():
1374 return context._raise_error(InvalidOperation, 'INF % x')
1375 elif not other:
1376 if self:
1377 return context._raise_error(InvalidOperation, 'x % 0')
1378 else:
1379 return context._raise_error(DivisionUndefined, '0 % 0')
1380
1381 remainder = self._divide(other, context)[1]
1382 if context._rounding_decision == ALWAYS_ROUND:
1383 remainder = remainder._fix(context)
1384 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001385
1386 def __rmod__(self, other, context=None):
1387 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001388 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001389 if other is NotImplemented:
1390 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001391 return other.__mod__(self, context=context)
1392
1393 def remainder_near(self, other, context=None):
1394 """
1395 Remainder nearest to 0- abs(remainder-near) <= other/2
1396 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001397 if context is None:
1398 context = getcontext()
1399
1400 other = _convert_other(other, raiseit=True)
1401
1402 ans = self._check_nans(other, context)
1403 if ans:
1404 return ans
1405
1406 # self == +/-infinity -> InvalidOperation
1407 if self._isinfinity():
1408 return context._raise_error(InvalidOperation,
1409 'remainder_near(infinity, x)')
1410
1411 # other == 0 -> either InvalidOperation or DivisionUndefined
1412 if not other:
1413 if self:
1414 return context._raise_error(InvalidOperation,
1415 'remainder_near(x, 0)')
1416 else:
1417 return context._raise_error(DivisionUndefined,
1418 'remainder_near(0, 0)')
1419
1420 # other = +/-infinity -> remainder = self
1421 if other._isinfinity():
1422 ans = Decimal(self)
1423 return ans._fix(context)
1424
1425 # self = 0 -> remainder = self, with ideal exponent
1426 ideal_exponent = min(self._exp, other._exp)
1427 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001428 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001429 return ans._fix(context)
1430
1431 # catch most cases of large or small quotient
1432 expdiff = self.adjusted() - other.adjusted()
1433 if expdiff >= context.prec + 1:
1434 # expdiff >= prec+1 => abs(self/other) > 10**prec
1435 return context._raise_error(DivisionImpossible)
1436 if expdiff <= -2:
1437 # expdiff <= -2 => abs(self/other) < 0.1
1438 ans = self._rescale(ideal_exponent, context.rounding)
1439 return ans._fix(context)
1440
1441 # adjust both arguments to have the same exponent, then divide
1442 op1 = _WorkRep(self)
1443 op2 = _WorkRep(other)
1444 if op1.exp >= op2.exp:
1445 op1.int *= 10**(op1.exp - op2.exp)
1446 else:
1447 op2.int *= 10**(op2.exp - op1.exp)
1448 q, r = divmod(op1.int, op2.int)
1449 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1450 # 10**ideal_exponent. Apply correction to ensure that
1451 # abs(remainder) <= abs(other)/2
1452 if 2*r + (q&1) > op2.int:
1453 r -= op2.int
1454 q += 1
1455
1456 if q >= 10**context.prec:
1457 return context._raise_error(DivisionImpossible)
1458
1459 # result has same sign as self unless r is negative
1460 sign = self._sign
1461 if r < 0:
1462 sign = 1-sign
1463 r = -r
1464
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001465 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001466 return ans._fix(context)
1467
1468 def __floordiv__(self, other, context=None):
1469 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001470 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001471 if other is NotImplemented:
1472 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001473
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001474 if context is None:
1475 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001476
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001477 ans = self._check_nans(other, context)
1478 if ans:
1479 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001480
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001481 if self._isinfinity():
1482 if other._isinfinity():
1483 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001484 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001485 return Infsign[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001486
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001487 if not other:
1488 if self:
1489 return context._raise_error(DivisionByZero, 'x // 0',
1490 self._sign ^ other._sign)
1491 else:
1492 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001493
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001494 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001495
1496 def __rfloordiv__(self, other, context=None):
1497 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001498 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001499 if other is NotImplemented:
1500 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001501 return other.__floordiv__(self, context=context)
1502
1503 def __float__(self):
1504 """Float representation."""
1505 return float(str(self))
1506
1507 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001508 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001509 if self._is_special:
1510 if self._isnan():
1511 context = getcontext()
1512 return context._raise_error(InvalidContext)
1513 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001514 raise OverflowError("Cannot convert infinity to int")
1515 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001516 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001517 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001518 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001519 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001520
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001521 def _fix_nan(self, context):
1522 """Decapitate the payload of a NaN to fit the context"""
1523 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001524
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001525 # maximum length of payload is precision if _clamp=0,
1526 # precision-1 if _clamp=1.
1527 max_payload_len = context.prec - context._clamp
1528 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001529 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1530 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001531 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001532
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001533 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001534 """Round if it is necessary to keep self within prec precision.
1535
1536 Rounds and fixes the exponent. Does not raise on a sNaN.
1537
1538 Arguments:
1539 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001540 context - context used.
1541 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001542
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001543 if context is None:
1544 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001545
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001546 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001547 if self._isnan():
1548 # decapitate payload if necessary
1549 return self._fix_nan(context)
1550 else:
1551 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001552 return Decimal(self)
1553
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001554 # if self is zero then exponent should be between Etiny and
1555 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1556 Etiny = context.Etiny()
1557 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001558 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001559 exp_max = [context.Emax, Etop][context._clamp]
1560 new_exp = min(max(self._exp, Etiny), exp_max)
1561 if new_exp != self._exp:
1562 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001563 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001564 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001565 return Decimal(self)
1566
1567 # exp_min is the smallest allowable exponent of the result,
1568 # equal to max(self.adjusted()-context.prec+1, Etiny)
1569 exp_min = len(self._int) + self._exp - context.prec
1570 if exp_min > Etop:
1571 # overflow: exp_min > Etop iff self.adjusted() > Emax
1572 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001573 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001574 return context._raise_error(Overflow, 'above Emax', self._sign)
1575 self_is_subnormal = exp_min < Etiny
1576 if self_is_subnormal:
1577 context._raise_error(Subnormal)
1578 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001579
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001580 # round if self has too many digits
1581 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001582 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001583 ans = self._rescale(exp_min, context.rounding)
1584 if ans != self:
1585 context._raise_error(Inexact)
1586 if self_is_subnormal:
1587 context._raise_error(Underflow)
1588 if not ans:
1589 # raise Clamped on underflow to 0
1590 context._raise_error(Clamped)
1591 elif len(ans._int) == context.prec+1:
1592 # we get here only if rescaling rounds the
1593 # cofficient up to exactly 10**context.prec
1594 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001595 ans = _dec_from_triple(ans._sign,
1596 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001597 else:
1598 # Inexact and Rounded have already been raised
1599 ans = context._raise_error(Overflow, 'above Emax',
1600 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001601 return ans
1602
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001603 # fold down if _clamp == 1 and self has too few digits
1604 if context._clamp == 1 and self._exp > Etop:
1605 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001606 self_padded = self._int + '0'*(self._exp - Etop)
1607 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001608
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001609 # here self was representable to begin with; return unchanged
1610 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001611
1612 _pick_rounding_function = {}
1613
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001614 # for each of the rounding functions below:
1615 # self is a finite, nonzero Decimal
1616 # prec is an integer satisfying 0 <= prec < len(self._int)
1617 # the rounded result will have exponent self._exp + len(self._int) - prec;
1618
1619 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001620 """Also known as round-towards-0, truncate."""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001621 newexp = self._exp + len(self._int) - prec
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001622 return _dec_from_triple(self._sign, self._int[:prec] or '0', newexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001623
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001624 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001625 """Rounds away from 0."""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001626 newexp = self._exp + len(self._int) - prec
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001627 tmp = _dec_from_triple(self._sign, self._int[:prec] or '0', newexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001628 for digit in self._int[prec:]:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001629 if digit != '0':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001630 return tmp._increment()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001631 return tmp
1632
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001633 def _round_half_up(self, prec):
1634 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001635 if self._int[prec] in '56789':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001636 return self._round_up(prec)
1637 else:
1638 return self._round_down(prec)
1639
1640 def _round_half_down(self, prec):
1641 """Round 5 down"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001642 if self._int[prec] == '5':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001643 for digit in self._int[prec+1:]:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001644 if digit != '0':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001645 break
1646 else:
1647 return self._round_down(prec)
1648 return self._round_half_up(prec)
1649
1650 def _round_half_even(self, prec):
1651 """Round 5 to even, rest to nearest."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001652 if prec and self._int[prec-1] in '13579':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001653 return self._round_half_up(prec)
1654 else:
1655 return self._round_half_down(prec)
1656
1657 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001658 """Rounds up (not away from 0 if negative.)"""
1659 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001660 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001661 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001662 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001663
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001664 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001665 """Rounds down (not towards 0 if negative)"""
1666 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001667 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001668 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001669 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001670
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001671 def _round_05up(self, prec):
1672 """Round down unless digit prec-1 is 0 or 5."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001673 if prec == 0 or self._int[prec-1] in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001674 return self._round_up(prec)
1675 else:
1676 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001677
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001678 def fma(self, other, third, context=None):
1679 """Fused multiply-add.
1680
1681 Returns self*other+third with no rounding of the intermediate
1682 product self*other.
1683
1684 self and other are multiplied together, with no rounding of
1685 the result. The third operand is then added to the result,
1686 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001687 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001688
1689 other = _convert_other(other, raiseit=True)
1690 third = _convert_other(third, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001691
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001692 if context is None:
1693 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001694
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001695 # do self*other in fresh context with no traps and no rounding
1696 mul_context = Context(traps=[], flags=[],
1697 _rounding_decision=NEVER_ROUND)
1698 product = self.__mul__(other, mul_context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001699
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001700 if mul_context.flags[InvalidOperation]:
1701 # reraise in current context
1702 return context._raise_error(InvalidOperation,
1703 'invalid multiplication in fma',
1704 1, product)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001705
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001706 ans = product.__add__(third, context)
1707 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001708
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001709 def _power_modulo(self, other, modulo, context=None):
1710 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001711
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001712 # if can't convert other and modulo to Decimal, raise
1713 # TypeError; there's no point returning NotImplemented (no
1714 # equivalent of __rpow__ for three argument pow)
1715 other = _convert_other(other, raiseit=True)
1716 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001717
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001718 if context is None:
1719 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001720
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001721 # deal with NaNs: if there are any sNaNs then first one wins,
1722 # (i.e. behaviour for NaNs is identical to that of fma)
1723 self_is_nan = self._isnan()
1724 other_is_nan = other._isnan()
1725 modulo_is_nan = modulo._isnan()
1726 if self_is_nan or other_is_nan or modulo_is_nan:
1727 if self_is_nan == 2:
1728 return context._raise_error(InvalidOperation, 'sNaN',
1729 1, self)
1730 if other_is_nan == 2:
1731 return context._raise_error(InvalidOperation, 'sNaN',
1732 1, other)
1733 if modulo_is_nan == 2:
1734 return context._raise_error(InvalidOperation, 'sNaN',
1735 1, modulo)
1736 if self_is_nan:
1737 return self._fix_nan(context)
1738 if other_is_nan:
1739 return other._fix_nan(context)
1740 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001741
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001742 # check inputs: we apply same restrictions as Python's pow()
1743 if not (self._isinteger() and
1744 other._isinteger() and
1745 modulo._isinteger()):
1746 return context._raise_error(InvalidOperation,
1747 'pow() 3rd argument not allowed '
1748 'unless all arguments are integers')
1749 if other < 0:
1750 return context._raise_error(InvalidOperation,
1751 'pow() 2nd argument cannot be '
1752 'negative when 3rd argument specified')
1753 if not modulo:
1754 return context._raise_error(InvalidOperation,
1755 'pow() 3rd argument cannot be 0')
1756
1757 # additional restriction for decimal: the modulus must be less
1758 # than 10**prec in absolute value
1759 if modulo.adjusted() >= context.prec:
1760 return context._raise_error(InvalidOperation,
1761 'insufficient precision: pow() 3rd '
1762 'argument must not have more than '
1763 'precision digits')
1764
1765 # define 0**0 == NaN, for consistency with two-argument pow
1766 # (even though it hurts!)
1767 if not other and not self:
1768 return context._raise_error(InvalidOperation,
1769 'at least one of pow() 1st argument '
1770 'and 2nd argument must be nonzero ;'
1771 '0**0 is not defined')
1772
1773 # compute sign of result
1774 if other._iseven():
1775 sign = 0
1776 else:
1777 sign = self._sign
1778
1779 # convert modulo to a Python integer, and self and other to
1780 # Decimal integers (i.e. force their exponents to be >= 0)
1781 modulo = abs(int(modulo))
1782 base = _WorkRep(self.to_integral_value())
1783 exponent = _WorkRep(other.to_integral_value())
1784
1785 # compute result using integer pow()
1786 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1787 for i in range(exponent.exp):
1788 base = pow(base, 10, modulo)
1789 base = pow(base, exponent.int, modulo)
1790
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001791 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001792
1793 def _power_exact(self, other, p):
1794 """Attempt to compute self**other exactly.
1795
1796 Given Decimals self and other and an integer p, attempt to
1797 compute an exact result for the power self**other, with p
1798 digits of precision. Return None if self**other is not
1799 exactly representable in p digits.
1800
1801 Assumes that elimination of special cases has already been
1802 performed: self and other must both be nonspecial; self must
1803 be positive and not numerically equal to 1; other must be
1804 nonzero. For efficiency, other._exp should not be too large,
1805 so that 10**abs(other._exp) is a feasible calculation."""
1806
1807 # In the comments below, we write x for the value of self and
1808 # y for the value of other. Write x = xc*10**xe and y =
1809 # yc*10**ye.
1810
1811 # The main purpose of this method is to identify the *failure*
1812 # of x**y to be exactly representable with as little effort as
1813 # possible. So we look for cheap and easy tests that
1814 # eliminate the possibility of x**y being exact. Only if all
1815 # these tests are passed do we go on to actually compute x**y.
1816
1817 # Here's the main idea. First normalize both x and y. We
1818 # express y as a rational m/n, with m and n relatively prime
1819 # and n>0. Then for x**y to be exactly representable (at
1820 # *any* precision), xc must be the nth power of a positive
1821 # integer and xe must be divisible by n. If m is negative
1822 # then additionally xc must be a power of either 2 or 5, hence
1823 # a power of 2**n or 5**n.
1824 #
1825 # There's a limit to how small |y| can be: if y=m/n as above
1826 # then:
1827 #
1828 # (1) if xc != 1 then for the result to be representable we
1829 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1830 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1831 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1832 # representable.
1833 #
1834 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1835 # |y| < 1/|xe| then the result is not representable.
1836 #
1837 # Note that since x is not equal to 1, at least one of (1) and
1838 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1839 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1840 #
1841 # There's also a limit to how large y can be, at least if it's
1842 # positive: the normalized result will have coefficient xc**y,
1843 # so if it's representable then xc**y < 10**p, and y <
1844 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1845 # not exactly representable.
1846
1847 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1848 # so |y| < 1/xe and the result is not representable.
1849 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1850 # < 1/nbits(xc).
1851
1852 x = _WorkRep(self)
1853 xc, xe = x.int, x.exp
1854 while xc % 10 == 0:
1855 xc //= 10
1856 xe += 1
1857
1858 y = _WorkRep(other)
1859 yc, ye = y.int, y.exp
1860 while yc % 10 == 0:
1861 yc //= 10
1862 ye += 1
1863
1864 # case where xc == 1: result is 10**(xe*y), with xe*y
1865 # required to be an integer
1866 if xc == 1:
1867 if ye >= 0:
1868 exponent = xe*yc*10**ye
1869 else:
1870 exponent, remainder = divmod(xe*yc, 10**-ye)
1871 if remainder:
1872 return None
1873 if y.sign == 1:
1874 exponent = -exponent
1875 # if other is a nonnegative integer, use ideal exponent
1876 if other._isinteger() and other._sign == 0:
1877 ideal_exponent = self._exp*int(other)
1878 zeros = min(exponent-ideal_exponent, p-1)
1879 else:
1880 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001881 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001882
1883 # case where y is negative: xc must be either a power
1884 # of 2 or a power of 5.
1885 if y.sign == 1:
1886 last_digit = xc % 10
1887 if last_digit in (2,4,6,8):
1888 # quick test for power of 2
1889 if xc & -xc != xc:
1890 return None
1891 # now xc is a power of 2; e is its exponent
1892 e = _nbits(xc)-1
1893 # find e*y and xe*y; both must be integers
1894 if ye >= 0:
1895 y_as_int = yc*10**ye
1896 e = e*y_as_int
1897 xe = xe*y_as_int
1898 else:
1899 ten_pow = 10**-ye
1900 e, remainder = divmod(e*yc, ten_pow)
1901 if remainder:
1902 return None
1903 xe, remainder = divmod(xe*yc, ten_pow)
1904 if remainder:
1905 return None
1906
1907 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1908 return None
1909 xc = 5**e
1910
1911 elif last_digit == 5:
1912 # e >= log_5(xc) if xc is a power of 5; we have
1913 # equality all the way up to xc=5**2658
1914 e = _nbits(xc)*28//65
1915 xc, remainder = divmod(5**e, xc)
1916 if remainder:
1917 return None
1918 while xc % 5 == 0:
1919 xc //= 5
1920 e -= 1
1921 if ye >= 0:
1922 y_as_integer = yc*10**ye
1923 e = e*y_as_integer
1924 xe = xe*y_as_integer
1925 else:
1926 ten_pow = 10**-ye
1927 e, remainder = divmod(e*yc, ten_pow)
1928 if remainder:
1929 return None
1930 xe, remainder = divmod(xe*yc, ten_pow)
1931 if remainder:
1932 return None
1933 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1934 return None
1935 xc = 2**e
1936 else:
1937 return None
1938
1939 if xc >= 10**p:
1940 return None
1941 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001942 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001943
1944 # now y is positive; find m and n such that y = m/n
1945 if ye >= 0:
1946 m, n = yc*10**ye, 1
1947 else:
1948 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1949 return None
1950 xc_bits = _nbits(xc)
1951 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1952 return None
1953 m, n = yc, 10**(-ye)
1954 while m % 2 == n % 2 == 0:
1955 m //= 2
1956 n //= 2
1957 while m % 5 == n % 5 == 0:
1958 m //= 5
1959 n //= 5
1960
1961 # compute nth root of xc*10**xe
1962 if n > 1:
1963 # if 1 < xc < 2**n then xc isn't an nth power
1964 if xc != 1 and xc_bits <= n:
1965 return None
1966
1967 xe, rem = divmod(xe, n)
1968 if rem != 0:
1969 return None
1970
1971 # compute nth root of xc using Newton's method
1972 a = 1 << -(-_nbits(xc)//n) # initial estimate
1973 while True:
1974 q, r = divmod(xc, a**(n-1))
1975 if a <= q:
1976 break
1977 else:
1978 a = (a*(n-1) + q)//n
1979 if not (a == q and r == 0):
1980 return None
1981 xc = a
1982
1983 # now xc*10**xe is the nth root of the original xc*10**xe
1984 # compute mth power of xc*10**xe
1985
1986 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1987 # 10**p and the result is not representable.
1988 if xc > 1 and m > p*100//_log10_lb(xc):
1989 return None
1990 xc = xc**m
1991 xe *= m
1992 if xc > 10**p:
1993 return None
1994
1995 # by this point the result *is* exactly representable
1996 # adjust the exponent to get as close as possible to the ideal
1997 # exponent, if necessary
1998 str_xc = str(xc)
1999 if other._isinteger() and other._sign == 0:
2000 ideal_exponent = self._exp*int(other)
2001 zeros = min(xe-ideal_exponent, p-len(str_xc))
2002 else:
2003 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002004 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002005
2006 def __pow__(self, other, modulo=None, context=None):
2007 """Return self ** other [ % modulo].
2008
2009 With two arguments, compute self**other.
2010
2011 With three arguments, compute (self**other) % modulo. For the
2012 three argument form, the following restrictions on the
2013 arguments hold:
2014
2015 - all three arguments must be integral
2016 - other must be nonnegative
2017 - either self or other (or both) must be nonzero
2018 - modulo must be nonzero and must have at most p digits,
2019 where p is the context precision.
2020
2021 If any of these restrictions is violated the InvalidOperation
2022 flag is raised.
2023
2024 The result of pow(self, other, modulo) is identical to the
2025 result that would be obtained by computing (self**other) %
2026 modulo with unbounded precision, but is computed more
2027 efficiently. It is always exact.
2028 """
2029
2030 if modulo is not None:
2031 return self._power_modulo(other, modulo, context)
2032
2033 other = _convert_other(other)
2034 if other is NotImplemented:
2035 return other
2036
2037 if context is None:
2038 context = getcontext()
2039
2040 # either argument is a NaN => result is NaN
2041 ans = self._check_nans(other, context)
2042 if ans:
2043 return ans
2044
2045 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2046 if not other:
2047 if not self:
2048 return context._raise_error(InvalidOperation, '0 ** 0')
2049 else:
2050 return Dec_p1
2051
2052 # result has sign 1 iff self._sign is 1 and other is an odd integer
2053 result_sign = 0
2054 if self._sign == 1:
2055 if other._isinteger():
2056 if not other._iseven():
2057 result_sign = 1
2058 else:
2059 # -ve**noninteger = NaN
2060 # (-0)**noninteger = 0**noninteger
2061 if self:
2062 return context._raise_error(InvalidOperation,
2063 'x ** y with x negative and y not an integer')
2064 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002065 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002066
2067 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2068 if not self:
2069 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002070 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002071 else:
2072 return Infsign[result_sign]
2073
2074 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002075 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002076 if other._sign == 0:
2077 return Infsign[result_sign]
2078 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002079 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002080
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002081 # 1**other = 1, but the choice of exponent and the flags
2082 # depend on the exponent of self, and on whether other is a
2083 # positive integer, a negative integer, or neither
2084 if self == Dec_p1:
2085 if other._isinteger():
2086 # exp = max(self._exp*max(int(other), 0),
2087 # 1-context.prec) but evaluating int(other) directly
2088 # is dangerous until we know other is small (other
2089 # could be 1e999999999)
2090 if other._sign == 1:
2091 multiplier = 0
2092 elif other > context.prec:
2093 multiplier = context.prec
2094 else:
2095 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002096
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002097 exp = self._exp * multiplier
2098 if exp < 1-context.prec:
2099 exp = 1-context.prec
2100 context._raise_error(Rounded)
2101 else:
2102 context._raise_error(Inexact)
2103 context._raise_error(Rounded)
2104 exp = 1-context.prec
2105
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002106 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002107
2108 # compute adjusted exponent of self
2109 self_adj = self.adjusted()
2110
2111 # self ** infinity is infinity if self > 1, 0 if self < 1
2112 # self ** -infinity is infinity if self < 1, 0 if self > 1
2113 if other._isinfinity():
2114 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002115 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002116 else:
2117 return Infsign[result_sign]
2118
2119 # from here on, the result always goes through the call
2120 # to _fix at the end of this function.
2121 ans = None
2122
2123 # crude test to catch cases of extreme overflow/underflow. If
2124 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2125 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2126 # self**other >= 10**(Emax+1), so overflow occurs. The test
2127 # for underflow is similar.
2128 bound = self._log10_exp_bound() + other.adjusted()
2129 if (self_adj >= 0) == (other._sign == 0):
2130 # self > 1 and other +ve, or self < 1 and other -ve
2131 # possibility of overflow
2132 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002133 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002134 else:
2135 # self > 1 and other -ve, or self < 1 and other +ve
2136 # possibility of underflow to 0
2137 Etiny = context.Etiny()
2138 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002139 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002140
2141 # try for an exact result with precision +1
2142 if ans is None:
2143 ans = self._power_exact(other, context.prec + 1)
2144 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002145 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002146
2147 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2148 if ans is None:
2149 p = context.prec
2150 x = _WorkRep(self)
2151 xc, xe = x.int, x.exp
2152 y = _WorkRep(other)
2153 yc, ye = y.int, y.exp
2154 if y.sign == 1:
2155 yc = -yc
2156
2157 # compute correctly rounded result: start with precision +3,
2158 # then increase precision until result is unambiguously roundable
2159 extra = 3
2160 while True:
2161 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2162 if coeff % (5*10**(len(str(coeff))-p-1)):
2163 break
2164 extra += 3
2165
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002166 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002167
2168 # the specification says that for non-integer other we need to
2169 # raise Inexact, even when the result is actually exact. In
2170 # the same way, we need to raise Underflow here if the result
2171 # is subnormal. (The call to _fix will take care of raising
2172 # Rounded and Subnormal, as usual.)
2173 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002174 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002175 # pad with zeros up to length context.prec+1 if necessary
2176 if len(ans._int) <= context.prec:
2177 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002178 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2179 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002180 if ans.adjusted() < context.Emin:
2181 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002182
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002183 # unlike exp, ln and log10, the power function respects the
2184 # rounding mode; no need to use ROUND_HALF_EVEN here
2185 ans = ans._fix(context)
2186 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002187
2188 def __rpow__(self, other, context=None):
2189 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002190 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002191 if other is NotImplemented:
2192 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002193 return other.__pow__(self, context=context)
2194
2195 def normalize(self, context=None):
2196 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002197
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002198 if context is None:
2199 context = getcontext()
2200
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002201 if self._is_special:
2202 ans = self._check_nans(context=context)
2203 if ans:
2204 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002205
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002206 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002207 if dup._isinfinity():
2208 return dup
2209
2210 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002211 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002212 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002213 end = len(dup._int)
2214 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002215 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002216 exp += 1
2217 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002218 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002219
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002220 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002221 """Quantize self so its exponent is the same as that of exp.
2222
2223 Similar to self._rescale(exp._exp) but with error checking.
2224 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002225 exp = _convert_other(exp, raiseit=True)
2226
2227 if context is None:
2228 context = getcontext()
2229 if rounding is None:
2230 rounding = context.rounding
2231
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002232 if self._is_special or exp._is_special:
2233 ans = self._check_nans(exp, context)
2234 if ans:
2235 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002236
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002237 if exp._isinfinity() or self._isinfinity():
2238 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002239 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002240 return context._raise_error(InvalidOperation,
2241 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002242
2243 # if we're not watching exponents, do a simple rescale
2244 if not watchexp:
2245 ans = self._rescale(exp._exp, rounding)
2246 # raise Inexact and Rounded where appropriate
2247 if ans._exp > self._exp:
2248 context._raise_error(Rounded)
2249 if ans != self:
2250 context._raise_error(Inexact)
2251 return ans
2252
2253 # exp._exp should be between Etiny and Emax
2254 if not (context.Etiny() <= exp._exp <= context.Emax):
2255 return context._raise_error(InvalidOperation,
2256 'target exponent out of bounds in quantize')
2257
2258 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002259 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002260 return ans._fix(context)
2261
2262 self_adjusted = self.adjusted()
2263 if self_adjusted > context.Emax:
2264 return context._raise_error(InvalidOperation,
2265 'exponent of quantize result too large for current context')
2266 if self_adjusted - exp._exp + 1 > context.prec:
2267 return context._raise_error(InvalidOperation,
2268 'quantize result has too many digits for current context')
2269
2270 ans = self._rescale(exp._exp, rounding)
2271 if ans.adjusted() > context.Emax:
2272 return context._raise_error(InvalidOperation,
2273 'exponent of quantize result too large for current context')
2274 if len(ans._int) > context.prec:
2275 return context._raise_error(InvalidOperation,
2276 'quantize result has too many digits for current context')
2277
2278 # raise appropriate flags
2279 if ans._exp > self._exp:
2280 context._raise_error(Rounded)
2281 if ans != self:
2282 context._raise_error(Inexact)
2283 if ans and ans.adjusted() < context.Emin:
2284 context._raise_error(Subnormal)
2285
2286 # call to fix takes care of any necessary folddown
2287 ans = ans._fix(context)
2288 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002289
2290 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002291 """Return True if self and other have the same exponent; otherwise
2292 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002293
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002294 If either operand is a special value, the following rules are used:
2295 * return True if both operands are infinities
2296 * return True if both operands are NaNs
2297 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002298 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002299 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002300 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002301 return (self.is_nan() and other.is_nan() or
2302 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002303 return self._exp == other._exp
2304
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002305 def _rescale(self, exp, rounding):
2306 """Rescale self so that the exponent is exp, either by padding with zeros
2307 or by truncating digits, using the given rounding mode.
2308
2309 Specials are returned without change. This operation is
2310 quiet: it raises no flags, and uses no information from the
2311 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002312
2313 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002314 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002315 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002316 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002317 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002318 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002319 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002320
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002321 if self._exp >= exp:
2322 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002323 return _dec_from_triple(self._sign,
2324 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002325
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002326 # too many digits; round and lose data. If self.adjusted() <
2327 # exp-1, replace self by 10**(exp-1) before rounding
2328 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002329 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002330 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002331 digits = 0
2332 this_function = getattr(self, self._pick_rounding_function[rounding])
2333 return this_function(digits)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002334
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002335 def to_integral_exact(self, rounding=None, context=None):
2336 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002337
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002338 If no rounding mode is specified, take the rounding mode from
2339 the context. This method raises the Rounded and Inexact flags
2340 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002341
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002342 See also: to_integral_value, which does exactly the same as
2343 this method except that it doesn't raise Inexact or Rounded.
2344 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002345 if self._is_special:
2346 ans = self._check_nans(context=context)
2347 if ans:
2348 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002349 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002350 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002351 return Decimal(self)
2352 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002353 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002354 if context is None:
2355 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002356 if rounding is None:
2357 rounding = context.rounding
2358 context._raise_error(Rounded)
2359 ans = self._rescale(0, rounding)
2360 if ans != self:
2361 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002362 return ans
2363
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002364 def to_integral_value(self, rounding=None, context=None):
2365 """Rounds to the nearest integer, without raising inexact, rounded."""
2366 if context is None:
2367 context = getcontext()
2368 if rounding is None:
2369 rounding = context.rounding
2370 if self._is_special:
2371 ans = self._check_nans(context=context)
2372 if ans:
2373 return ans
2374 return Decimal(self)
2375 if self._exp >= 0:
2376 return Decimal(self)
2377 else:
2378 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002379
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002380 # the method name changed, but we provide also the old one, for compatibility
2381 to_integral = to_integral_value
2382
2383 def sqrt(self, context=None):
2384 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002385 if self._is_special:
2386 ans = self._check_nans(context=context)
2387 if ans:
2388 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002389
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002390 if self._isinfinity() and self._sign == 0:
2391 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002392
2393 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002394 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002395 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002396 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002397
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002398 if context is None:
2399 context = getcontext()
2400
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002401 if self._sign == 1:
2402 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2403
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002404 # At this point self represents a positive number. Let p be
2405 # the desired precision and express self in the form c*100**e
2406 # with c a positive real number and e an integer, c and e
2407 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2408 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2409 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2410 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2411 # the closest integer to sqrt(c) with the even integer chosen
2412 # in the case of a tie.
2413 #
2414 # To ensure correct rounding in all cases, we use the
2415 # following trick: we compute the square root to an extra
2416 # place (precision p+1 instead of precision p), rounding down.
2417 # Then, if the result is inexact and its last digit is 0 or 5,
2418 # we increase the last digit to 1 or 6 respectively; if it's
2419 # exact we leave the last digit alone. Now the final round to
2420 # p places (or fewer in the case of underflow) will round
2421 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002422
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002423 # use an extra digit of precision
2424 prec = context.prec+1
2425
2426 # write argument in the form c*100**e where e = self._exp//2
2427 # is the 'ideal' exponent, to be used if the square root is
2428 # exactly representable. l is the number of 'digits' of c in
2429 # base 100, so that 100**(l-1) <= c < 100**l.
2430 op = _WorkRep(self)
2431 e = op.exp >> 1
2432 if op.exp & 1:
2433 c = op.int * 10
2434 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002435 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002436 c = op.int
2437 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002438
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002439 # rescale so that c has exactly prec base 100 'digits'
2440 shift = prec-l
2441 if shift >= 0:
2442 c *= 100**shift
2443 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002444 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002445 c, remainder = divmod(c, 100**-shift)
2446 exact = not remainder
2447 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002448
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002449 # find n = floor(sqrt(c)) using Newton's method
2450 n = 10**prec
2451 while True:
2452 q = c//n
2453 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002454 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002455 else:
2456 n = n + q >> 1
2457 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002458
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002459 if exact:
2460 # result is exact; rescale to use ideal exponent e
2461 if shift >= 0:
2462 # assert n % 10**shift == 0
2463 n //= 10**shift
2464 else:
2465 n *= 10**-shift
2466 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002467 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002468 # result is not exact; fix last digit as described above
2469 if n % 5 == 0:
2470 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002471
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002472 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002473
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002474 # round, and fit to current context
2475 context = context._shallow_copy()
2476 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002477 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002478 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002479
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002480 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002481
2482 def max(self, other, context=None):
2483 """Returns the larger value.
2484
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002485 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002486 NaN (and signals if one is sNaN). Also rounds.
2487 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002488 other = _convert_other(other, raiseit=True)
2489
2490 if context is None:
2491 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002492
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002493 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002494 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002495 # number is always returned
2496 sn = self._isnan()
2497 on = other._isnan()
2498 if sn or on:
2499 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002500 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002501 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002502 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002503 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002504
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002505 c = self.__cmp__(other)
2506 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002507 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002508 # then an ordering is applied:
2509 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002510 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002511 # positive sign and min returns the operand with the negative sign
2512 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002513 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002514 # the result. This is exactly the ordering used in compare_total.
2515 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002516
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002517 if c == -1:
2518 ans = other
2519 else:
2520 ans = self
2521
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002522 if context._rounding_decision == ALWAYS_ROUND:
2523 return ans._fix(context)
2524 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002525
2526 def min(self, other, context=None):
2527 """Returns the smaller value.
2528
Guido van Rossumd8faa362007-04-27 19:54:29 +00002529 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002530 NaN (and signals if one is sNaN). Also rounds.
2531 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002532 other = _convert_other(other, raiseit=True)
2533
2534 if context is None:
2535 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002536
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002537 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002538 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002539 # number is always returned
2540 sn = self._isnan()
2541 on = other._isnan()
2542 if sn or on:
2543 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002544 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002545 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002546 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002547 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002548
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002549 c = self.__cmp__(other)
2550 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002551 c = self.compare_total(other)
2552
2553 if c == -1:
2554 ans = self
2555 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002556 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002557
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002558 if context._rounding_decision == ALWAYS_ROUND:
2559 return ans._fix(context)
2560 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002561
2562 def _isinteger(self):
2563 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002564 if self._is_special:
2565 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002566 if self._exp >= 0:
2567 return True
2568 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002569 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002570
2571 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002572 """Returns True if self is even. Assumes self is an integer."""
2573 if not self or self._exp > 0:
2574 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002575 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002576
2577 def adjusted(self):
2578 """Return the adjusted exponent of self"""
2579 try:
2580 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002581 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002582 except TypeError:
2583 return 0
2584
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002585 def canonical(self, context=None):
2586 """Returns the same Decimal object.
2587
2588 As we do not have different encodings for the same number, the
2589 received object already is in its canonical form.
2590 """
2591 return self
2592
2593 def compare_signal(self, other, context=None):
2594 """Compares self to the other operand numerically.
2595
2596 It's pretty much like compare(), but all NaNs signal, with signaling
2597 NaNs taking precedence over quiet NaNs.
2598 """
2599 if context is None:
2600 context = getcontext()
2601
2602 self_is_nan = self._isnan()
2603 other_is_nan = other._isnan()
2604 if self_is_nan == 2:
2605 return context._raise_error(InvalidOperation, 'sNaN',
2606 1, self)
2607 if other_is_nan == 2:
2608 return context._raise_error(InvalidOperation, 'sNaN',
2609 1, other)
2610 if self_is_nan:
2611 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2612 1, self)
2613 if other_is_nan:
2614 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2615 1, other)
2616 return self.compare(other, context=context)
2617
2618 def compare_total(self, other):
2619 """Compares self to other using the abstract representations.
2620
2621 This is not like the standard compare, which use their numerical
2622 value. Note that a total ordering is defined for all possible abstract
2623 representations.
2624 """
2625 # if one is negative and the other is positive, it's easy
2626 if self._sign and not other._sign:
2627 return Dec_n1
2628 if not self._sign and other._sign:
2629 return Dec_p1
2630 sign = self._sign
2631
2632 # let's handle both NaN types
2633 self_nan = self._isnan()
2634 other_nan = other._isnan()
2635 if self_nan or other_nan:
2636 if self_nan == other_nan:
2637 if self._int < other._int:
2638 if sign:
2639 return Dec_p1
2640 else:
2641 return Dec_n1
2642 if self._int > other._int:
2643 if sign:
2644 return Dec_n1
2645 else:
2646 return Dec_p1
2647 return Dec_0
2648
2649 if sign:
2650 if self_nan == 1:
2651 return Dec_n1
2652 if other_nan == 1:
2653 return Dec_p1
2654 if self_nan == 2:
2655 return Dec_n1
2656 if other_nan == 2:
2657 return Dec_p1
2658 else:
2659 if self_nan == 1:
2660 return Dec_p1
2661 if other_nan == 1:
2662 return Dec_n1
2663 if self_nan == 2:
2664 return Dec_p1
2665 if other_nan == 2:
2666 return Dec_n1
2667
2668 if self < other:
2669 return Dec_n1
2670 if self > other:
2671 return Dec_p1
2672
2673 if self._exp < other._exp:
2674 if sign:
2675 return Dec_p1
2676 else:
2677 return Dec_n1
2678 if self._exp > other._exp:
2679 if sign:
2680 return Dec_n1
2681 else:
2682 return Dec_p1
2683 return Dec_0
2684
2685
2686 def compare_total_mag(self, other):
2687 """Compares self to other using abstract repr., ignoring sign.
2688
2689 Like compare_total, but with operand's sign ignored and assumed to be 0.
2690 """
2691 s = self.copy_abs()
2692 o = other.copy_abs()
2693 return s.compare_total(o)
2694
2695 def copy_abs(self):
2696 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002697 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002698
2699 def copy_negate(self):
2700 """Returns a copy with the sign inverted."""
2701 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002702 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002703 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002704 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002705
2706 def copy_sign(self, other):
2707 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002708 return _dec_from_triple(other._sign, self._int,
2709 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002710
2711 def exp(self, context=None):
2712 """Returns e ** self."""
2713
2714 if context is None:
2715 context = getcontext()
2716
2717 # exp(NaN) = NaN
2718 ans = self._check_nans(context=context)
2719 if ans:
2720 return ans
2721
2722 # exp(-Infinity) = 0
2723 if self._isinfinity() == -1:
2724 return Dec_0
2725
2726 # exp(0) = 1
2727 if not self:
2728 return Dec_p1
2729
2730 # exp(Infinity) = Infinity
2731 if self._isinfinity() == 1:
2732 return Decimal(self)
2733
2734 # the result is now guaranteed to be inexact (the true
2735 # mathematical result is transcendental). There's no need to
2736 # raise Rounded and Inexact here---they'll always be raised as
2737 # a result of the call to _fix.
2738 p = context.prec
2739 adj = self.adjusted()
2740
2741 # we only need to do any computation for quite a small range
2742 # of adjusted exponents---for example, -29 <= adj <= 10 for
2743 # the default context. For smaller exponent the result is
2744 # indistinguishable from 1 at the given precision, while for
2745 # larger exponent the result either overflows or underflows.
2746 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2747 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002748 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002749 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2750 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002751 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002752 elif self._sign == 0 and adj < -p:
2753 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002754 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002755 elif self._sign == 1 and adj < -p-1:
2756 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002757 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002758 # general case
2759 else:
2760 op = _WorkRep(self)
2761 c, e = op.int, op.exp
2762 if op.sign == 1:
2763 c = -c
2764
2765 # compute correctly rounded result: increase precision by
2766 # 3 digits at a time until we get an unambiguously
2767 # roundable result
2768 extra = 3
2769 while True:
2770 coeff, exp = _dexp(c, e, p+extra)
2771 if coeff % (5*10**(len(str(coeff))-p-1)):
2772 break
2773 extra += 3
2774
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002775 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002776
2777 # at this stage, ans should round correctly with *any*
2778 # rounding mode, not just with ROUND_HALF_EVEN
2779 context = context._shallow_copy()
2780 rounding = context._set_rounding(ROUND_HALF_EVEN)
2781 ans = ans._fix(context)
2782 context.rounding = rounding
2783
2784 return ans
2785
2786 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002787 """Return True if self is canonical; otherwise return False.
2788
2789 Currently, the encoding of a Decimal instance is always
2790 canonical, so this method returns True for any Decimal.
2791 """
2792 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002793
2794 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002795 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002796
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002797 A Decimal instance is considered finite if it is neither
2798 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002799 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002800 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002801
2802 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002803 """Return True if self is infinite; otherwise return False."""
2804 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002805
2806 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002807 """Return True if self is a qNaN or sNaN; otherwise return False."""
2808 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002809
2810 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002811 """Return True if self is a normal number; otherwise return False."""
2812 if self._is_special or not self:
2813 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002814 if context is None:
2815 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002816 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002817
2818 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002819 """Return True if self is a quiet NaN; otherwise return False."""
2820 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002821
2822 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002823 """Return True if self is negative; otherwise return False."""
2824 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002825
2826 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002827 """Return True if self is a signaling NaN; otherwise return False."""
2828 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002829
2830 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002831 """Return True if self is subnormal; otherwise return False."""
2832 if self._is_special or not self:
2833 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002834 if context is None:
2835 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002836 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002837
2838 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002839 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002840 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002841
2842 def _ln_exp_bound(self):
2843 """Compute a lower bound for the adjusted exponent of self.ln().
2844 In other words, compute r such that self.ln() >= 10**r. Assumes
2845 that self is finite and positive and that self != 1.
2846 """
2847
2848 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2849 adj = self._exp + len(self._int) - 1
2850 if adj >= 1:
2851 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2852 return len(str(adj*23//10)) - 1
2853 if adj <= -2:
2854 # argument <= 0.1
2855 return len(str((-1-adj)*23//10)) - 1
2856 op = _WorkRep(self)
2857 c, e = op.int, op.exp
2858 if adj == 0:
2859 # 1 < self < 10
2860 num = str(c-10**-e)
2861 den = str(c)
2862 return len(num) - len(den) - (num < den)
2863 # adj == -1, 0.1 <= self < 1
2864 return e + len(str(10**-e - c)) - 1
2865
2866
2867 def ln(self, context=None):
2868 """Returns the natural (base e) logarithm of self."""
2869
2870 if context is None:
2871 context = getcontext()
2872
2873 # ln(NaN) = NaN
2874 ans = self._check_nans(context=context)
2875 if ans:
2876 return ans
2877
2878 # ln(0.0) == -Infinity
2879 if not self:
2880 return negInf
2881
2882 # ln(Infinity) = Infinity
2883 if self._isinfinity() == 1:
2884 return Inf
2885
2886 # ln(1.0) == 0.0
2887 if self == Dec_p1:
2888 return Dec_0
2889
2890 # ln(negative) raises InvalidOperation
2891 if self._sign == 1:
2892 return context._raise_error(InvalidOperation,
2893 'ln of a negative value')
2894
2895 # result is irrational, so necessarily inexact
2896 op = _WorkRep(self)
2897 c, e = op.int, op.exp
2898 p = context.prec
2899
2900 # correctly rounded result: repeatedly increase precision by 3
2901 # until we get an unambiguously roundable result
2902 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2903 while True:
2904 coeff = _dlog(c, e, places)
2905 # assert len(str(abs(coeff)))-p >= 1
2906 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2907 break
2908 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002909 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002910
2911 context = context._shallow_copy()
2912 rounding = context._set_rounding(ROUND_HALF_EVEN)
2913 ans = ans._fix(context)
2914 context.rounding = rounding
2915 return ans
2916
2917 def _log10_exp_bound(self):
2918 """Compute a lower bound for the adjusted exponent of self.log10().
2919 In other words, find r such that self.log10() >= 10**r.
2920 Assumes that self is finite and positive and that self != 1.
2921 """
2922
2923 # For x >= 10 or x < 0.1 we only need a bound on the integer
2924 # part of log10(self), and this comes directly from the
2925 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2926 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2927 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2928
2929 adj = self._exp + len(self._int) - 1
2930 if adj >= 1:
2931 # self >= 10
2932 return len(str(adj))-1
2933 if adj <= -2:
2934 # self < 0.1
2935 return len(str(-1-adj))-1
2936 op = _WorkRep(self)
2937 c, e = op.int, op.exp
2938 if adj == 0:
2939 # 1 < self < 10
2940 num = str(c-10**-e)
2941 den = str(231*c)
2942 return len(num) - len(den) - (num < den) + 2
2943 # adj == -1, 0.1 <= self < 1
2944 num = str(10**-e-c)
2945 return len(num) + e - (num < "231") - 1
2946
2947 def log10(self, context=None):
2948 """Returns the base 10 logarithm of self."""
2949
2950 if context is None:
2951 context = getcontext()
2952
2953 # log10(NaN) = NaN
2954 ans = self._check_nans(context=context)
2955 if ans:
2956 return ans
2957
2958 # log10(0.0) == -Infinity
2959 if not self:
2960 return negInf
2961
2962 # log10(Infinity) = Infinity
2963 if self._isinfinity() == 1:
2964 return Inf
2965
2966 # log10(negative or -Infinity) raises InvalidOperation
2967 if self._sign == 1:
2968 return context._raise_error(InvalidOperation,
2969 'log10 of a negative value')
2970
2971 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002972 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002973 # answer may need rounding
2974 ans = Decimal(self._exp + len(self._int) - 1)
2975 else:
2976 # result is irrational, so necessarily inexact
2977 op = _WorkRep(self)
2978 c, e = op.int, op.exp
2979 p = context.prec
2980
2981 # correctly rounded result: repeatedly increase precision
2982 # until result is unambiguously roundable
2983 places = p-self._log10_exp_bound()+2
2984 while True:
2985 coeff = _dlog10(c, e, places)
2986 # assert len(str(abs(coeff)))-p >= 1
2987 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2988 break
2989 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002990 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002991
2992 context = context._shallow_copy()
2993 rounding = context._set_rounding(ROUND_HALF_EVEN)
2994 ans = ans._fix(context)
2995 context.rounding = rounding
2996 return ans
2997
2998 def logb(self, context=None):
2999 """ Returns the exponent of the magnitude of self's MSD.
3000
3001 The result is the integer which is the exponent of the magnitude
3002 of the most significant digit of self (as though it were truncated
3003 to a single digit while maintaining the value of that digit and
3004 without limiting the resulting exponent).
3005 """
3006 # logb(NaN) = NaN
3007 ans = self._check_nans(context=context)
3008 if ans:
3009 return ans
3010
3011 if context is None:
3012 context = getcontext()
3013
3014 # logb(+/-Inf) = +Inf
3015 if self._isinfinity():
3016 return Inf
3017
3018 # logb(0) = -Inf, DivisionByZero
3019 if not self:
3020 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3021
3022 # otherwise, simply return the adjusted exponent of self, as a
3023 # Decimal. Note that no attempt is made to fit the result
3024 # into the current context.
3025 return Decimal(self.adjusted())
3026
3027 def _islogical(self):
3028 """Return True if self is a logical operand.
3029
3030 For being logical, it must be a finite numbers with a sign of 0,
3031 an exponent of 0, and a coefficient whose digits must all be
3032 either 0 or 1.
3033 """
3034 if self._sign != 0 or self._exp != 0:
3035 return False
3036 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003037 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003038 return False
3039 return True
3040
3041 def _fill_logical(self, context, opa, opb):
3042 dif = context.prec - len(opa)
3043 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003044 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003045 elif dif < 0:
3046 opa = opa[-context.prec:]
3047 dif = context.prec - len(opb)
3048 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003049 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003050 elif dif < 0:
3051 opb = opb[-context.prec:]
3052 return opa, opb
3053
3054 def logical_and(self, other, context=None):
3055 """Applies an 'and' operation between self and other's digits."""
3056 if context is None:
3057 context = getcontext()
3058 if not self._islogical() or not other._islogical():
3059 return context._raise_error(InvalidOperation)
3060
3061 # fill to context.prec
3062 (opa, opb) = self._fill_logical(context, self._int, other._int)
3063
3064 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003065 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3066 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003067
3068 def logical_invert(self, context=None):
3069 """Invert all its digits."""
3070 if context is None:
3071 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003072 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3073 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003074
3075 def logical_or(self, other, context=None):
3076 """Applies an 'or' operation between self and other's digits."""
3077 if context is None:
3078 context = getcontext()
3079 if not self._islogical() or not other._islogical():
3080 return context._raise_error(InvalidOperation)
3081
3082 # fill to context.prec
3083 (opa, opb) = self._fill_logical(context, self._int, other._int)
3084
3085 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003086 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3087 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003088
3089 def logical_xor(self, other, context=None):
3090 """Applies an 'xor' operation between self and other's digits."""
3091 if context is None:
3092 context = getcontext()
3093 if not self._islogical() or not other._islogical():
3094 return context._raise_error(InvalidOperation)
3095
3096 # fill to context.prec
3097 (opa, opb) = self._fill_logical(context, self._int, other._int)
3098
3099 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003100 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3101 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003102
3103 def max_mag(self, other, context=None):
3104 """Compares the values numerically with their sign ignored."""
3105 other = _convert_other(other, raiseit=True)
3106
3107 if context is None:
3108 context = getcontext()
3109
3110 if self._is_special or other._is_special:
3111 # If one operand is a quiet NaN and the other is number, then the
3112 # number is always returned
3113 sn = self._isnan()
3114 on = other._isnan()
3115 if sn or on:
3116 if on == 1 and sn != 2:
3117 return self._fix_nan(context)
3118 if sn == 1 and on != 2:
3119 return other._fix_nan(context)
3120 return self._check_nans(other, context)
3121
3122 c = self.copy_abs().__cmp__(other.copy_abs())
3123 if c == 0:
3124 c = self.compare_total(other)
3125
3126 if c == -1:
3127 ans = other
3128 else:
3129 ans = self
3130
3131 if context._rounding_decision == ALWAYS_ROUND:
3132 return ans._fix(context)
3133 return ans
3134
3135 def min_mag(self, other, context=None):
3136 """Compares the values numerically with their sign ignored."""
3137 other = _convert_other(other, raiseit=True)
3138
3139 if context is None:
3140 context = getcontext()
3141
3142 if self._is_special or other._is_special:
3143 # If one operand is a quiet NaN and the other is number, then the
3144 # number is always returned
3145 sn = self._isnan()
3146 on = other._isnan()
3147 if sn or on:
3148 if on == 1 and sn != 2:
3149 return self._fix_nan(context)
3150 if sn == 1 and on != 2:
3151 return other._fix_nan(context)
3152 return self._check_nans(other, context)
3153
3154 c = self.copy_abs().__cmp__(other.copy_abs())
3155 if c == 0:
3156 c = self.compare_total(other)
3157
3158 if c == -1:
3159 ans = self
3160 else:
3161 ans = other
3162
3163 if context._rounding_decision == ALWAYS_ROUND:
3164 return ans._fix(context)
3165 return ans
3166
3167 def next_minus(self, context=None):
3168 """Returns the largest representable number smaller than itself."""
3169 if context is None:
3170 context = getcontext()
3171
3172 ans = self._check_nans(context=context)
3173 if ans:
3174 return ans
3175
3176 if self._isinfinity() == -1:
3177 return negInf
3178 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003179 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003180
3181 context = context.copy()
3182 context._set_rounding(ROUND_FLOOR)
3183 context._ignore_all_flags()
3184 new_self = self._fix(context)
3185 if new_self != self:
3186 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003187 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3188 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003189
3190 def next_plus(self, context=None):
3191 """Returns the smallest representable number larger than itself."""
3192 if context is None:
3193 context = getcontext()
3194
3195 ans = self._check_nans(context=context)
3196 if ans:
3197 return ans
3198
3199 if self._isinfinity() == 1:
3200 return Inf
3201 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003202 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003203
3204 context = context.copy()
3205 context._set_rounding(ROUND_CEILING)
3206 context._ignore_all_flags()
3207 new_self = self._fix(context)
3208 if new_self != self:
3209 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003210 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3211 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003212
3213 def next_toward(self, other, context=None):
3214 """Returns the number closest to self, in the direction towards other.
3215
3216 The result is the closest representable number to self
3217 (excluding self) that is in the direction towards other,
3218 unless both have the same value. If the two operands are
3219 numerically equal, then the result is a copy of self with the
3220 sign set to be the same as the sign of other.
3221 """
3222 other = _convert_other(other, raiseit=True)
3223
3224 if context is None:
3225 context = getcontext()
3226
3227 ans = self._check_nans(other, context)
3228 if ans:
3229 return ans
3230
3231 comparison = self.__cmp__(other)
3232 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003233 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003234
3235 if comparison == -1:
3236 ans = self.next_plus(context)
3237 else: # comparison == 1
3238 ans = self.next_minus(context)
3239
3240 # decide which flags to raise using value of ans
3241 if ans._isinfinity():
3242 context._raise_error(Overflow,
3243 'Infinite result from next_toward',
3244 ans._sign)
3245 context._raise_error(Rounded)
3246 context._raise_error(Inexact)
3247 elif ans.adjusted() < context.Emin:
3248 context._raise_error(Underflow)
3249 context._raise_error(Subnormal)
3250 context._raise_error(Rounded)
3251 context._raise_error(Inexact)
3252 # if precision == 1 then we don't raise Clamped for a
3253 # result 0E-Etiny.
3254 if not ans:
3255 context._raise_error(Clamped)
3256
3257 return ans
3258
3259 def number_class(self, context=None):
3260 """Returns an indication of the class of self.
3261
3262 The class is one of the following strings:
3263 -sNaN
3264 -NaN
3265 -Infinity
3266 -Normal
3267 -Subnormal
3268 -Zero
3269 +Zero
3270 +Subnormal
3271 +Normal
3272 +Infinity
3273 """
3274 if self.is_snan():
3275 return "sNaN"
3276 if self.is_qnan():
3277 return "NaN"
3278 inf = self._isinfinity()
3279 if inf == 1:
3280 return "+Infinity"
3281 if inf == -1:
3282 return "-Infinity"
3283 if self.is_zero():
3284 if self._sign:
3285 return "-Zero"
3286 else:
3287 return "+Zero"
3288 if context is None:
3289 context = getcontext()
3290 if self.is_subnormal(context=context):
3291 if self._sign:
3292 return "-Subnormal"
3293 else:
3294 return "+Subnormal"
3295 # just a normal, regular, boring number, :)
3296 if self._sign:
3297 return "-Normal"
3298 else:
3299 return "+Normal"
3300
3301 def radix(self):
3302 """Just returns 10, as this is Decimal, :)"""
3303 return Decimal(10)
3304
3305 def rotate(self, other, context=None):
3306 """Returns a rotated copy of self, value-of-other times."""
3307 if context is None:
3308 context = getcontext()
3309
3310 ans = self._check_nans(other, context)
3311 if ans:
3312 return ans
3313
3314 if other._exp != 0:
3315 return context._raise_error(InvalidOperation)
3316 if not (-context.prec <= int(other) <= context.prec):
3317 return context._raise_error(InvalidOperation)
3318
3319 if self._isinfinity():
3320 return Decimal(self)
3321
3322 # get values, pad if necessary
3323 torot = int(other)
3324 rotdig = self._int
3325 topad = context.prec - len(rotdig)
3326 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003327 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003328
3329 # let's rotate!
3330 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003331 return _dec_from_triple(self._sign,
3332 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003333
3334 def scaleb (self, other, context=None):
3335 """Returns self operand after adding the second value to its exp."""
3336 if context is None:
3337 context = getcontext()
3338
3339 ans = self._check_nans(other, context)
3340 if ans:
3341 return ans
3342
3343 if other._exp != 0:
3344 return context._raise_error(InvalidOperation)
3345 liminf = -2 * (context.Emax + context.prec)
3346 limsup = 2 * (context.Emax + context.prec)
3347 if not (liminf <= int(other) <= limsup):
3348 return context._raise_error(InvalidOperation)
3349
3350 if self._isinfinity():
3351 return Decimal(self)
3352
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003353 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003354 d = d._fix(context)
3355 return d
3356
3357 def shift(self, other, context=None):
3358 """Returns a shifted copy of self, value-of-other times."""
3359 if context is None:
3360 context = getcontext()
3361
3362 ans = self._check_nans(other, context)
3363 if ans:
3364 return ans
3365
3366 if other._exp != 0:
3367 return context._raise_error(InvalidOperation)
3368 if not (-context.prec <= int(other) <= context.prec):
3369 return context._raise_error(InvalidOperation)
3370
3371 if self._isinfinity():
3372 return Decimal(self)
3373
3374 # get values, pad if necessary
3375 torot = int(other)
3376 if not torot:
3377 return Decimal(self)
3378 rotdig = self._int
3379 topad = context.prec - len(rotdig)
3380 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003381 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003382
3383 # let's shift!
3384 if torot < 0:
3385 rotated = rotdig[:torot]
3386 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003387 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003388 rotated = rotated[-context.prec:]
3389
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003390 return _dec_from_triple(self._sign,
3391 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003392
Guido van Rossumd8faa362007-04-27 19:54:29 +00003393 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003394 def __reduce__(self):
3395 return (self.__class__, (str(self),))
3396
3397 def __copy__(self):
3398 if type(self) == Decimal:
3399 return self # I'm immutable; therefore I am my own clone
3400 return self.__class__(str(self))
3401
3402 def __deepcopy__(self, memo):
3403 if type(self) == Decimal:
3404 return self # My components are also immutable
3405 return self.__class__(str(self))
3406
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003407def _dec_from_triple(sign, coefficient, exponent, special=False):
3408 """Create a decimal instance directly, without any validation,
3409 normalization (e.g. removal of leading zeros) or argument
3410 conversion.
3411
3412 This function is for *internal use only*.
3413 """
3414
3415 self = object.__new__(Decimal)
3416 self._sign = sign
3417 self._int = coefficient
3418 self._exp = exponent
3419 self._is_special = special
3420
3421 return self
3422
Guido van Rossumd8faa362007-04-27 19:54:29 +00003423##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003424
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003425
3426# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003427rounding_functions = [name for name in Decimal.__dict__.keys()
3428 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003429for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003430 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003431 globalname = name[1:].upper()
3432 val = globals()[globalname]
3433 Decimal._pick_rounding_function[val] = name
3434
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003435del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003436
Thomas Wouters89f507f2006-12-13 04:49:30 +00003437class _ContextManager(object):
3438 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003439
Thomas Wouters89f507f2006-12-13 04:49:30 +00003440 Sets a copy of the supplied context in __enter__() and restores
3441 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003442 """
3443 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003444 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003445 def __enter__(self):
3446 self.saved_context = getcontext()
3447 setcontext(self.new_context)
3448 return self.new_context
3449 def __exit__(self, t, v, tb):
3450 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003451
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003452class Context(object):
3453 """Contains the context for a Decimal instance.
3454
3455 Contains:
3456 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003457 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003458 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003459 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003460 raised when it is caused. Otherwise, a value is
3461 substituted in.
3462 flags - When an exception is caused, flags[exception] is incremented.
3463 (Whether or not the trap_enabler is set)
3464 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003465 Emin - Minimum exponent
3466 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003467 capitals - If 1, 1*10^1 is printed as 1E+1.
3468 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003469 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003470 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003471
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003472 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003473 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003474 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003475 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003476 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003477 _ignored_flags=None):
3478 if flags is None:
3479 flags = []
3480 if _ignored_flags is None:
3481 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003482 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003483 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003484 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003485 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003486 for name, val in locals().items():
3487 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003488 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003489 else:
3490 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003491 del self.self
3492
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003493 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003494 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003495 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003496 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3497 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3498 % vars(self))
3499 names = [f.__name__ for f, v in self.flags.items() if v]
3500 s.append('flags=[' + ', '.join(names) + ']')
3501 names = [t.__name__ for t, v in self.traps.items() if v]
3502 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003503 return ', '.join(s) + ')'
3504
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003505 def clear_flags(self):
3506 """Reset all flags to zero"""
3507 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003508 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003509
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003510 def _shallow_copy(self):
3511 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003512 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003513 self._rounding_decision, self.Emin, self.Emax,
3514 self.capitals, self._clamp, self._ignored_flags)
3515 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003516
3517 def copy(self):
3518 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003519 nc = Context(self.prec, self.rounding, self.traps.copy(),
3520 self.flags.copy(), self._rounding_decision, self.Emin,
3521 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003522 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003523 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003524
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003525 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003526 """Handles an error
3527
3528 If the flag is in _ignored_flags, returns the default response.
3529 Otherwise, it increments the flag, then, if the corresponding
3530 trap_enabler is set, it reaises the exception. Otherwise, it returns
3531 the default value after incrementing the flag.
3532 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003533 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003534 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003535 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003536 return error().handle(self, *args)
3537
3538 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003539 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003540 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003541 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003542
3543 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003544 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003545 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003546
3547 def _ignore_all_flags(self):
3548 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003549 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003550
3551 def _ignore_flags(self, *flags):
3552 """Ignore the flags, if they are raised"""
3553 # Do not mutate-- This way, copies of a context leave the original
3554 # alone.
3555 self._ignored_flags = (self._ignored_flags + list(flags))
3556 return list(flags)
3557
3558 def _regard_flags(self, *flags):
3559 """Stop ignoring the flags, if they are raised"""
3560 if flags and isinstance(flags[0], (tuple,list)):
3561 flags = flags[0]
3562 for flag in flags:
3563 self._ignored_flags.remove(flag)
3564
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003565 def __hash__(self):
3566 """A Context cannot be hashed."""
3567 # We inherit object.__hash__, so we must deny this explicitly
Guido van Rossumd8faa362007-04-27 19:54:29 +00003568 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003569
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003570 def Etiny(self):
3571 """Returns Etiny (= Emin - prec + 1)"""
3572 return int(self.Emin - self.prec + 1)
3573
3574 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003575 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003576 return int(self.Emax - self.prec + 1)
3577
3578 def _set_rounding_decision(self, type):
3579 """Sets the rounding decision.
3580
3581 Sets the rounding decision, and returns the current (previous)
3582 rounding decision. Often used like:
3583
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003584 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003585 # That so you don't change the calling context
3586 # if an error occurs in the middle (say DivisionImpossible is raised).
3587
3588 rounding = context._set_rounding_decision(NEVER_ROUND)
3589 instance = instance / Decimal(2)
3590 context._set_rounding_decision(rounding)
3591
3592 This will make it not round for that operation.
3593 """
3594
3595 rounding = self._rounding_decision
3596 self._rounding_decision = type
3597 return rounding
3598
3599 def _set_rounding(self, type):
3600 """Sets the rounding type.
3601
3602 Sets the rounding type, and returns the current (previous)
3603 rounding type. Often used like:
3604
3605 context = context.copy()
3606 # so you don't change the calling context
3607 # if an error occurs in the middle.
3608 rounding = context._set_rounding(ROUND_UP)
3609 val = self.__sub__(other, context=context)
3610 context._set_rounding(rounding)
3611
3612 This will make it round up for that operation.
3613 """
3614 rounding = self.rounding
3615 self.rounding= type
3616 return rounding
3617
Raymond Hettingerfed52962004-07-14 15:41:57 +00003618 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003619 """Creates a new Decimal instance but using self as context."""
3620 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003621 if d._isnan() and len(d._int) > self.prec - self._clamp:
3622 return self._raise_error(ConversionSyntax,
3623 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003624 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003625
Guido van Rossumd8faa362007-04-27 19:54:29 +00003626 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003627 def abs(self, a):
3628 """Returns the absolute value of the operand.
3629
3630 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003631 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003632 the plus operation on the operand.
3633
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003634 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003635 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003636 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003637 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003638 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003639 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003640 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003641 Decimal("101.5")
3642 """
3643 return a.__abs__(context=self)
3644
3645 def add(self, a, b):
3646 """Return the sum of the two operands.
3647
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003648 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003649 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003650 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003651 Decimal("1.02E+4")
3652 """
3653 return a.__add__(b, context=self)
3654
3655 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003656 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003657
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003658 def canonical(self, a):
3659 """Returns the same Decimal object.
3660
3661 As we do not have different encodings for the same number, the
3662 received object already is in its canonical form.
3663
3664 >>> ExtendedContext.canonical(Decimal('2.50'))
3665 Decimal("2.50")
3666 """
3667 return a.canonical(context=self)
3668
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003669 def compare(self, a, b):
3670 """Compares values numerically.
3671
3672 If the signs of the operands differ, a value representing each operand
3673 ('-1' if the operand is less than zero, '0' if the operand is zero or
3674 negative zero, or '1' if the operand is greater than zero) is used in
3675 place of that operand for the comparison instead of the actual
3676 operand.
3677
3678 The comparison is then effected by subtracting the second operand from
3679 the first and then returning a value according to the result of the
3680 subtraction: '-1' if the result is less than zero, '0' if the result is
3681 zero or negative zero, or '1' if the result is greater than zero.
3682
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003683 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003684 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003685 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003686 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003687 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003688 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003689 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003690 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003691 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003692 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003693 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003694 Decimal("-1")
3695 """
3696 return a.compare(b, context=self)
3697
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003698 def compare_signal(self, a, b):
3699 """Compares the values of the two operands numerically.
3700
3701 It's pretty much like compare(), but all NaNs signal, with signaling
3702 NaNs taking precedence over quiet NaNs.
3703
3704 >>> c = ExtendedContext
3705 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3706 Decimal("-1")
3707 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3708 Decimal("0")
3709 >>> c.flags[InvalidOperation] = 0
3710 >>> print(c.flags[InvalidOperation])
3711 0
3712 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3713 Decimal("NaN")
3714 >>> print(c.flags[InvalidOperation])
3715 1
3716 >>> c.flags[InvalidOperation] = 0
3717 >>> print(c.flags[InvalidOperation])
3718 0
3719 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3720 Decimal("NaN")
3721 >>> print(c.flags[InvalidOperation])
3722 1
3723 """
3724 return a.compare_signal(b, context=self)
3725
3726 def compare_total(self, a, b):
3727 """Compares two operands using their abstract representation.
3728
3729 This is not like the standard compare, which use their numerical
3730 value. Note that a total ordering is defined for all possible abstract
3731 representations.
3732
3733 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3734 Decimal("-1")
3735 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3736 Decimal("-1")
3737 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3738 Decimal("-1")
3739 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3740 Decimal("0")
3741 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3742 Decimal("1")
3743 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3744 Decimal("-1")
3745 """
3746 return a.compare_total(b)
3747
3748 def compare_total_mag(self, a, b):
3749 """Compares two operands using their abstract representation ignoring sign.
3750
3751 Like compare_total, but with operand's sign ignored and assumed to be 0.
3752 """
3753 return a.compare_total_mag(b)
3754
3755 def copy_abs(self, a):
3756 """Returns a copy of the operand with the sign set to 0.
3757
3758 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3759 Decimal("2.1")
3760 >>> ExtendedContext.copy_abs(Decimal('-100'))
3761 Decimal("100")
3762 """
3763 return a.copy_abs()
3764
3765 def copy_decimal(self, a):
3766 """Returns a copy of the decimal objet.
3767
3768 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3769 Decimal("2.1")
3770 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3771 Decimal("-1.00")
3772 """
3773 return Decimal(a)
3774
3775 def copy_negate(self, a):
3776 """Returns a copy of the operand with the sign inverted.
3777
3778 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3779 Decimal("-101.5")
3780 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3781 Decimal("101.5")
3782 """
3783 return a.copy_negate()
3784
3785 def copy_sign(self, a, b):
3786 """Copies the second operand's sign to the first one.
3787
3788 In detail, it returns a copy of the first operand with the sign
3789 equal to the sign of the second operand.
3790
3791 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3792 Decimal("1.50")
3793 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3794 Decimal("1.50")
3795 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3796 Decimal("-1.50")
3797 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3798 Decimal("-1.50")
3799 """
3800 return a.copy_sign(b)
3801
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003802 def divide(self, a, b):
3803 """Decimal division in a specified context.
3804
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003805 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003806 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003807 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003808 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003809 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003810 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003811 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003812 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003813 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003814 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003815 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003816 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003817 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003818 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003819 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003820 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003821 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003822 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003823 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003824 Decimal("1.20E+6")
3825 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003826 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003827
3828 def divide_int(self, a, b):
3829 """Divides two numbers and returns the integer part of the result.
3830
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003831 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003832 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003833 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003834 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003835 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003836 Decimal("3")
3837 """
3838 return a.__floordiv__(b, context=self)
3839
3840 def divmod(self, a, b):
3841 return a.__divmod__(b, context=self)
3842
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003843 def exp(self, a):
3844 """Returns e ** a.
3845
3846 >>> c = ExtendedContext.copy()
3847 >>> c.Emin = -999
3848 >>> c.Emax = 999
3849 >>> c.exp(Decimal('-Infinity'))
3850 Decimal("0")
3851 >>> c.exp(Decimal('-1'))
3852 Decimal("0.367879441")
3853 >>> c.exp(Decimal('0'))
3854 Decimal("1")
3855 >>> c.exp(Decimal('1'))
3856 Decimal("2.71828183")
3857 >>> c.exp(Decimal('0.693147181'))
3858 Decimal("2.00000000")
3859 >>> c.exp(Decimal('+Infinity'))
3860 Decimal("Infinity")
3861 """
3862 return a.exp(context=self)
3863
3864 def fma(self, a, b, c):
3865 """Returns a multiplied by b, plus c.
3866
3867 The first two operands are multiplied together, using multiply,
3868 the third operand is then added to the result of that
3869 multiplication, using add, all with only one final rounding.
3870
3871 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3872 Decimal("22")
3873 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3874 Decimal("-8")
3875 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3876 Decimal("1.38435736E+12")
3877 """
3878 return a.fma(b, c, context=self)
3879
3880 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003881 """Return True if the operand is canonical; otherwise return False.
3882
3883 Currently, the encoding of a Decimal instance is always
3884 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003885
3886 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003887 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003888 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003889 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003890
3891 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003892 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003893
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003894 A Decimal instance is considered finite if it is neither
3895 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003896
3897 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003898 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003899 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003900 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003901 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003902 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003903 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003904 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003905 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003906 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003907 """
3908 return a.is_finite()
3909
3910 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003911 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003912
3913 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003914 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003915 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003916 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003917 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003918 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003919 """
3920 return a.is_infinite()
3921
3922 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003923 """Return True if the operand is a qNaN or sNaN;
3924 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003925
3926 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003927 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003928 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003929 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003930 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003931 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003932 """
3933 return a.is_nan()
3934
3935 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003936 """Return True if the operand is a normal number;
3937 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003938
3939 >>> c = ExtendedContext.copy()
3940 >>> c.Emin = -999
3941 >>> c.Emax = 999
3942 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003943 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003944 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003945 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003946 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003947 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003948 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003949 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003950 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003951 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003952 """
3953 return a.is_normal(context=self)
3954
3955 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003956 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003957
3958 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003959 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003960 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003961 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003962 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003963 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003964 """
3965 return a.is_qnan()
3966
3967 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003968 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003969
3970 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003971 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003972 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003973 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003974 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003975 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003976 """
3977 return a.is_signed()
3978
3979 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003980 """Return True if the operand is a signaling NaN;
3981 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003982
3983 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003984 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003985 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003986 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003987 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003988 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003989 """
3990 return a.is_snan()
3991
3992 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003993 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003994
3995 >>> c = ExtendedContext.copy()
3996 >>> c.Emin = -999
3997 >>> c.Emax = 999
3998 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003999 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004000 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004001 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004002 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004003 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004004 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004005 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004006 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004007 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004008 """
4009 return a.is_subnormal(context=self)
4010
4011 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004012 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004013
4014 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004015 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004016 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004017 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004018 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004019 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004020 """
4021 return a.is_zero()
4022
4023 def ln(self, a):
4024 """Returns the natural (base e) logarithm of the operand.
4025
4026 >>> c = ExtendedContext.copy()
4027 >>> c.Emin = -999
4028 >>> c.Emax = 999
4029 >>> c.ln(Decimal('0'))
4030 Decimal("-Infinity")
4031 >>> c.ln(Decimal('1.000'))
4032 Decimal("0")
4033 >>> c.ln(Decimal('2.71828183'))
4034 Decimal("1.00000000")
4035 >>> c.ln(Decimal('10'))
4036 Decimal("2.30258509")
4037 >>> c.ln(Decimal('+Infinity'))
4038 Decimal("Infinity")
4039 """
4040 return a.ln(context=self)
4041
4042 def log10(self, a):
4043 """Returns the base 10 logarithm of the operand.
4044
4045 >>> c = ExtendedContext.copy()
4046 >>> c.Emin = -999
4047 >>> c.Emax = 999
4048 >>> c.log10(Decimal('0'))
4049 Decimal("-Infinity")
4050 >>> c.log10(Decimal('0.001'))
4051 Decimal("-3")
4052 >>> c.log10(Decimal('1.000'))
4053 Decimal("0")
4054 >>> c.log10(Decimal('2'))
4055 Decimal("0.301029996")
4056 >>> c.log10(Decimal('10'))
4057 Decimal("1")
4058 >>> c.log10(Decimal('70'))
4059 Decimal("1.84509804")
4060 >>> c.log10(Decimal('+Infinity'))
4061 Decimal("Infinity")
4062 """
4063 return a.log10(context=self)
4064
4065 def logb(self, a):
4066 """ Returns the exponent of the magnitude of the operand's MSD.
4067
4068 The result is the integer which is the exponent of the magnitude
4069 of the most significant digit of the operand (as though the
4070 operand were truncated to a single digit while maintaining the
4071 value of that digit and without limiting the resulting exponent).
4072
4073 >>> ExtendedContext.logb(Decimal('250'))
4074 Decimal("2")
4075 >>> ExtendedContext.logb(Decimal('2.50'))
4076 Decimal("0")
4077 >>> ExtendedContext.logb(Decimal('0.03'))
4078 Decimal("-2")
4079 >>> ExtendedContext.logb(Decimal('0'))
4080 Decimal("-Infinity")
4081 """
4082 return a.logb(context=self)
4083
4084 def logical_and(self, a, b):
4085 """Applies the logical operation 'and' between each operand's digits.
4086
4087 The operands must be both logical numbers.
4088
4089 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4090 Decimal("0")
4091 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4092 Decimal("0")
4093 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4094 Decimal("0")
4095 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4096 Decimal("1")
4097 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4098 Decimal("1000")
4099 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4100 Decimal("10")
4101 """
4102 return a.logical_and(b, context=self)
4103
4104 def logical_invert(self, a):
4105 """Invert all the digits in the operand.
4106
4107 The operand must be a logical number.
4108
4109 >>> ExtendedContext.logical_invert(Decimal('0'))
4110 Decimal("111111111")
4111 >>> ExtendedContext.logical_invert(Decimal('1'))
4112 Decimal("111111110")
4113 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4114 Decimal("0")
4115 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4116 Decimal("10101010")
4117 """
4118 return a.logical_invert(context=self)
4119
4120 def logical_or(self, a, b):
4121 """Applies the logical operation 'or' between each operand's digits.
4122
4123 The operands must be both logical numbers.
4124
4125 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4126 Decimal("0")
4127 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4128 Decimal("1")
4129 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4130 Decimal("1")
4131 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4132 Decimal("1")
4133 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4134 Decimal("1110")
4135 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4136 Decimal("1110")
4137 """
4138 return a.logical_or(b, context=self)
4139
4140 def logical_xor(self, a, b):
4141 """Applies the logical operation 'xor' between each operand's digits.
4142
4143 The operands must be both logical numbers.
4144
4145 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4146 Decimal("0")
4147 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4148 Decimal("1")
4149 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4150 Decimal("1")
4151 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4152 Decimal("0")
4153 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4154 Decimal("110")
4155 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4156 Decimal("1101")
4157 """
4158 return a.logical_xor(b, context=self)
4159
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004160 def max(self, a,b):
4161 """max compares two values numerically and returns the maximum.
4162
4163 If either operand is a NaN then the general rules apply.
4164 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004165 operation. If they are numerically equal then the left-hand operand
4166 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004167 infinity) of the two operands is chosen as the result.
4168
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004169 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004170 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004171 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004172 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004173 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004174 Decimal("1")
4175 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4176 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004177 """
4178 return a.max(b, context=self)
4179
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004180 def max_mag(self, a, b):
4181 """Compares the values numerically with their sign ignored."""
4182 return a.max_mag(b, context=self)
4183
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004184 def min(self, a,b):
4185 """min compares two values numerically and returns the minimum.
4186
4187 If either operand is a NaN then the general rules apply.
4188 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004189 operation. If they are numerically equal then the left-hand operand
4190 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004191 infinity) of the two operands is chosen as the result.
4192
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004193 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004194 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004195 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004196 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004197 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004198 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004199 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4200 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004201 """
4202 return a.min(b, context=self)
4203
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004204 def min_mag(self, a, b):
4205 """Compares the values numerically with their sign ignored."""
4206 return a.min_mag(b, context=self)
4207
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004208 def minus(self, a):
4209 """Minus corresponds to unary prefix minus in Python.
4210
4211 The operation is evaluated using the same rules as subtract; the
4212 operation minus(a) is calculated as subtract('0', a) where the '0'
4213 has the same exponent as the operand.
4214
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004215 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004216 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004217 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004218 Decimal("1.3")
4219 """
4220 return a.__neg__(context=self)
4221
4222 def multiply(self, a, b):
4223 """multiply multiplies two operands.
4224
4225 If either operand is a special value then the general rules apply.
4226 Otherwise, the operands are multiplied together ('long multiplication'),
4227 resulting in a number which may be as long as the sum of the lengths
4228 of the two operands.
4229
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004230 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004231 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004232 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004233 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004234 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004235 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004236 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004237 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004238 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004239 Decimal("4.28135971E+11")
4240 """
4241 return a.__mul__(b, context=self)
4242
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004243 def next_minus(self, a):
4244 """Returns the largest representable number smaller than a.
4245
4246 >>> c = ExtendedContext.copy()
4247 >>> c.Emin = -999
4248 >>> c.Emax = 999
4249 >>> ExtendedContext.next_minus(Decimal('1'))
4250 Decimal("0.999999999")
4251 >>> c.next_minus(Decimal('1E-1007'))
4252 Decimal("0E-1007")
4253 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4254 Decimal("-1.00000004")
4255 >>> c.next_minus(Decimal('Infinity'))
4256 Decimal("9.99999999E+999")
4257 """
4258 return a.next_minus(context=self)
4259
4260 def next_plus(self, a):
4261 """Returns the smallest representable number larger than a.
4262
4263 >>> c = ExtendedContext.copy()
4264 >>> c.Emin = -999
4265 >>> c.Emax = 999
4266 >>> ExtendedContext.next_plus(Decimal('1'))
4267 Decimal("1.00000001")
4268 >>> c.next_plus(Decimal('-1E-1007'))
4269 Decimal("-0E-1007")
4270 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4271 Decimal("-1.00000002")
4272 >>> c.next_plus(Decimal('-Infinity'))
4273 Decimal("-9.99999999E+999")
4274 """
4275 return a.next_plus(context=self)
4276
4277 def next_toward(self, a, b):
4278 """Returns the number closest to a, in direction towards b.
4279
4280 The result is the closest representable number from the first
4281 operand (but not the first operand) that is in the direction
4282 towards the second operand, unless the operands have the same
4283 value.
4284
4285 >>> c = ExtendedContext.copy()
4286 >>> c.Emin = -999
4287 >>> c.Emax = 999
4288 >>> c.next_toward(Decimal('1'), Decimal('2'))
4289 Decimal("1.00000001")
4290 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4291 Decimal("-0E-1007")
4292 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4293 Decimal("-1.00000002")
4294 >>> c.next_toward(Decimal('1'), Decimal('0'))
4295 Decimal("0.999999999")
4296 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4297 Decimal("0E-1007")
4298 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4299 Decimal("-1.00000004")
4300 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4301 Decimal("-0.00")
4302 """
4303 return a.next_toward(b, context=self)
4304
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004305 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004306 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004307
4308 Essentially a plus operation with all trailing zeros removed from the
4309 result.
4310
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004311 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004312 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004313 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004314 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004315 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004316 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004317 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004318 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004319 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004320 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004321 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004322 Decimal("0")
4323 """
4324 return a.normalize(context=self)
4325
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004326 def number_class(self, a):
4327 """Returns an indication of the class of the operand.
4328
4329 The class is one of the following strings:
4330 -sNaN
4331 -NaN
4332 -Infinity
4333 -Normal
4334 -Subnormal
4335 -Zero
4336 +Zero
4337 +Subnormal
4338 +Normal
4339 +Infinity
4340
4341 >>> c = Context(ExtendedContext)
4342 >>> c.Emin = -999
4343 >>> c.Emax = 999
4344 >>> c.number_class(Decimal('Infinity'))
4345 '+Infinity'
4346 >>> c.number_class(Decimal('1E-10'))
4347 '+Normal'
4348 >>> c.number_class(Decimal('2.50'))
4349 '+Normal'
4350 >>> c.number_class(Decimal('0.1E-999'))
4351 '+Subnormal'
4352 >>> c.number_class(Decimal('0'))
4353 '+Zero'
4354 >>> c.number_class(Decimal('-0'))
4355 '-Zero'
4356 >>> c.number_class(Decimal('-0.1E-999'))
4357 '-Subnormal'
4358 >>> c.number_class(Decimal('-1E-10'))
4359 '-Normal'
4360 >>> c.number_class(Decimal('-2.50'))
4361 '-Normal'
4362 >>> c.number_class(Decimal('-Infinity'))
4363 '-Infinity'
4364 >>> c.number_class(Decimal('NaN'))
4365 'NaN'
4366 >>> c.number_class(Decimal('-NaN'))
4367 'NaN'
4368 >>> c.number_class(Decimal('sNaN'))
4369 'sNaN'
4370 """
4371 return a.number_class(context=self)
4372
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004373 def plus(self, a):
4374 """Plus corresponds to unary prefix plus in Python.
4375
4376 The operation is evaluated using the same rules as add; the
4377 operation plus(a) is calculated as add('0', a) where the '0'
4378 has the same exponent as the operand.
4379
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004380 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004381 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004382 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004383 Decimal("-1.3")
4384 """
4385 return a.__pos__(context=self)
4386
4387 def power(self, a, b, modulo=None):
4388 """Raises a to the power of b, to modulo if given.
4389
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004390 With two arguments, compute a**b. If a is negative then b
4391 must be integral. The result will be inexact unless b is
4392 integral and the result is finite and can be expressed exactly
4393 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004394
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004395 With three arguments, compute (a**b) % modulo. For the
4396 three argument form, the following restrictions on the
4397 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004398
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004399 - all three arguments must be integral
4400 - b must be nonnegative
4401 - at least one of a or b must be nonzero
4402 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004403
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004404 The result of pow(a, b, modulo) is identical to the result
4405 that would be obtained by computing (a**b) % modulo with
4406 unbounded precision, but is computed more efficiently. It is
4407 always exact.
4408
4409 >>> c = ExtendedContext.copy()
4410 >>> c.Emin = -999
4411 >>> c.Emax = 999
4412 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004413 Decimal("8")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004414 >>> c.power(Decimal('-2'), Decimal('3'))
4415 Decimal("-8")
4416 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004417 Decimal("0.125")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004418 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004419 Decimal("69.7575744")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004420 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4421 Decimal("2.00000000")
4422 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004423 Decimal("0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004424 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004425 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004426 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004427 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004428 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004429 Decimal("-0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004430 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004431 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004432 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004433 Decimal("-Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004434 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004435 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004436 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004437 Decimal("NaN")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004438
4439 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4440 Decimal("11")
4441 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4442 Decimal("-11")
4443 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4444 Decimal("1")
4445 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4446 Decimal("11")
4447 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4448 Decimal("11729830")
4449 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4450 Decimal("-0")
4451 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4452 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004453 """
4454 return a.__pow__(b, modulo, context=self)
4455
4456 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004457 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004458
4459 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004460 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004461 exponent is being increased), multiplied by a positive power of ten (if
4462 the exponent is being decreased), or is unchanged (if the exponent is
4463 already equal to that of the right-hand operand).
4464
4465 Unlike other operations, if the length of the coefficient after the
4466 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004467 operation condition is raised. This guarantees that, unless there is
4468 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004469 equal to that of the right-hand operand.
4470
4471 Also unlike other operations, quantize will never raise Underflow, even
4472 if the result is subnormal and inexact.
4473
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004474 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004475 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004476 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004477 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004478 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004479 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004480 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004481 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004482 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004483 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004484 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004485 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004486 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004487 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004488 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004489 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004490 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004491 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004492 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004493 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004494 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004495 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004496 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004497 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004498 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004499 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004500 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004501 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004502 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004503 Decimal("2E+2")
4504 """
4505 return a.quantize(b, context=self)
4506
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004507 def radix(self):
4508 """Just returns 10, as this is Decimal, :)
4509
4510 >>> ExtendedContext.radix()
4511 Decimal("10")
4512 """
4513 return Decimal(10)
4514
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004515 def remainder(self, a, b):
4516 """Returns the remainder from integer division.
4517
4518 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004519 calculating integer division as described for divide-integer, rounded
4520 to precision digits if necessary. The sign of the result, if
4521 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004522
4523 This operation will fail under the same conditions as integer division
4524 (that is, if integer division on the same two operands would fail, the
4525 remainder cannot be calculated).
4526
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004527 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004528 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004529 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004530 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004531 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004532 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004533 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004534 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004535 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004536 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004537 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004538 Decimal("1.0")
4539 """
4540 return a.__mod__(b, context=self)
4541
4542 def remainder_near(self, a, b):
4543 """Returns to be "a - b * n", where n is the integer nearest the exact
4544 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004545 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004546 sign of a.
4547
4548 This operation will fail under the same conditions as integer division
4549 (that is, if integer division on the same two operands would fail, the
4550 remainder cannot be calculated).
4551
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004552 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004553 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004554 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004555 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004556 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004557 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004558 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004559 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004560 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004561 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004562 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004563 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004564 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004565 Decimal("-0.3")
4566 """
4567 return a.remainder_near(b, context=self)
4568
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004569 def rotate(self, a, b):
4570 """Returns a rotated copy of a, b times.
4571
4572 The coefficient of the result is a rotated copy of the digits in
4573 the coefficient of the first operand. The number of places of
4574 rotation is taken from the absolute value of the second operand,
4575 with the rotation being to the left if the second operand is
4576 positive or to the right otherwise.
4577
4578 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4579 Decimal("400000003")
4580 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4581 Decimal("12")
4582 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4583 Decimal("891234567")
4584 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4585 Decimal("123456789")
4586 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4587 Decimal("345678912")
4588 """
4589 return a.rotate(b, context=self)
4590
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004591 def same_quantum(self, a, b):
4592 """Returns True if the two operands have the same exponent.
4593
4594 The result is never affected by either the sign or the coefficient of
4595 either operand.
4596
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004597 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004598 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004599 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004600 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004601 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004602 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004603 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004604 True
4605 """
4606 return a.same_quantum(b)
4607
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004608 def scaleb (self, a, b):
4609 """Returns the first operand after adding the second value its exp.
4610
4611 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4612 Decimal("0.0750")
4613 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4614 Decimal("7.50")
4615 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4616 Decimal("7.50E+3")
4617 """
4618 return a.scaleb (b, context=self)
4619
4620 def shift(self, a, b):
4621 """Returns a shifted copy of a, b times.
4622
4623 The coefficient of the result is a shifted copy of the digits
4624 in the coefficient of the first operand. The number of places
4625 to shift is taken from the absolute value of the second operand,
4626 with the shift being to the left if the second operand is
4627 positive or to the right otherwise. Digits shifted into the
4628 coefficient are zeros.
4629
4630 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4631 Decimal("400000000")
4632 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4633 Decimal("0")
4634 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4635 Decimal("1234567")
4636 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4637 Decimal("123456789")
4638 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4639 Decimal("345678900")
4640 """
4641 return a.shift(b, context=self)
4642
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004643 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004644 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004645
4646 If the result must be inexact, it is rounded using the round-half-even
4647 algorithm.
4648
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004649 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004650 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004651 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004652 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004653 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004654 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004655 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004656 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004657 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004658 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004659 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004660 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004661 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004662 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004663 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004664 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004665 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004666 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004667 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004668 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004669 """
4670 return a.sqrt(context=self)
4671
4672 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004673 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004674
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004675 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004676 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004677 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004678 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004679 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004680 Decimal("-0.77")
4681 """
4682 return a.__sub__(b, context=self)
4683
4684 def to_eng_string(self, a):
4685 """Converts a number to a string, using scientific notation.
4686
4687 The operation is not affected by the context.
4688 """
4689 return a.to_eng_string(context=self)
4690
4691 def to_sci_string(self, a):
4692 """Converts a number to a string, using scientific notation.
4693
4694 The operation is not affected by the context.
4695 """
4696 return a.__str__(context=self)
4697
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004698 def to_integral_exact(self, a):
4699 """Rounds to an integer.
4700
4701 When the operand has a negative exponent, the result is the same
4702 as using the quantize() operation using the given operand as the
4703 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4704 of the operand as the precision setting; Inexact and Rounded flags
4705 are allowed in this operation. The rounding mode is taken from the
4706 context.
4707
4708 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4709 Decimal("2")
4710 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4711 Decimal("100")
4712 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4713 Decimal("100")
4714 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4715 Decimal("102")
4716 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4717 Decimal("-102")
4718 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4719 Decimal("1.0E+6")
4720 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4721 Decimal("7.89E+77")
4722 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4723 Decimal("-Infinity")
4724 """
4725 return a.to_integral_exact(context=self)
4726
4727 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004728 """Rounds to an integer.
4729
4730 When the operand has a negative exponent, the result is the same
4731 as using the quantize() operation using the given operand as the
4732 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4733 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004734 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004735
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004736 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004737 Decimal("2")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004738 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004739 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004740 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004741 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004742 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004743 Decimal("102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004744 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004745 Decimal("-102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004746 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004747 Decimal("1.0E+6")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004748 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004749 Decimal("7.89E+77")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004750 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004751 Decimal("-Infinity")
4752 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004753 return a.to_integral_value(context=self)
4754
4755 # the method name changed, but we provide also the old one, for compatibility
4756 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004757
4758class _WorkRep(object):
4759 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004760 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004761 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004762 # exp: None, int, or string
4763
4764 def __init__(self, value=None):
4765 if value is None:
4766 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004767 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004768 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004769 elif isinstance(value, Decimal):
4770 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00004771 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004772 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004773 else:
4774 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004775 self.sign = value[0]
4776 self.int = value[1]
4777 self.exp = value[2]
4778
4779 def __repr__(self):
4780 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4781
4782 __str__ = __repr__
4783
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004784
4785
4786def _normalize(op1, op2, shouldround = 0, prec = 0):
4787 """Normalizes op1, op2 to have the same exp and length of coefficient.
4788
4789 Done during addition.
4790 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004791 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004792 tmp = op2
4793 other = op1
4794 else:
4795 tmp = op1
4796 other = op2
4797
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004798 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4799 # Then adding 10**exp to tmp has the same effect (after rounding)
4800 # as adding any positive quantity smaller than 10**exp; similarly
4801 # for subtraction. So if other is smaller than 10**exp we replace
4802 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4803 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004804 tmp_len = len(str(tmp.int))
4805 other_len = len(str(other.int))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004806 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4807 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004808 other.int = 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004809 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004810
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004811 tmp.int *= 10 ** (tmp.exp - other.exp)
4812 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004813 return op1, op2
4814
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004815##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004816
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004817# This function from Tim Peters was taken from here:
4818# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4819# The correction being in the function definition is for speed, and
4820# the whole function is not resolved with math.log because of avoiding
4821# the use of floats.
4822def _nbits(n, correction = {
4823 '0': 4, '1': 3, '2': 2, '3': 2,
4824 '4': 1, '5': 1, '6': 1, '7': 1,
4825 '8': 0, '9': 0, 'a': 0, 'b': 0,
4826 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4827 """Number of bits in binary representation of the positive integer n,
4828 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004829 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004830 if n < 0:
4831 raise ValueError("The argument to _nbits should be nonnegative.")
4832 hex_n = "%x" % n
4833 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004834
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004835def _sqrt_nearest(n, a):
4836 """Closest integer to the square root of the positive integer n. a is
4837 an initial approximation to the square root. Any positive integer
4838 will do for a, but the closer a is to the square root of n the
4839 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004840
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004841 """
4842 if n <= 0 or a <= 0:
4843 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4844
4845 b=0
4846 while a != b:
4847 b, a = a, a--n//a>>1
4848 return a
4849
4850def _rshift_nearest(x, shift):
4851 """Given an integer x and a nonnegative integer shift, return closest
4852 integer to x / 2**shift; use round-to-even in case of a tie.
4853
4854 """
4855 b, q = 1 << shift, x >> shift
4856 return q + (2*(x & (b-1)) + (q&1) > b)
4857
4858def _div_nearest(a, b):
4859 """Closest integer to a/b, a and b positive integers; rounds to even
4860 in the case of a tie.
4861
4862 """
4863 q, r = divmod(a, b)
4864 return q + (2*r + (q&1) > b)
4865
4866def _ilog(x, M, L = 8):
4867 """Integer approximation to M*log(x/M), with absolute error boundable
4868 in terms only of x/M.
4869
4870 Given positive integers x and M, return an integer approximation to
4871 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4872 between the approximation and the exact result is at most 22. For
4873 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4874 both cases these are upper bounds on the error; it will usually be
4875 much smaller."""
4876
4877 # The basic algorithm is the following: let log1p be the function
4878 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4879 # the reduction
4880 #
4881 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4882 #
4883 # repeatedly until the argument to log1p is small (< 2**-L in
4884 # absolute value). For small y we can use the Taylor series
4885 # expansion
4886 #
4887 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4888 #
4889 # truncating at T such that y**T is small enough. The whole
4890 # computation is carried out in a form of fixed-point arithmetic,
4891 # with a real number z being represented by an integer
4892 # approximation to z*M. To avoid loss of precision, the y below
4893 # is actually an integer approximation to 2**R*y*M, where R is the
4894 # number of reductions performed so far.
4895
4896 y = x-M
4897 # argument reduction; R = number of reductions performed
4898 R = 0
4899 while (R <= L and abs(y) << L-R >= M or
4900 R > L and abs(y) >> R-L >= M):
4901 y = _div_nearest((M*y) << 1,
4902 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4903 R += 1
4904
4905 # Taylor series with T terms
4906 T = -int(-10*len(str(M))//(3*L))
4907 yshift = _rshift_nearest(y, R)
4908 w = _div_nearest(M, T)
4909 for k in range(T-1, 0, -1):
4910 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4911
4912 return _div_nearest(w*y, M)
4913
4914def _dlog10(c, e, p):
4915 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4916 approximation to 10**p * log10(c*10**e), with an absolute error of
4917 at most 1. Assumes that c*10**e is not exactly 1."""
4918
4919 # increase precision by 2; compensate for this by dividing
4920 # final result by 100
4921 p += 2
4922
4923 # write c*10**e as d*10**f with either:
4924 # f >= 0 and 1 <= d <= 10, or
4925 # f <= 0 and 0.1 <= d <= 1.
4926 # Thus for c*10**e close to 1, f = 0
4927 l = len(str(c))
4928 f = e+l - (e+l >= 1)
4929
4930 if p > 0:
4931 M = 10**p
4932 k = e+p-f
4933 if k >= 0:
4934 c *= 10**k
4935 else:
4936 c = _div_nearest(c, 10**-k)
4937
4938 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004939 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004940 log_d = _div_nearest(log_d*M, log_10)
4941 log_tenpower = f*M # exact
4942 else:
4943 log_d = 0 # error < 2.31
4944 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4945
4946 return _div_nearest(log_tenpower+log_d, 100)
4947
4948def _dlog(c, e, p):
4949 """Given integers c, e and p with c > 0, compute an integer
4950 approximation to 10**p * log(c*10**e), with an absolute error of
4951 at most 1. Assumes that c*10**e is not exactly 1."""
4952
4953 # Increase precision by 2. The precision increase is compensated
4954 # for at the end with a division by 100.
4955 p += 2
4956
4957 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4958 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4959 # as 10**p * log(d) + 10**p*f * log(10).
4960 l = len(str(c))
4961 f = e+l - (e+l >= 1)
4962
4963 # compute approximation to 10**p*log(d), with error < 27
4964 if p > 0:
4965 k = e+p-f
4966 if k >= 0:
4967 c *= 10**k
4968 else:
4969 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4970
4971 # _ilog magnifies existing error in c by a factor of at most 10
4972 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4973 else:
4974 # p <= 0: just approximate the whole thing by 0; error < 2.31
4975 log_d = 0
4976
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004977 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004978 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004979 extra = len(str(abs(f)))-1
4980 if p + extra >= 0:
4981 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4982 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4983 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004984 else:
4985 f_log_ten = 0
4986 else:
4987 f_log_ten = 0
4988
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004989 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004990 return _div_nearest(f_log_ten + log_d, 100)
4991
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004992class _Log10Memoize(object):
4993 """Class to compute, store, and allow retrieval of, digits of the
4994 constant log(10) = 2.302585.... This constant is needed by
4995 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4996 def __init__(self):
4997 self.digits = "23025850929940456840179914546843642076011014886"
4998
4999 def getdigits(self, p):
5000 """Given an integer p >= 0, return floor(10**p)*log(10).
5001
5002 For example, self.getdigits(3) returns 2302.
5003 """
5004 # digits are stored as a string, for quick conversion to
5005 # integer in the case that we've already computed enough
5006 # digits; the stored digits should always be correct
5007 # (truncated, not rounded to nearest).
5008 if p < 0:
5009 raise ValueError("p should be nonnegative")
5010
5011 if p >= len(self.digits):
5012 # compute p+3, p+6, p+9, ... digits; continue until at
5013 # least one of the extra digits is nonzero
5014 extra = 3
5015 while True:
5016 # compute p+extra digits, correct to within 1ulp
5017 M = 10**(p+extra+2)
5018 digits = str(_div_nearest(_ilog(10*M, M), 100))
5019 if digits[-extra:] != '0'*extra:
5020 break
5021 extra += 3
5022 # keep all reliable digits so far; remove trailing zeros
5023 # and next nonzero digit
5024 self.digits = digits.rstrip('0')[:-1]
5025 return int(self.digits[:p+1])
5026
5027_log10_digits = _Log10Memoize().getdigits
5028
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005029def _iexp(x, M, L=8):
5030 """Given integers x and M, M > 0, such that x/M is small in absolute
5031 value, compute an integer approximation to M*exp(x/M). For 0 <=
5032 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5033 is usually much smaller)."""
5034
5035 # Algorithm: to compute exp(z) for a real number z, first divide z
5036 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5037 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5038 # series
5039 #
5040 # expm1(x) = x + x**2/2! + x**3/3! + ...
5041 #
5042 # Now use the identity
5043 #
5044 # expm1(2x) = expm1(x)*(expm1(x)+2)
5045 #
5046 # R times to compute the sequence expm1(z/2**R),
5047 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5048
5049 # Find R such that x/2**R/M <= 2**-L
5050 R = _nbits((x<<L)//M)
5051
5052 # Taylor series. (2**L)**T > M
5053 T = -int(-10*len(str(M))//(3*L))
5054 y = _div_nearest(x, T)
5055 Mshift = M<<R
5056 for i in range(T-1, 0, -1):
5057 y = _div_nearest(x*(Mshift + y), Mshift * i)
5058
5059 # Expansion
5060 for k in range(R-1, -1, -1):
5061 Mshift = M<<(k+2)
5062 y = _div_nearest(y*(y+Mshift), Mshift)
5063
5064 return M+y
5065
5066def _dexp(c, e, p):
5067 """Compute an approximation to exp(c*10**e), with p decimal places of
5068 precision.
5069
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005070 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005071
5072 10**(p-1) <= d <= 10**p, and
5073 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5074
5075 In other words, d*10**f is an approximation to exp(c*10**e) with p
5076 digits of precision, and with an error in d of at most 1. This is
5077 almost, but not quite, the same as the error being < 1ulp: when d
5078 = 10**(p-1) the error could be up to 10 ulp."""
5079
5080 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5081 p += 2
5082
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005083 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005084 extra = max(0, e + len(str(c)) - 1)
5085 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005086
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005087 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005088 # rounding down
5089 shift = e+q
5090 if shift >= 0:
5091 cshift = c*10**shift
5092 else:
5093 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005094 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005095
5096 # reduce remainder back to original precision
5097 rem = _div_nearest(rem, 10**extra)
5098
5099 # error in result of _iexp < 120; error after division < 0.62
5100 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5101
5102def _dpower(xc, xe, yc, ye, p):
5103 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5104 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5105
5106 10**(p-1) <= c <= 10**p, and
5107 (c-1)*10**e < x**y < (c+1)*10**e
5108
5109 in other words, c*10**e is an approximation to x**y with p digits
5110 of precision, and with an error in c of at most 1. (This is
5111 almost, but not quite, the same as the error being < 1ulp: when c
5112 == 10**(p-1) we can only guarantee error < 10ulp.)
5113
5114 We assume that: x is positive and not equal to 1, and y is nonzero.
5115 """
5116
5117 # Find b such that 10**(b-1) <= |y| <= 10**b
5118 b = len(str(abs(yc))) + ye
5119
5120 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5121 lxc = _dlog(xc, xe, p+b+1)
5122
5123 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5124 shift = ye-b
5125 if shift >= 0:
5126 pc = lxc*yc*10**shift
5127 else:
5128 pc = _div_nearest(lxc*yc, 10**-shift)
5129
5130 if pc == 0:
5131 # we prefer a result that isn't exactly 1; this makes it
5132 # easier to compute a correctly rounded result in __pow__
5133 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5134 coeff, exp = 10**(p-1)+1, 1-p
5135 else:
5136 coeff, exp = 10**p-1, -p
5137 else:
5138 coeff, exp = _dexp(pc, -(p+1), p+1)
5139 coeff = _div_nearest(coeff, 10)
5140 exp += 1
5141
5142 return coeff, exp
5143
5144def _log10_lb(c, correction = {
5145 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5146 '6': 23, '7': 16, '8': 10, '9': 5}):
5147 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5148 if c <= 0:
5149 raise ValueError("The argument to _log10_lb should be nonnegative.")
5150 str_c = str(c)
5151 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005152
Guido van Rossumd8faa362007-04-27 19:54:29 +00005153##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005154
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005155def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005156 """Convert other to Decimal.
5157
5158 Verifies that it's ok to use in an implicit construction.
5159 """
5160 if isinstance(other, Decimal):
5161 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005162 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005163 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005164 if raiseit:
5165 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005166 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005167
Guido van Rossumd8faa362007-04-27 19:54:29 +00005168##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005169
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005170# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005171# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005172
5173DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005174 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005175 traps=[DivisionByZero, Overflow, InvalidOperation],
5176 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005177 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005178 Emax=999999999,
5179 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005180 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005181)
5182
5183# Pre-made alternate contexts offered by the specification
5184# Don't change these; the user should be able to select these
5185# contexts and be able to reproduce results from other implementations
5186# of the spec.
5187
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005188BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005189 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005190 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5191 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005192)
5193
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005194ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005195 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005196 traps=[],
5197 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005198)
5199
5200
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005201##### crud for parsing strings #############################################
5202import re
5203
5204# Regular expression used for parsing numeric strings. Additional
5205# comments:
5206#
5207# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5208# whitespace. But note that the specification disallows whitespace in
5209# a numeric string.
5210#
5211# 2. For finite numbers (not infinities and NaNs) the body of the
5212# number between the optional sign and the optional exponent must have
5213# at least one decimal digit, possibly after the decimal point. The
5214# lookahead expression '(?=\d|\.\d)' checks this.
5215#
5216# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5217# other meaning for \d than the numbers [0-9].
5218
5219import re
5220_parser = re.compile(r""" # A numeric string consists of:
5221# \s*
5222 (?P<sign>[-+])? # an optional sign, followed by either...
5223 (
5224 (?=\d|\.\d) # ...a number (with at least one digit)
5225 (?P<int>\d*) # consisting of a (possibly empty) integer part
5226 (\.(?P<frac>\d*))? # followed by an optional fractional part
5227 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5228 |
5229 Inf(inity)? # ...an infinity, or...
5230 |
5231 (?P<signal>s)? # ...an (optionally signaling)
5232 NaN # NaN
5233 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5234 )
5235# \s*
5236 $
5237""", re.VERBOSE | re.IGNORECASE).match
5238
5239del re
5240
5241
Guido van Rossumd8faa362007-04-27 19:54:29 +00005242##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005243
Guido van Rossumd8faa362007-04-27 19:54:29 +00005244# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005245Inf = Decimal('Inf')
5246negInf = Decimal('-Inf')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005247NaN = Decimal('NaN')
5248Dec_0 = Decimal(0)
5249Dec_p1 = Decimal(1)
5250Dec_n1 = Decimal(-1)
5251Dec_p2 = Decimal(2)
5252Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005253
Guido van Rossumd8faa362007-04-27 19:54:29 +00005254# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005255Infsign = (Inf, negInf)
5256
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005257
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005258
5259if __name__ == '__main__':
5260 import doctest, sys
5261 doctest.testmod(sys.modules[__name__])