blob: ba335bba469370fce915a741db25595371cc213c [file] [log] [blame]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001# Copyright (c) 2004 Python Software Foundation.
2# All rights reserved.
3
4# Written by Eric Price <eprice at tjhsst.edu>
5# and Facundo Batista <facundo at taniquetil.com.ar>
6# and Raymond Hettinger <python at rcn.com>
Fred Drake1f34eb12004-07-01 14:28:36 +00007# and Aahz <aahz at pobox.com>
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00008# and Tim Peters
9
Raymond Hettinger27dbcf22004-08-19 22:39:55 +000010# This module is currently Py2.3 compatible and should be kept that way
11# unless a major compelling advantage arises. IOW, 2.3 compatibility is
12# strongly preferred, but not guaranteed.
13
14# Also, this module should be kept in sync with the latest updates of
15# the IBM specification as it evolves. Those updates will be treated
16# as bug fixes (deviation from the spec is a compatibility, usability
17# bug) and will be backported. At this point the spec is stabilizing
18# and the updates are becoming fewer, smaller, and less significant.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000019
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000020"""
21This is a Py2.3 implementation of decimal floating point arithmetic based on
22the General Decimal Arithmetic Specification:
23
24 www2.hursley.ibm.com/decimal/decarith.html
25
Raymond Hettinger0ea241e2004-07-04 13:53:24 +000026and IEEE standard 854-1987:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000027
28 www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
29
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000030Decimal floating point has finite precision with arbitrarily large bounds.
31
Guido van Rossumd8faa362007-04-27 19:54:29 +000032The purpose of this module is to support arithmetic using familiar
33"schoolhouse" rules and to avoid some of the tricky representation
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000034issues associated with binary floating point. The package is especially
35useful for financial applications or for contexts where users have
36expectations that are at odds with binary floating point (for instance,
37in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
38of the expected Decimal("0.00") returned by decimal floating point).
39
40Here are some examples of using the decimal module:
41
42>>> from decimal import *
Raymond Hettingerbd7f76d2004-07-08 00:49:18 +000043>>> setcontext(ExtendedContext)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000044>>> Decimal(0)
45Decimal("0")
46>>> Decimal("1")
47Decimal("1")
48>>> Decimal("-.0123")
49Decimal("-0.0123")
50>>> Decimal(123456)
51Decimal("123456")
52>>> Decimal("123.45e12345678901234567890")
53Decimal("1.2345E+12345678901234567892")
54>>> Decimal("1.33") + Decimal("1.27")
55Decimal("2.60")
56>>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41")
57Decimal("-2.20")
58>>> dig = Decimal(1)
Guido van Rossum7131f842007-02-09 20:13:25 +000059>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000600.333333333
61>>> getcontext().prec = 18
Guido van Rossum7131f842007-02-09 20:13:25 +000062>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000630.333333333333333333
Guido van Rossum7131f842007-02-09 20:13:25 +000064>>> print(dig.sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000651
Guido van Rossum7131f842007-02-09 20:13:25 +000066>>> print(Decimal(3).sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000671.73205080756887729
Guido van Rossum7131f842007-02-09 20:13:25 +000068>>> print(Decimal(3) ** 123)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000694.85192780976896427E+58
70>>> inf = Decimal(1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000071>>> print(inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000072Infinity
73>>> neginf = Decimal(-1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000074>>> print(neginf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000075-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000076>>> print(neginf + inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000077NaN
Guido van Rossum7131f842007-02-09 20:13:25 +000078>>> print(neginf * inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000079-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000080>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000081Infinity
Raymond Hettingerbf440692004-07-10 14:14:37 +000082>>> getcontext().traps[DivisionByZero] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000083>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000084Traceback (most recent call last):
85 ...
86 ...
87 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +000088decimal.DivisionByZero: x / 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000089>>> c = Context()
Raymond Hettingerbf440692004-07-10 14:14:37 +000090>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000091>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000920
93>>> c.divide(Decimal(0), Decimal(0))
94Decimal("NaN")
Raymond Hettingerbf440692004-07-10 14:14:37 +000095>>> c.traps[InvalidOperation] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000096>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000098>>> c.flags[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000099>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000
Guido van Rossum7131f842007-02-09 20:13:25 +0000101>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000102Traceback (most recent call last):
103 ...
104 ...
105 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +0000106decimal.InvalidOperation: 0 / 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000107>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000109>>> c.flags[InvalidOperation] = 0
Raymond Hettingerbf440692004-07-10 14:14:37 +0000110>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000111>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000112NaN
Guido van Rossum7131f842007-02-09 20:13:25 +0000113>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141
115>>>
116"""
117
118__all__ = [
119 # Two major classes
120 'Decimal', 'Context',
121
122 # Contexts
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +0000123 'DefaultContext', 'BasicContext', 'ExtendedContext',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000124
125 # Exceptions
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +0000126 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
127 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000128
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000129 # Constants for use in setting up contexts
130 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000131 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000132
133 # Functions for manipulating contexts
Thomas Wouters89f507f2006-12-13 04:49:30 +0000134 'setcontext', 'getcontext', 'localcontext'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000135]
136
Guido van Rossuma13f4a12007-12-10 20:04:04 +0000137import numbers as _numbers
Raymond Hettingereb260842005-06-07 18:52:34 +0000138import copy as _copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000139
Guido van Rossumd8faa362007-04-27 19:54:29 +0000140# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000141ROUND_DOWN = 'ROUND_DOWN'
142ROUND_HALF_UP = 'ROUND_HALF_UP'
143ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
144ROUND_CEILING = 'ROUND_CEILING'
145ROUND_FLOOR = 'ROUND_FLOOR'
146ROUND_UP = 'ROUND_UP'
147ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000148ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000149
Guido van Rossumd8faa362007-04-27 19:54:29 +0000150# Rounding decision (not part of the public API)
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000151NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY
152ALWAYS_ROUND = 'ALWAYS_ROUND' # Every operation rounds at end.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000153
Guido van Rossumd8faa362007-04-27 19:54:29 +0000154# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000155
156class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000157 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000158
159 Used exceptions derive from this.
160 If an exception derives from another exception besides this (such as
161 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
162 called if the others are present. This isn't actually used for
163 anything, though.
164
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000165 handle -- Called when context._raise_error is called and the
166 trap_enabler is set. First argument is self, second is the
167 context. More arguments can be given, those being after
168 the explanation in _raise_error (For example,
169 context._raise_error(NewError, '(-x)!', self._sign) would
170 call NewError().handle(context, self._sign).)
171
172 To define a new exception, it should be sufficient to have it derive
173 from DecimalException.
174 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000175 def handle(self, context, *args):
176 pass
177
178
179class Clamped(DecimalException):
180 """Exponent of a 0 changed to fit bounds.
181
182 This occurs and signals clamped if the exponent of a result has been
183 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000184 representation. This may occur when the exponent of a zero result would
185 be outside the bounds of a representation, or when a large normal
186 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000187 this latter case, the exponent is reduced to fit and the corresponding
188 number of zero digits are appended to the coefficient ("fold-down").
189 """
190
191
192class InvalidOperation(DecimalException):
193 """An invalid operation was performed.
194
195 Various bad things cause this:
196
197 Something creates a signaling NaN
198 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000199 0 * (+-)INF
200 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000201 x % 0
202 (+-)INF % x
203 x._rescale( non-integer )
204 sqrt(-x) , x > 0
205 0 ** 0
206 x ** (non-integer)
207 x ** (+-)INF
208 An operand is invalid
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000209
210 The result of the operation after these is a quiet positive NaN,
211 except when the cause is a signaling NaN, in which case the result is
212 also a quiet NaN, but with the original sign, and an optional
213 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000214 """
215 def handle(self, context, *args):
216 if args:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000217 if args[0] == 1: # sNaN, must drop 's' but keep diagnostics
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000218 ans = _dec_from_triple(args[1]._sign, args[1]._int, 'n', True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000219 return ans._fix_nan(context)
220 elif args[0] == 2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000221 return _dec_from_triple(args[1], args[2], 'n', True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000222 return NaN
223
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000224
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000225class ConversionSyntax(InvalidOperation):
226 """Trying to convert badly formed string.
227
228 This occurs and signals invalid-operation if an string is being
229 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000230 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000231 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000232 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000233 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000234
235class DivisionByZero(DecimalException, ZeroDivisionError):
236 """Division by 0.
237
238 This occurs and signals division-by-zero if division of a finite number
239 by zero was attempted (during a divide-integer or divide operation, or a
240 power operation with negative right-hand operand), and the dividend was
241 not zero.
242
243 The result of the operation is [sign,inf], where sign is the exclusive
244 or of the signs of the operands for divide, or is 1 for an odd power of
245 -0, for power.
246 """
247
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000248 def handle(self, context, sign, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000249 return Infsign[sign]
250
251class DivisionImpossible(InvalidOperation):
252 """Cannot perform the division adequately.
253
254 This occurs and signals invalid-operation if the integer result of a
255 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000256 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000257 """
258
259 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000260 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000261
262class DivisionUndefined(InvalidOperation, ZeroDivisionError):
263 """Undefined result of division.
264
265 This occurs and signals invalid-operation if division by zero was
266 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000267 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000268 """
269
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000270 def handle(self, context, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000271 return NaN
272
273class Inexact(DecimalException):
274 """Had to round, losing information.
275
276 This occurs and signals inexact whenever the result of an operation is
277 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000278 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000279 result in all cases is unchanged.
280
281 The inexact signal may be tested (or trapped) to determine if a given
282 operation (or sequence of operations) was inexact.
283 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000284 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000285
286class InvalidContext(InvalidOperation):
287 """Invalid context. Unknown rounding, for example.
288
289 This occurs and signals invalid-operation if an invalid context was
Guido van Rossumd8faa362007-04-27 19:54:29 +0000290 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000291 on creation and either the precision exceeds the capability of the
292 underlying concrete representation or an unknown or unsupported rounding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000293 was specified. These aspects of the context need only be checked when
294 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000295 """
296
297 def handle(self, context, *args):
298 return NaN
299
300class Rounded(DecimalException):
301 """Number got rounded (not necessarily changed during rounding).
302
303 This occurs and signals rounded whenever the result of an operation is
304 rounded (that is, some zero or non-zero digits were discarded from the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000305 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000306 result in all cases is unchanged.
307
308 The rounded signal may be tested (or trapped) to determine if a given
309 operation (or sequence of operations) caused a loss of precision.
310 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000311 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000312
313class Subnormal(DecimalException):
314 """Exponent < Emin before rounding.
315
316 This occurs and signals subnormal whenever the result of a conversion or
317 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000318 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000319
320 The subnormal signal may be tested (or trapped) to determine if a given
321 or operation (or sequence of operations) yielded a subnormal result.
322 """
323 pass
324
325class Overflow(Inexact, Rounded):
326 """Numerical overflow.
327
328 This occurs and signals overflow if the adjusted exponent of a result
329 (from a conversion or from an operation that is not an attempt to divide
330 by zero), after rounding, would be greater than the largest value that
331 can be handled by the implementation (the value Emax).
332
333 The result depends on the rounding mode:
334
335 For round-half-up and round-half-even (and for round-half-down and
336 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000337 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000338 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000339 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000340 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000341 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000342 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000343 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000344 will also be raised.
345 """
346
347 def handle(self, context, sign, *args):
348 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000349 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000350 return Infsign[sign]
351 if sign == 0:
352 if context.rounding == ROUND_CEILING:
353 return Infsign[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000354 return _dec_from_triple(sign, '9'*context.prec,
355 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000356 if sign == 1:
357 if context.rounding == ROUND_FLOOR:
358 return Infsign[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000359 return _dec_from_triple(sign, '9'*context.prec,
360 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000361
362
363class Underflow(Inexact, Rounded, Subnormal):
364 """Numerical underflow with result rounded to 0.
365
366 This occurs and signals underflow if a result is inexact and the
367 adjusted exponent of the result would be smaller (more negative) than
368 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000369 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000370
371 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000372 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000373 in 0 with the sign of the intermediate result and an exponent of Etiny.
374
375 In all cases, Inexact, Rounded, and Subnormal will also be raised.
376 """
377
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000378# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000379_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000380 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000381
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000382# Map conditions (per the spec) to signals
383_condition_map = {ConversionSyntax:InvalidOperation,
384 DivisionImpossible:InvalidOperation,
385 DivisionUndefined:InvalidOperation,
386 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000387
Guido van Rossumd8faa362007-04-27 19:54:29 +0000388##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000389
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000390# The getcontext() and setcontext() function manage access to a thread-local
391# current context. Py2.4 offers direct support for thread locals. If that
392# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000393# work for older Pythons. If threads are not part of the build, create a
394# mock threading object with threading.local() returning the module namespace.
395
396try:
397 import threading
398except ImportError:
399 # Python was compiled without threads; create a mock object instead
400 import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +0000401 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000402 def local(self, sys=sys):
403 return sys.modules[__name__]
404 threading = MockThreading()
405 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000406
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000407try:
408 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000409
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000410except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000411
Guido van Rossumd8faa362007-04-27 19:54:29 +0000412 # To fix reloading, force it to create a new context
413 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000414 if hasattr(threading.currentThread(), '__decimal_context__'):
415 del threading.currentThread().__decimal_context__
416
417 def setcontext(context):
418 """Set this thread's context to context."""
419 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000420 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000421 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000422 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000423
424 def getcontext():
425 """Returns this thread's context.
426
427 If this thread does not yet have a context, returns
428 a new context and sets this thread's context.
429 New contexts are copies of DefaultContext.
430 """
431 try:
432 return threading.currentThread().__decimal_context__
433 except AttributeError:
434 context = Context()
435 threading.currentThread().__decimal_context__ = context
436 return context
437
438else:
439
440 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000441 if hasattr(local, '__decimal_context__'):
442 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000443
444 def getcontext(_local=local):
445 """Returns this thread's context.
446
447 If this thread does not yet have a context, returns
448 a new context and sets this thread's context.
449 New contexts are copies of DefaultContext.
450 """
451 try:
452 return _local.__decimal_context__
453 except AttributeError:
454 context = Context()
455 _local.__decimal_context__ = context
456 return context
457
458 def setcontext(context, _local=local):
459 """Set this thread's context to context."""
460 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000461 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000462 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000463 _local.__decimal_context__ = context
464
465 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000466
Thomas Wouters89f507f2006-12-13 04:49:30 +0000467def localcontext(ctx=None):
468 """Return a context manager for a copy of the supplied context
469
470 Uses a copy of the current context if no context is specified
471 The returned context manager creates a local decimal context
472 in a with statement:
473 def sin(x):
474 with localcontext() as ctx:
475 ctx.prec += 2
476 # Rest of sin calculation algorithm
477 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000478 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000479
480 def sin(x):
481 with localcontext(ExtendedContext):
482 # Rest of sin calculation algorithm
483 # uses the Extended Context from the
484 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000485 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000486
487 """
488 # The string below can't be included in the docstring until Python 2.6
489 # as the doctest module doesn't understand __future__ statements
490 """
491 >>> from __future__ import with_statement
Guido van Rossum7131f842007-02-09 20:13:25 +0000492 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000493 28
494 >>> with localcontext():
495 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000496 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000497 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000498 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000499 30
500 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000501 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000502 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000503 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000504 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000505 28
506 """
507 if ctx is None: ctx = getcontext()
508 return _ContextManager(ctx)
509
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000510
Guido van Rossumd8faa362007-04-27 19:54:29 +0000511##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000512
Guido van Rossuma13f4a12007-12-10 20:04:04 +0000513class Decimal(_numbers.Real, _numbers.Inexact):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000514 """Floating point class for decimal arithmetic."""
515
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000516 __slots__ = ('_exp','_int','_sign', '_is_special')
517 # Generally, the value of the Decimal instance is given by
518 # (-1)**_sign * _int * 10**_exp
519 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000520
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000521 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000522 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000523 """Create a decimal point instance.
524
525 >>> Decimal('3.14') # string input
526 Decimal("3.14")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000527 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000528 Decimal("3.14")
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000529 >>> Decimal(314) # int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000530 Decimal("314")
531 >>> Decimal(Decimal(314)) # another decimal instance
532 Decimal("314")
533 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000534
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000535 # Note that the coefficient, self._int, is actually stored as
536 # a string rather than as a tuple of digits. This speeds up
537 # the "digits to integer" and "integer to digits" conversions
538 # that are used in almost every arithmetic operation on
539 # Decimals. This is an internal detail: the as_tuple function
540 # and the Decimal constructor still deal with tuples of
541 # digits.
542
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000543 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000544
Christian Heimesd59c64c2007-11-30 19:27:20 +0000545 # From a string
546 # REs insist on real strings, so we can too.
547 if isinstance(value, str):
548 m = _parser(value)
549 if m is None:
550 if context is None:
551 context = getcontext()
552 return context._raise_error(ConversionSyntax,
553 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000554
Christian Heimesd59c64c2007-11-30 19:27:20 +0000555 if m.group('sign') == "-":
556 self._sign = 1
557 else:
558 self._sign = 0
559 intpart = m.group('int')
560 if intpart is not None:
561 # finite number
562 fracpart = m.group('frac')
563 exp = int(m.group('exp') or '0')
564 if fracpart is not None:
565 self._int = (intpart+fracpart).lstrip('0') or '0'
566 self._exp = exp - len(fracpart)
567 else:
568 self._int = intpart.lstrip('0') or '0'
569 self._exp = exp
570 self._is_special = False
571 else:
572 diag = m.group('diag')
573 if diag is not None:
574 # NaN
575 self._int = diag.lstrip('0')
576 if m.group('signal'):
577 self._exp = 'N'
578 else:
579 self._exp = 'n'
580 else:
581 # infinity
582 self._int = '0'
583 self._exp = 'F'
584 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000585 return self
586
587 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000588 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000589 if value >= 0:
590 self._sign = 0
591 else:
592 self._sign = 1
593 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000594 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000595 self._is_special = False
596 return self
597
598 # From another decimal
599 if isinstance(value, Decimal):
600 self._exp = value._exp
601 self._sign = value._sign
602 self._int = value._int
603 self._is_special = value._is_special
604 return self
605
606 # From an internal working value
607 if isinstance(value, _WorkRep):
608 self._sign = value.sign
609 self._int = str(value.int)
610 self._exp = int(value.exp)
611 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000612 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000613
614 # tuple/list conversion (possibly from as_tuple())
615 if isinstance(value, (list,tuple)):
616 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000617 raise ValueError('Invalid tuple size in creation of Decimal '
618 'from list or tuple. The list or tuple '
619 'should have exactly three elements.')
620 # process sign. The isinstance test rejects floats
621 if not (isinstance(value[0], int) and value[0] in (0,1)):
622 raise ValueError("Invalid sign. The first value in the tuple "
623 "should be an integer; either 0 for a "
624 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000625 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000626 if value[2] == 'F':
627 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000628 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000629 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000630 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000631 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000632 # process and validate the digits in value[1]
633 digits = []
634 for digit in value[1]:
635 if isinstance(digit, int) and 0 <= digit <= 9:
636 # skip leading zeros
637 if digits or digit != 0:
638 digits.append(digit)
639 else:
640 raise ValueError("The second value in the tuple must "
641 "be composed of integers in the range "
642 "0 through 9.")
643 if value[2] in ('n', 'N'):
644 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000645 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000646 self._exp = value[2]
647 self._is_special = True
648 elif isinstance(value[2], int):
649 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000650 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000651 self._exp = value[2]
652 self._is_special = False
653 else:
654 raise ValueError("The third value in the tuple must "
655 "be an integer, or one of the "
656 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000657 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000658
Raymond Hettingerbf440692004-07-10 14:14:37 +0000659 if isinstance(value, float):
660 raise TypeError("Cannot convert float to Decimal. " +
661 "First convert the float to a string")
662
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000663 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000664
665 def _isnan(self):
666 """Returns whether the number is not actually one.
667
668 0 if a number
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000669 1 if NaN (it could be a normal quiet NaN or a phantom one)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000670 2 if sNaN
671 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000672 if self._is_special:
673 exp = self._exp
674 if exp == 'n':
675 return 1
676 elif exp == 'N':
677 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000678 return 0
679
680 def _isinfinity(self):
681 """Returns whether the number is infinite
682
683 0 if finite or not a number
684 1 if +INF
685 -1 if -INF
686 """
687 if self._exp == 'F':
688 if self._sign:
689 return -1
690 return 1
691 return 0
692
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000693 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000694 """Returns whether the number is not actually one.
695
696 if self, other are sNaN, signal
697 if self, other are NaN return nan
698 return 0
699
700 Done before operations.
701 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000702
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000703 self_is_nan = self._isnan()
704 if other is None:
705 other_is_nan = False
706 else:
707 other_is_nan = other._isnan()
708
709 if self_is_nan or other_is_nan:
710 if context is None:
711 context = getcontext()
712
713 if self_is_nan == 2:
714 return context._raise_error(InvalidOperation, 'sNaN',
715 1, self)
716 if other_is_nan == 2:
717 return context._raise_error(InvalidOperation, 'sNaN',
718 1, other)
719 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000720 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000721
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000722 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000723 return 0
724
Jack Diederich4dafcc42006-11-28 19:15:13 +0000725 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000726 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000727
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000728 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000729 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000730 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000731
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000732 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000733 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000734 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000735 # Never return NotImplemented
736 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000737
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000738 if self._is_special or other._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000739 # check for nans, without raising on a signaling nan
740 if self._isnan() or other._isnan():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000741 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000742
743 # INF = INF
744 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000745
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000746 # check for zeros; note that cmp(0, -0) should return 0
747 if not self:
748 if not other:
749 return 0
750 else:
751 return -((-1)**other._sign)
752 if not other:
753 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000754
Guido van Rossumd8faa362007-04-27 19:54:29 +0000755 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000756 if other._sign < self._sign:
757 return -1
758 if self._sign < other._sign:
759 return 1
760
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000761 self_adjusted = self.adjusted()
762 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000763 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000764 self_padded = self._int + '0'*(self._exp - other._exp)
765 other_padded = other._int + '0'*(other._exp - self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000766 return cmp(self_padded, other_padded) * (-1)**self._sign
767 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000768 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000769 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000770 return -((-1)**self._sign)
771
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000772 def __eq__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000773 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000774 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000775 return self.__cmp__(other) == 0
776
777 def __ne__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000778 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000779 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000780 return self.__cmp__(other) != 0
781
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000782 def __lt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000783 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000784 return NotImplemented
785 return self.__cmp__(other) < 0
786
787 def __le__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000788 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000789 return NotImplemented
790 return self.__cmp__(other) <= 0
791
792 def __gt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000793 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000794 return NotImplemented
795 return self.__cmp__(other) > 0
796
797 def __ge__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000798 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000799 return NotImplemented
800 return self.__cmp__(other) >= 0
801
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000802 def compare(self, other, context=None):
803 """Compares one to another.
804
805 -1 => a < b
806 0 => a = b
807 1 => a > b
808 NaN => one is NaN
809 Like __cmp__, but returns Decimal instances.
810 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000812
Guido van Rossumd8faa362007-04-27 19:54:29 +0000813 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000814 if (self._is_special or other and other._is_special):
815 ans = self._check_nans(other, context)
816 if ans:
817 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000818
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000819 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000820
821 def __hash__(self):
822 """x.__hash__() <==> hash(x)"""
823 # Decimal integers must hash the same as the ints
824 # Non-integer decimals are normalized and hashed as strings
Thomas Wouters477c8d52006-05-27 19:21:47 +0000825 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000826 if self._is_special:
827 if self._isnan():
828 raise TypeError('Cannot hash a NaN value.')
829 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000830 if not self:
831 return 0
832 if self._isinteger():
833 op = _WorkRep(self.to_integral_value())
834 # to make computation feasible for Decimals with large
835 # exponent, we use the fact that hash(n) == hash(m) for
836 # any two nonzero integers n and m such that (i) n and m
837 # have the same sign, and (ii) n is congruent to m modulo
838 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
839 # hash((-1)**s*c*pow(10, e, 2**64-1).
840 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000841 return hash(str(self.normalize()))
842
843 def as_tuple(self):
844 """Represents the number as a triple tuple.
845
846 To show the internals exactly as they are.
847 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000848 return (self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000849
850 def __repr__(self):
851 """Represents the number as an instance of Decimal."""
852 # Invariant: eval(repr(d)) == d
853 return 'Decimal("%s")' % str(self)
854
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000855 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000856 """Return string representation of the number in scientific notation.
857
858 Captures all of the information in the underlying representation.
859 """
860
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000861 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000862 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000863 if self._exp == 'F':
864 return sign + 'Infinity'
865 elif self._exp == 'n':
866 return sign + 'NaN' + self._int
867 else: # self._exp == 'N'
868 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000869
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000870 # number of digits of self._int to left of decimal point
871 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000872
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000873 # dotplace is number of digits of self._int to the left of the
874 # decimal point in the mantissa of the output string (that is,
875 # after adjusting the exponent)
876 if self._exp <= 0 and leftdigits > -6:
877 # no exponent required
878 dotplace = leftdigits
879 elif not eng:
880 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000881 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000882 elif self._int == '0':
883 # engineering notation, zero
884 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000885 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000886 # engineering notation, nonzero
887 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000888
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000889 if dotplace <= 0:
890 intpart = '0'
891 fracpart = '.' + '0'*(-dotplace) + self._int
892 elif dotplace >= len(self._int):
893 intpart = self._int+'0'*(dotplace-len(self._int))
894 fracpart = ''
895 else:
896 intpart = self._int[:dotplace]
897 fracpart = '.' + self._int[dotplace:]
898 if leftdigits == dotplace:
899 exp = ''
900 else:
901 if context is None:
902 context = getcontext()
903 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
904
905 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000906
907 def to_eng_string(self, context=None):
908 """Convert to engineering-type string.
909
910 Engineering notation has an exponent which is a multiple of 3, so there
911 are up to 3 digits left of the decimal place.
912
913 Same rules for when in exponential and when as a value as in __str__.
914 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000915 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000916
917 def __neg__(self, context=None):
918 """Returns a copy with the sign switched.
919
920 Rounds, if it has reason.
921 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000922 if self._is_special:
923 ans = self._check_nans(context=context)
924 if ans:
925 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000926
927 if not self:
928 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000929 ans = self.copy_sign(Dec_0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000930 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000931 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000932
933 if context is None:
934 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000935 if context._rounding_decision == ALWAYS_ROUND:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000936 return ans._fix(context)
937 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000938
939 def __pos__(self, context=None):
940 """Returns a copy, unless it is a sNaN.
941
942 Rounds the number (if more then precision digits)
943 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000944 if self._is_special:
945 ans = self._check_nans(context=context)
946 if ans:
947 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000948
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000949 if not self:
950 # + (-0) = 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000951 ans = self.copy_sign(Dec_0)
952 else:
953 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000954
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000955 if context is None:
956 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000957 if context._rounding_decision == ALWAYS_ROUND:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000958 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000959 return ans
960
961 def __abs__(self, round=1, context=None):
962 """Returns the absolute value of self.
963
964 If the second argument is 0, do not round.
965 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000966 if self._is_special:
967 ans = self._check_nans(context=context)
968 if ans:
969 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000970
971 if not round:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000972 if context is None:
973 context = getcontext()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000974 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000975 context._set_rounding_decision(NEVER_ROUND)
976
977 if self._sign:
978 ans = self.__neg__(context=context)
979 else:
980 ans = self.__pos__(context=context)
981
982 return ans
983
984 def __add__(self, other, context=None):
985 """Returns self + other.
986
987 -INF + INF (or the reverse) cause InvalidOperation errors.
988 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000989 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000990 if other is NotImplemented:
991 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000992
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000993 if context is None:
994 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000995
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000996 if self._is_special or other._is_special:
997 ans = self._check_nans(other, context)
998 if ans:
999 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001001 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001002 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001003 if self._sign != other._sign and other._isinfinity():
1004 return context._raise_error(InvalidOperation, '-INF + INF')
1005 return Decimal(self)
1006 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001007 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001008
1009 shouldround = context._rounding_decision == ALWAYS_ROUND
1010
1011 exp = min(self._exp, other._exp)
1012 negativezero = 0
1013 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001014 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001015 negativezero = 1
1016
1017 if not self and not other:
1018 sign = min(self._sign, other._sign)
1019 if negativezero:
1020 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001021 ans = _dec_from_triple(sign, '0', exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001022 if shouldround:
1023 ans = ans._fix(context)
1024 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001025 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001026 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001027 ans = other._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001028 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001029 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001030 return ans
1031 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001032 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001033 ans = self._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001034 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001035 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001036 return ans
1037
1038 op1 = _WorkRep(self)
1039 op2 = _WorkRep(other)
1040 op1, op2 = _normalize(op1, op2, shouldround, context.prec)
1041
1042 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001043 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001044 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001045 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001046 ans = _dec_from_triple(negativezero, '0', exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001047 if shouldround:
1048 ans = ans._fix(context)
1049 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001050 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001051 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001052 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001053 if op1.sign == 1:
1054 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055 op1.sign, op2.sign = op2.sign, op1.sign
1056 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001057 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001058 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001059 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001060 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001061 op1.sign, op2.sign = (0, 0)
1062 else:
1063 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001064 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001065
Raymond Hettinger17931de2004-10-27 06:21:46 +00001066 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001067 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001068 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001069 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001070
1071 result.exp = op1.exp
1072 ans = Decimal(result)
1073 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001074 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001075 return ans
1076
1077 __radd__ = __add__
1078
1079 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001080 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001081 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001082 if other is NotImplemented:
1083 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001084
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001085 if self._is_special or other._is_special:
1086 ans = self._check_nans(other, context=context)
1087 if ans:
1088 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001089
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001090 # self - other is computed as self + other.copy_negate()
1091 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001092
1093 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001094 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001095 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001096 if other is NotImplemented:
1097 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001098
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001099 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001100
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001101 def __mul__(self, other, context=None):
1102 """Return self * other.
1103
1104 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1105 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001106 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001107 if other is NotImplemented:
1108 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001109
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001110 if context is None:
1111 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001112
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001113 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001114
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001115 if self._is_special or other._is_special:
1116 ans = self._check_nans(other, context)
1117 if ans:
1118 return ans
1119
1120 if self._isinfinity():
1121 if not other:
1122 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1123 return Infsign[resultsign]
1124
1125 if other._isinfinity():
1126 if not self:
1127 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1128 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001129
1130 resultexp = self._exp + other._exp
1131 shouldround = context._rounding_decision == ALWAYS_ROUND
1132
1133 # Special case for multiplying by zero
1134 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001135 ans = _dec_from_triple(resultsign, '0', resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001136 if shouldround:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001137 # Fixing in case the exponent is out of bounds
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001138 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001139 return ans
1140
1141 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001142 if self._int == '1':
1143 ans = _dec_from_triple(resultsign, other._int, resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001144 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001145 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001146 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001147 if other._int == '1':
1148 ans = _dec_from_triple(resultsign, self._int, resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001149 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001150 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001151 return ans
1152
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001153 op1 = _WorkRep(self)
1154 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001155
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001156 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001157 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001158 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001159
1160 return ans
1161 __rmul__ = __mul__
1162
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001163 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001164 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001165 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001166 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001167 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001168
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001169 if context is None:
1170 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001171
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001172 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001173
1174 if self._is_special or other._is_special:
1175 ans = self._check_nans(other, context)
1176 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001177 return ans
1178
1179 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001180 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001181
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001182 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001183 return Infsign[sign]
1184
1185 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001186 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001187 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001188
1189 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001190 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001191 if not self:
1192 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001193 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001194
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001195 if not self:
1196 exp = self._exp - other._exp
1197 coeff = 0
1198 else:
1199 # OK, so neither = 0, INF or NaN
1200 shift = len(other._int) - len(self._int) + context.prec + 1
1201 exp = self._exp - other._exp - shift
1202 op1 = _WorkRep(self)
1203 op2 = _WorkRep(other)
1204 if shift >= 0:
1205 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1206 else:
1207 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1208 if remainder:
1209 # result is not exact; adjust to ensure correct rounding
1210 if coeff % 5 == 0:
1211 coeff += 1
1212 else:
1213 # result is exact; get as close to ideal exponent as possible
1214 ideal_exp = self._exp - other._exp
1215 while exp < ideal_exp and coeff % 10 == 0:
1216 coeff //= 10
1217 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001218
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001219 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001220 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001221
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001222 def _divide(self, other, context):
1223 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001224
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001225 Assumes that neither self nor other is a NaN, that self is not
1226 infinite and that other is nonzero.
1227 """
1228 sign = self._sign ^ other._sign
1229 if other._isinfinity():
1230 ideal_exp = self._exp
1231 else:
1232 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001233
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001234 expdiff = self.adjusted() - other.adjusted()
1235 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001236 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001237 self._rescale(ideal_exp, context.rounding))
1238 if expdiff <= context.prec:
1239 op1 = _WorkRep(self)
1240 op2 = _WorkRep(other)
1241 if op1.exp >= op2.exp:
1242 op1.int *= 10**(op1.exp - op2.exp)
1243 else:
1244 op2.int *= 10**(op2.exp - op1.exp)
1245 q, r = divmod(op1.int, op2.int)
1246 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001247 return (_dec_from_triple(sign, str(q), 0),
1248 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001249
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001250 # Here the quotient is too large to be representable
1251 ans = context._raise_error(DivisionImpossible,
1252 'quotient too large in //, % or divmod')
1253 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001254
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001255 def __rtruediv__(self, other, context=None):
1256 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001257 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001258 if other is NotImplemented:
1259 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001260 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001261
1262 def __divmod__(self, other, context=None):
1263 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001264 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001265 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001266 other = _convert_other(other)
1267 if other is NotImplemented:
1268 return other
1269
1270 if context is None:
1271 context = getcontext()
1272
1273 ans = self._check_nans(other, context)
1274 if ans:
1275 return (ans, ans)
1276
1277 sign = self._sign ^ other._sign
1278 if self._isinfinity():
1279 if other._isinfinity():
1280 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1281 return ans, ans
1282 else:
1283 return (Infsign[sign],
1284 context._raise_error(InvalidOperation, 'INF % x'))
1285
1286 if not other:
1287 if not self:
1288 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1289 return ans, ans
1290 else:
1291 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1292 context._raise_error(InvalidOperation, 'x % 0'))
1293
1294 quotient, remainder = self._divide(other, context)
1295 if context._rounding_decision == ALWAYS_ROUND:
1296 remainder = remainder._fix(context)
1297 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001298
1299 def __rdivmod__(self, other, context=None):
1300 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001301 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001302 if other is NotImplemented:
1303 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001304 return other.__divmod__(self, context=context)
1305
1306 def __mod__(self, other, context=None):
1307 """
1308 self % other
1309 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001310 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001311 if other is NotImplemented:
1312 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001313
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001314 if context is None:
1315 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001316
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001317 ans = self._check_nans(other, context)
1318 if ans:
1319 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001320
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001321 if self._isinfinity():
1322 return context._raise_error(InvalidOperation, 'INF % x')
1323 elif not other:
1324 if self:
1325 return context._raise_error(InvalidOperation, 'x % 0')
1326 else:
1327 return context._raise_error(DivisionUndefined, '0 % 0')
1328
1329 remainder = self._divide(other, context)[1]
1330 if context._rounding_decision == ALWAYS_ROUND:
1331 remainder = remainder._fix(context)
1332 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001333
1334 def __rmod__(self, other, context=None):
1335 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001336 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001337 if other is NotImplemented:
1338 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001339 return other.__mod__(self, context=context)
1340
1341 def remainder_near(self, other, context=None):
1342 """
1343 Remainder nearest to 0- abs(remainder-near) <= other/2
1344 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001345 if context is None:
1346 context = getcontext()
1347
1348 other = _convert_other(other, raiseit=True)
1349
1350 ans = self._check_nans(other, context)
1351 if ans:
1352 return ans
1353
1354 # self == +/-infinity -> InvalidOperation
1355 if self._isinfinity():
1356 return context._raise_error(InvalidOperation,
1357 'remainder_near(infinity, x)')
1358
1359 # other == 0 -> either InvalidOperation or DivisionUndefined
1360 if not other:
1361 if self:
1362 return context._raise_error(InvalidOperation,
1363 'remainder_near(x, 0)')
1364 else:
1365 return context._raise_error(DivisionUndefined,
1366 'remainder_near(0, 0)')
1367
1368 # other = +/-infinity -> remainder = self
1369 if other._isinfinity():
1370 ans = Decimal(self)
1371 return ans._fix(context)
1372
1373 # self = 0 -> remainder = self, with ideal exponent
1374 ideal_exponent = min(self._exp, other._exp)
1375 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001376 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001377 return ans._fix(context)
1378
1379 # catch most cases of large or small quotient
1380 expdiff = self.adjusted() - other.adjusted()
1381 if expdiff >= context.prec + 1:
1382 # expdiff >= prec+1 => abs(self/other) > 10**prec
1383 return context._raise_error(DivisionImpossible)
1384 if expdiff <= -2:
1385 # expdiff <= -2 => abs(self/other) < 0.1
1386 ans = self._rescale(ideal_exponent, context.rounding)
1387 return ans._fix(context)
1388
1389 # adjust both arguments to have the same exponent, then divide
1390 op1 = _WorkRep(self)
1391 op2 = _WorkRep(other)
1392 if op1.exp >= op2.exp:
1393 op1.int *= 10**(op1.exp - op2.exp)
1394 else:
1395 op2.int *= 10**(op2.exp - op1.exp)
1396 q, r = divmod(op1.int, op2.int)
1397 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1398 # 10**ideal_exponent. Apply correction to ensure that
1399 # abs(remainder) <= abs(other)/2
1400 if 2*r + (q&1) > op2.int:
1401 r -= op2.int
1402 q += 1
1403
1404 if q >= 10**context.prec:
1405 return context._raise_error(DivisionImpossible)
1406
1407 # result has same sign as self unless r is negative
1408 sign = self._sign
1409 if r < 0:
1410 sign = 1-sign
1411 r = -r
1412
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001413 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001414 return ans._fix(context)
1415
1416 def __floordiv__(self, other, context=None):
1417 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001418 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001419 if other is NotImplemented:
1420 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001421
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001422 if context is None:
1423 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001424
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001425 ans = self._check_nans(other, context)
1426 if ans:
1427 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001428
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001429 if self._isinfinity():
1430 if other._isinfinity():
1431 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001432 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001433 return Infsign[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001434
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001435 if not other:
1436 if self:
1437 return context._raise_error(DivisionByZero, 'x // 0',
1438 self._sign ^ other._sign)
1439 else:
1440 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001441
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001442 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001443
1444 def __rfloordiv__(self, other, context=None):
1445 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001446 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001447 if other is NotImplemented:
1448 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001449 return other.__floordiv__(self, context=context)
1450
1451 def __float__(self):
1452 """Float representation."""
1453 return float(str(self))
1454
1455 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001456 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001457 if self._is_special:
1458 if self._isnan():
1459 context = getcontext()
1460 return context._raise_error(InvalidContext)
1461 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001462 raise OverflowError("Cannot convert infinity to int")
1463 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001464 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001465 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001466 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001467 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001468
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001469 def _fix_nan(self, context):
1470 """Decapitate the payload of a NaN to fit the context"""
1471 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001472
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001473 # maximum length of payload is precision if _clamp=0,
1474 # precision-1 if _clamp=1.
1475 max_payload_len = context.prec - context._clamp
1476 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001477 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1478 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001479 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001480
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001481 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001482 """Round if it is necessary to keep self within prec precision.
1483
1484 Rounds and fixes the exponent. Does not raise on a sNaN.
1485
1486 Arguments:
1487 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001488 context - context used.
1489 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001490
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001491 if context is None:
1492 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001493
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001494 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001495 if self._isnan():
1496 # decapitate payload if necessary
1497 return self._fix_nan(context)
1498 else:
1499 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001500 return Decimal(self)
1501
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001502 # if self is zero then exponent should be between Etiny and
1503 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1504 Etiny = context.Etiny()
1505 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001506 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001507 exp_max = [context.Emax, Etop][context._clamp]
1508 new_exp = min(max(self._exp, Etiny), exp_max)
1509 if new_exp != self._exp:
1510 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001511 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001512 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001513 return Decimal(self)
1514
1515 # exp_min is the smallest allowable exponent of the result,
1516 # equal to max(self.adjusted()-context.prec+1, Etiny)
1517 exp_min = len(self._int) + self._exp - context.prec
1518 if exp_min > Etop:
1519 # overflow: exp_min > Etop iff self.adjusted() > Emax
1520 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001521 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001522 return context._raise_error(Overflow, 'above Emax', self._sign)
1523 self_is_subnormal = exp_min < Etiny
1524 if self_is_subnormal:
1525 context._raise_error(Subnormal)
1526 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001527
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001528 # round if self has too many digits
1529 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001530 context._raise_error(Rounded)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001531 digits = len(self._int) + self._exp - exp_min
1532 if digits < 0:
1533 self = _dec_from_triple(self._sign, '1', exp_min-1)
1534 digits = 0
1535 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1536 changed = this_function(digits)
1537 coeff = self._int[:digits] or '0'
1538 if changed == 1:
1539 coeff = str(int(coeff)+1)
1540 ans = _dec_from_triple(self._sign, coeff, exp_min)
1541
1542 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001543 context._raise_error(Inexact)
1544 if self_is_subnormal:
1545 context._raise_error(Underflow)
1546 if not ans:
1547 # raise Clamped on underflow to 0
1548 context._raise_error(Clamped)
1549 elif len(ans._int) == context.prec+1:
1550 # we get here only if rescaling rounds the
1551 # cofficient up to exactly 10**context.prec
1552 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001553 ans = _dec_from_triple(ans._sign,
1554 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001555 else:
1556 # Inexact and Rounded have already been raised
1557 ans = context._raise_error(Overflow, 'above Emax',
1558 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001559 return ans
1560
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001561 # fold down if _clamp == 1 and self has too few digits
1562 if context._clamp == 1 and self._exp > Etop:
1563 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001564 self_padded = self._int + '0'*(self._exp - Etop)
1565 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001566
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001567 # here self was representable to begin with; return unchanged
1568 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001569
1570 _pick_rounding_function = {}
1571
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001572 # for each of the rounding functions below:
1573 # self is a finite, nonzero Decimal
1574 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001575 #
1576 # each function returns either -1, 0, or 1, as follows:
1577 # 1 indicates that self should be rounded up (away from zero)
1578 # 0 indicates that self should be truncated, and that all the
1579 # digits to be truncated are zeros (so the value is unchanged)
1580 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001581
1582 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001583 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001584 if _all_zeros(self._int, prec):
1585 return 0
1586 else:
1587 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001588
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001589 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001590 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001591 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001592
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001593 def _round_half_up(self, prec):
1594 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001595 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001596 return 1
1597 elif _all_zeros(self._int, prec):
1598 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001599 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001600 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001601
1602 def _round_half_down(self, prec):
1603 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001604 if _exact_half(self._int, prec):
1605 return -1
1606 else:
1607 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001608
1609 def _round_half_even(self, prec):
1610 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001611 if _exact_half(self._int, prec) and \
1612 (prec == 0 or self._int[prec-1] in '02468'):
1613 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001614 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001615 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001616
1617 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001618 """Rounds up (not away from 0 if negative.)"""
1619 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001620 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001621 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001622 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001623
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001624 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001625 """Rounds down (not towards 0 if negative)"""
1626 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001627 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001628 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001629 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001630
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001631 def _round_05up(self, prec):
1632 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001633 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001634 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001635 else:
1636 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001637
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001638 def fma(self, other, third, context=None):
1639 """Fused multiply-add.
1640
1641 Returns self*other+third with no rounding of the intermediate
1642 product self*other.
1643
1644 self and other are multiplied together, with no rounding of
1645 the result. The third operand is then added to the result,
1646 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001647 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001648
1649 other = _convert_other(other, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001650
1651 # compute product; raise InvalidOperation if either operand is
1652 # a signaling NaN or if the product is zero times infinity.
1653 if self._is_special or other._is_special:
1654 if context is None:
1655 context = getcontext()
1656 if self._exp == 'N':
1657 return context._raise_error(InvalidOperation, 'sNaN',
1658 1, self)
1659 if other._exp == 'N':
1660 return context._raise_error(InvalidOperation, 'sNaN',
1661 1, other)
1662 if self._exp == 'n':
1663 product = self
1664 elif other._exp == 'n':
1665 product = other
1666 elif self._exp == 'F':
1667 if not other:
1668 return context._raise_error(InvalidOperation,
1669 'INF * 0 in fma')
1670 product = Infsign[self._sign ^ other._sign]
1671 elif other._exp == 'F':
1672 if not self:
1673 return context._raise_error(InvalidOperation,
1674 '0 * INF in fma')
1675 product = Infsign[self._sign ^ other._sign]
1676 else:
1677 product = _dec_from_triple(self._sign ^ other._sign,
1678 str(int(self._int) * int(other._int)),
1679 self._exp + other._exp)
1680
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001681 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001682 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001683
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001684 def _power_modulo(self, other, modulo, context=None):
1685 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001686
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001687 # if can't convert other and modulo to Decimal, raise
1688 # TypeError; there's no point returning NotImplemented (no
1689 # equivalent of __rpow__ for three argument pow)
1690 other = _convert_other(other, raiseit=True)
1691 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001692
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001693 if context is None:
1694 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001695
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001696 # deal with NaNs: if there are any sNaNs then first one wins,
1697 # (i.e. behaviour for NaNs is identical to that of fma)
1698 self_is_nan = self._isnan()
1699 other_is_nan = other._isnan()
1700 modulo_is_nan = modulo._isnan()
1701 if self_is_nan or other_is_nan or modulo_is_nan:
1702 if self_is_nan == 2:
1703 return context._raise_error(InvalidOperation, 'sNaN',
1704 1, self)
1705 if other_is_nan == 2:
1706 return context._raise_error(InvalidOperation, 'sNaN',
1707 1, other)
1708 if modulo_is_nan == 2:
1709 return context._raise_error(InvalidOperation, 'sNaN',
1710 1, modulo)
1711 if self_is_nan:
1712 return self._fix_nan(context)
1713 if other_is_nan:
1714 return other._fix_nan(context)
1715 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001716
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001717 # check inputs: we apply same restrictions as Python's pow()
1718 if not (self._isinteger() and
1719 other._isinteger() and
1720 modulo._isinteger()):
1721 return context._raise_error(InvalidOperation,
1722 'pow() 3rd argument not allowed '
1723 'unless all arguments are integers')
1724 if other < 0:
1725 return context._raise_error(InvalidOperation,
1726 'pow() 2nd argument cannot be '
1727 'negative when 3rd argument specified')
1728 if not modulo:
1729 return context._raise_error(InvalidOperation,
1730 'pow() 3rd argument cannot be 0')
1731
1732 # additional restriction for decimal: the modulus must be less
1733 # than 10**prec in absolute value
1734 if modulo.adjusted() >= context.prec:
1735 return context._raise_error(InvalidOperation,
1736 'insufficient precision: pow() 3rd '
1737 'argument must not have more than '
1738 'precision digits')
1739
1740 # define 0**0 == NaN, for consistency with two-argument pow
1741 # (even though it hurts!)
1742 if not other and not self:
1743 return context._raise_error(InvalidOperation,
1744 'at least one of pow() 1st argument '
1745 'and 2nd argument must be nonzero ;'
1746 '0**0 is not defined')
1747
1748 # compute sign of result
1749 if other._iseven():
1750 sign = 0
1751 else:
1752 sign = self._sign
1753
1754 # convert modulo to a Python integer, and self and other to
1755 # Decimal integers (i.e. force their exponents to be >= 0)
1756 modulo = abs(int(modulo))
1757 base = _WorkRep(self.to_integral_value())
1758 exponent = _WorkRep(other.to_integral_value())
1759
1760 # compute result using integer pow()
1761 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1762 for i in range(exponent.exp):
1763 base = pow(base, 10, modulo)
1764 base = pow(base, exponent.int, modulo)
1765
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001766 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001767
1768 def _power_exact(self, other, p):
1769 """Attempt to compute self**other exactly.
1770
1771 Given Decimals self and other and an integer p, attempt to
1772 compute an exact result for the power self**other, with p
1773 digits of precision. Return None if self**other is not
1774 exactly representable in p digits.
1775
1776 Assumes that elimination of special cases has already been
1777 performed: self and other must both be nonspecial; self must
1778 be positive and not numerically equal to 1; other must be
1779 nonzero. For efficiency, other._exp should not be too large,
1780 so that 10**abs(other._exp) is a feasible calculation."""
1781
1782 # In the comments below, we write x for the value of self and
1783 # y for the value of other. Write x = xc*10**xe and y =
1784 # yc*10**ye.
1785
1786 # The main purpose of this method is to identify the *failure*
1787 # of x**y to be exactly representable with as little effort as
1788 # possible. So we look for cheap and easy tests that
1789 # eliminate the possibility of x**y being exact. Only if all
1790 # these tests are passed do we go on to actually compute x**y.
1791
1792 # Here's the main idea. First normalize both x and y. We
1793 # express y as a rational m/n, with m and n relatively prime
1794 # and n>0. Then for x**y to be exactly representable (at
1795 # *any* precision), xc must be the nth power of a positive
1796 # integer and xe must be divisible by n. If m is negative
1797 # then additionally xc must be a power of either 2 or 5, hence
1798 # a power of 2**n or 5**n.
1799 #
1800 # There's a limit to how small |y| can be: if y=m/n as above
1801 # then:
1802 #
1803 # (1) if xc != 1 then for the result to be representable we
1804 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1805 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1806 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1807 # representable.
1808 #
1809 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1810 # |y| < 1/|xe| then the result is not representable.
1811 #
1812 # Note that since x is not equal to 1, at least one of (1) and
1813 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1814 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1815 #
1816 # There's also a limit to how large y can be, at least if it's
1817 # positive: the normalized result will have coefficient xc**y,
1818 # so if it's representable then xc**y < 10**p, and y <
1819 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1820 # not exactly representable.
1821
1822 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1823 # so |y| < 1/xe and the result is not representable.
1824 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1825 # < 1/nbits(xc).
1826
1827 x = _WorkRep(self)
1828 xc, xe = x.int, x.exp
1829 while xc % 10 == 0:
1830 xc //= 10
1831 xe += 1
1832
1833 y = _WorkRep(other)
1834 yc, ye = y.int, y.exp
1835 while yc % 10 == 0:
1836 yc //= 10
1837 ye += 1
1838
1839 # case where xc == 1: result is 10**(xe*y), with xe*y
1840 # required to be an integer
1841 if xc == 1:
1842 if ye >= 0:
1843 exponent = xe*yc*10**ye
1844 else:
1845 exponent, remainder = divmod(xe*yc, 10**-ye)
1846 if remainder:
1847 return None
1848 if y.sign == 1:
1849 exponent = -exponent
1850 # if other is a nonnegative integer, use ideal exponent
1851 if other._isinteger() and other._sign == 0:
1852 ideal_exponent = self._exp*int(other)
1853 zeros = min(exponent-ideal_exponent, p-1)
1854 else:
1855 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001856 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001857
1858 # case where y is negative: xc must be either a power
1859 # of 2 or a power of 5.
1860 if y.sign == 1:
1861 last_digit = xc % 10
1862 if last_digit in (2,4,6,8):
1863 # quick test for power of 2
1864 if xc & -xc != xc:
1865 return None
1866 # now xc is a power of 2; e is its exponent
1867 e = _nbits(xc)-1
1868 # find e*y and xe*y; both must be integers
1869 if ye >= 0:
1870 y_as_int = yc*10**ye
1871 e = e*y_as_int
1872 xe = xe*y_as_int
1873 else:
1874 ten_pow = 10**-ye
1875 e, remainder = divmod(e*yc, ten_pow)
1876 if remainder:
1877 return None
1878 xe, remainder = divmod(xe*yc, ten_pow)
1879 if remainder:
1880 return None
1881
1882 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1883 return None
1884 xc = 5**e
1885
1886 elif last_digit == 5:
1887 # e >= log_5(xc) if xc is a power of 5; we have
1888 # equality all the way up to xc=5**2658
1889 e = _nbits(xc)*28//65
1890 xc, remainder = divmod(5**e, xc)
1891 if remainder:
1892 return None
1893 while xc % 5 == 0:
1894 xc //= 5
1895 e -= 1
1896 if ye >= 0:
1897 y_as_integer = yc*10**ye
1898 e = e*y_as_integer
1899 xe = xe*y_as_integer
1900 else:
1901 ten_pow = 10**-ye
1902 e, remainder = divmod(e*yc, ten_pow)
1903 if remainder:
1904 return None
1905 xe, remainder = divmod(xe*yc, ten_pow)
1906 if remainder:
1907 return None
1908 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1909 return None
1910 xc = 2**e
1911 else:
1912 return None
1913
1914 if xc >= 10**p:
1915 return None
1916 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001917 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001918
1919 # now y is positive; find m and n such that y = m/n
1920 if ye >= 0:
1921 m, n = yc*10**ye, 1
1922 else:
1923 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1924 return None
1925 xc_bits = _nbits(xc)
1926 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1927 return None
1928 m, n = yc, 10**(-ye)
1929 while m % 2 == n % 2 == 0:
1930 m //= 2
1931 n //= 2
1932 while m % 5 == n % 5 == 0:
1933 m //= 5
1934 n //= 5
1935
1936 # compute nth root of xc*10**xe
1937 if n > 1:
1938 # if 1 < xc < 2**n then xc isn't an nth power
1939 if xc != 1 and xc_bits <= n:
1940 return None
1941
1942 xe, rem = divmod(xe, n)
1943 if rem != 0:
1944 return None
1945
1946 # compute nth root of xc using Newton's method
1947 a = 1 << -(-_nbits(xc)//n) # initial estimate
1948 while True:
1949 q, r = divmod(xc, a**(n-1))
1950 if a <= q:
1951 break
1952 else:
1953 a = (a*(n-1) + q)//n
1954 if not (a == q and r == 0):
1955 return None
1956 xc = a
1957
1958 # now xc*10**xe is the nth root of the original xc*10**xe
1959 # compute mth power of xc*10**xe
1960
1961 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1962 # 10**p and the result is not representable.
1963 if xc > 1 and m > p*100//_log10_lb(xc):
1964 return None
1965 xc = xc**m
1966 xe *= m
1967 if xc > 10**p:
1968 return None
1969
1970 # by this point the result *is* exactly representable
1971 # adjust the exponent to get as close as possible to the ideal
1972 # exponent, if necessary
1973 str_xc = str(xc)
1974 if other._isinteger() and other._sign == 0:
1975 ideal_exponent = self._exp*int(other)
1976 zeros = min(xe-ideal_exponent, p-len(str_xc))
1977 else:
1978 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001979 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001980
1981 def __pow__(self, other, modulo=None, context=None):
1982 """Return self ** other [ % modulo].
1983
1984 With two arguments, compute self**other.
1985
1986 With three arguments, compute (self**other) % modulo. For the
1987 three argument form, the following restrictions on the
1988 arguments hold:
1989
1990 - all three arguments must be integral
1991 - other must be nonnegative
1992 - either self or other (or both) must be nonzero
1993 - modulo must be nonzero and must have at most p digits,
1994 where p is the context precision.
1995
1996 If any of these restrictions is violated the InvalidOperation
1997 flag is raised.
1998
1999 The result of pow(self, other, modulo) is identical to the
2000 result that would be obtained by computing (self**other) %
2001 modulo with unbounded precision, but is computed more
2002 efficiently. It is always exact.
2003 """
2004
2005 if modulo is not None:
2006 return self._power_modulo(other, modulo, context)
2007
2008 other = _convert_other(other)
2009 if other is NotImplemented:
2010 return other
2011
2012 if context is None:
2013 context = getcontext()
2014
2015 # either argument is a NaN => result is NaN
2016 ans = self._check_nans(other, context)
2017 if ans:
2018 return ans
2019
2020 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2021 if not other:
2022 if not self:
2023 return context._raise_error(InvalidOperation, '0 ** 0')
2024 else:
2025 return Dec_p1
2026
2027 # result has sign 1 iff self._sign is 1 and other is an odd integer
2028 result_sign = 0
2029 if self._sign == 1:
2030 if other._isinteger():
2031 if not other._iseven():
2032 result_sign = 1
2033 else:
2034 # -ve**noninteger = NaN
2035 # (-0)**noninteger = 0**noninteger
2036 if self:
2037 return context._raise_error(InvalidOperation,
2038 'x ** y with x negative and y not an integer')
2039 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002040 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002041
2042 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2043 if not self:
2044 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002045 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002046 else:
2047 return Infsign[result_sign]
2048
2049 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002050 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002051 if other._sign == 0:
2052 return Infsign[result_sign]
2053 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002054 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002055
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002056 # 1**other = 1, but the choice of exponent and the flags
2057 # depend on the exponent of self, and on whether other is a
2058 # positive integer, a negative integer, or neither
2059 if self == Dec_p1:
2060 if other._isinteger():
2061 # exp = max(self._exp*max(int(other), 0),
2062 # 1-context.prec) but evaluating int(other) directly
2063 # is dangerous until we know other is small (other
2064 # could be 1e999999999)
2065 if other._sign == 1:
2066 multiplier = 0
2067 elif other > context.prec:
2068 multiplier = context.prec
2069 else:
2070 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002071
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002072 exp = self._exp * multiplier
2073 if exp < 1-context.prec:
2074 exp = 1-context.prec
2075 context._raise_error(Rounded)
2076 else:
2077 context._raise_error(Inexact)
2078 context._raise_error(Rounded)
2079 exp = 1-context.prec
2080
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002081 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002082
2083 # compute adjusted exponent of self
2084 self_adj = self.adjusted()
2085
2086 # self ** infinity is infinity if self > 1, 0 if self < 1
2087 # self ** -infinity is infinity if self < 1, 0 if self > 1
2088 if other._isinfinity():
2089 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002090 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002091 else:
2092 return Infsign[result_sign]
2093
2094 # from here on, the result always goes through the call
2095 # to _fix at the end of this function.
2096 ans = None
2097
2098 # crude test to catch cases of extreme overflow/underflow. If
2099 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2100 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2101 # self**other >= 10**(Emax+1), so overflow occurs. The test
2102 # for underflow is similar.
2103 bound = self._log10_exp_bound() + other.adjusted()
2104 if (self_adj >= 0) == (other._sign == 0):
2105 # self > 1 and other +ve, or self < 1 and other -ve
2106 # possibility of overflow
2107 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002108 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002109 else:
2110 # self > 1 and other -ve, or self < 1 and other +ve
2111 # possibility of underflow to 0
2112 Etiny = context.Etiny()
2113 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002114 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002115
2116 # try for an exact result with precision +1
2117 if ans is None:
2118 ans = self._power_exact(other, context.prec + 1)
2119 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002120 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002121
2122 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2123 if ans is None:
2124 p = context.prec
2125 x = _WorkRep(self)
2126 xc, xe = x.int, x.exp
2127 y = _WorkRep(other)
2128 yc, ye = y.int, y.exp
2129 if y.sign == 1:
2130 yc = -yc
2131
2132 # compute correctly rounded result: start with precision +3,
2133 # then increase precision until result is unambiguously roundable
2134 extra = 3
2135 while True:
2136 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2137 if coeff % (5*10**(len(str(coeff))-p-1)):
2138 break
2139 extra += 3
2140
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002141 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002142
2143 # the specification says that for non-integer other we need to
2144 # raise Inexact, even when the result is actually exact. In
2145 # the same way, we need to raise Underflow here if the result
2146 # is subnormal. (The call to _fix will take care of raising
2147 # Rounded and Subnormal, as usual.)
2148 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002149 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002150 # pad with zeros up to length context.prec+1 if necessary
2151 if len(ans._int) <= context.prec:
2152 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002153 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2154 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002155 if ans.adjusted() < context.Emin:
2156 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002157
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002158 # unlike exp, ln and log10, the power function respects the
2159 # rounding mode; no need to use ROUND_HALF_EVEN here
2160 ans = ans._fix(context)
2161 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002162
2163 def __rpow__(self, other, context=None):
2164 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002165 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002166 if other is NotImplemented:
2167 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002168 return other.__pow__(self, context=context)
2169
2170 def normalize(self, context=None):
2171 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002172
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002173 if context is None:
2174 context = getcontext()
2175
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002176 if self._is_special:
2177 ans = self._check_nans(context=context)
2178 if ans:
2179 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002180
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002181 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002182 if dup._isinfinity():
2183 return dup
2184
2185 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002186 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002187 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002188 end = len(dup._int)
2189 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002190 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002191 exp += 1
2192 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002193 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002194
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002195 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002196 """Quantize self so its exponent is the same as that of exp.
2197
2198 Similar to self._rescale(exp._exp) but with error checking.
2199 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002200 exp = _convert_other(exp, raiseit=True)
2201
2202 if context is None:
2203 context = getcontext()
2204 if rounding is None:
2205 rounding = context.rounding
2206
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002207 if self._is_special or exp._is_special:
2208 ans = self._check_nans(exp, context)
2209 if ans:
2210 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002211
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002212 if exp._isinfinity() or self._isinfinity():
2213 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002214 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002215 return context._raise_error(InvalidOperation,
2216 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002217
2218 # if we're not watching exponents, do a simple rescale
2219 if not watchexp:
2220 ans = self._rescale(exp._exp, rounding)
2221 # raise Inexact and Rounded where appropriate
2222 if ans._exp > self._exp:
2223 context._raise_error(Rounded)
2224 if ans != self:
2225 context._raise_error(Inexact)
2226 return ans
2227
2228 # exp._exp should be between Etiny and Emax
2229 if not (context.Etiny() <= exp._exp <= context.Emax):
2230 return context._raise_error(InvalidOperation,
2231 'target exponent out of bounds in quantize')
2232
2233 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002234 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002235 return ans._fix(context)
2236
2237 self_adjusted = self.adjusted()
2238 if self_adjusted > context.Emax:
2239 return context._raise_error(InvalidOperation,
2240 'exponent of quantize result too large for current context')
2241 if self_adjusted - exp._exp + 1 > context.prec:
2242 return context._raise_error(InvalidOperation,
2243 'quantize result has too many digits for current context')
2244
2245 ans = self._rescale(exp._exp, rounding)
2246 if ans.adjusted() > context.Emax:
2247 return context._raise_error(InvalidOperation,
2248 'exponent of quantize result too large for current context')
2249 if len(ans._int) > context.prec:
2250 return context._raise_error(InvalidOperation,
2251 'quantize result has too many digits for current context')
2252
2253 # raise appropriate flags
2254 if ans._exp > self._exp:
2255 context._raise_error(Rounded)
2256 if ans != self:
2257 context._raise_error(Inexact)
2258 if ans and ans.adjusted() < context.Emin:
2259 context._raise_error(Subnormal)
2260
2261 # call to fix takes care of any necessary folddown
2262 ans = ans._fix(context)
2263 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002264
2265 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002266 """Return True if self and other have the same exponent; otherwise
2267 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002268
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002269 If either operand is a special value, the following rules are used:
2270 * return True if both operands are infinities
2271 * return True if both operands are NaNs
2272 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002273 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002274 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002275 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002276 return (self.is_nan() and other.is_nan() or
2277 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002278 return self._exp == other._exp
2279
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002280 def _rescale(self, exp, rounding):
2281 """Rescale self so that the exponent is exp, either by padding with zeros
2282 or by truncating digits, using the given rounding mode.
2283
2284 Specials are returned without change. This operation is
2285 quiet: it raises no flags, and uses no information from the
2286 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002287
2288 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002289 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002290 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002291 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002292 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002293 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002294 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002295
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002296 if self._exp >= exp:
2297 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002298 return _dec_from_triple(self._sign,
2299 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002300
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002301 # too many digits; round and lose data. If self.adjusted() <
2302 # exp-1, replace self by 10**(exp-1) before rounding
2303 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002304 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002305 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002306 digits = 0
2307 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002308 changed = this_function(digits)
2309 coeff = self._int[:digits] or '0'
2310 if changed == 1:
2311 coeff = str(int(coeff)+1)
2312 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002313
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002314 def to_integral_exact(self, rounding=None, context=None):
2315 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002316
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002317 If no rounding mode is specified, take the rounding mode from
2318 the context. This method raises the Rounded and Inexact flags
2319 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002320
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002321 See also: to_integral_value, which does exactly the same as
2322 this method except that it doesn't raise Inexact or Rounded.
2323 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002324 if self._is_special:
2325 ans = self._check_nans(context=context)
2326 if ans:
2327 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002328 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002329 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002330 return Decimal(self)
2331 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002332 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002333 if context is None:
2334 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002335 if rounding is None:
2336 rounding = context.rounding
2337 context._raise_error(Rounded)
2338 ans = self._rescale(0, rounding)
2339 if ans != self:
2340 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002341 return ans
2342
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002343 def to_integral_value(self, rounding=None, context=None):
2344 """Rounds to the nearest integer, without raising inexact, rounded."""
2345 if context is None:
2346 context = getcontext()
2347 if rounding is None:
2348 rounding = context.rounding
2349 if self._is_special:
2350 ans = self._check_nans(context=context)
2351 if ans:
2352 return ans
2353 return Decimal(self)
2354 if self._exp >= 0:
2355 return Decimal(self)
2356 else:
2357 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002358
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002359 # the method name changed, but we provide also the old one, for compatibility
2360 to_integral = to_integral_value
2361
2362 def sqrt(self, context=None):
2363 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002364 if self._is_special:
2365 ans = self._check_nans(context=context)
2366 if ans:
2367 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002368
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002369 if self._isinfinity() and self._sign == 0:
2370 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002371
2372 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002373 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002374 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002375 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002376
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002377 if context is None:
2378 context = getcontext()
2379
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002380 if self._sign == 1:
2381 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2382
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002383 # At this point self represents a positive number. Let p be
2384 # the desired precision and express self in the form c*100**e
2385 # with c a positive real number and e an integer, c and e
2386 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2387 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2388 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2389 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2390 # the closest integer to sqrt(c) with the even integer chosen
2391 # in the case of a tie.
2392 #
2393 # To ensure correct rounding in all cases, we use the
2394 # following trick: we compute the square root to an extra
2395 # place (precision p+1 instead of precision p), rounding down.
2396 # Then, if the result is inexact and its last digit is 0 or 5,
2397 # we increase the last digit to 1 or 6 respectively; if it's
2398 # exact we leave the last digit alone. Now the final round to
2399 # p places (or fewer in the case of underflow) will round
2400 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002401
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002402 # use an extra digit of precision
2403 prec = context.prec+1
2404
2405 # write argument in the form c*100**e where e = self._exp//2
2406 # is the 'ideal' exponent, to be used if the square root is
2407 # exactly representable. l is the number of 'digits' of c in
2408 # base 100, so that 100**(l-1) <= c < 100**l.
2409 op = _WorkRep(self)
2410 e = op.exp >> 1
2411 if op.exp & 1:
2412 c = op.int * 10
2413 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002414 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002415 c = op.int
2416 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002417
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002418 # rescale so that c has exactly prec base 100 'digits'
2419 shift = prec-l
2420 if shift >= 0:
2421 c *= 100**shift
2422 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002423 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002424 c, remainder = divmod(c, 100**-shift)
2425 exact = not remainder
2426 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002427
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002428 # find n = floor(sqrt(c)) using Newton's method
2429 n = 10**prec
2430 while True:
2431 q = c//n
2432 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002433 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002434 else:
2435 n = n + q >> 1
2436 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002437
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002438 if exact:
2439 # result is exact; rescale to use ideal exponent e
2440 if shift >= 0:
2441 # assert n % 10**shift == 0
2442 n //= 10**shift
2443 else:
2444 n *= 10**-shift
2445 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002446 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002447 # result is not exact; fix last digit as described above
2448 if n % 5 == 0:
2449 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002450
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002451 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002452
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002453 # round, and fit to current context
2454 context = context._shallow_copy()
2455 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002456 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002457 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002458
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002459 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002460
2461 def max(self, other, context=None):
2462 """Returns the larger value.
2463
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002464 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002465 NaN (and signals if one is sNaN). Also rounds.
2466 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002467 other = _convert_other(other, raiseit=True)
2468
2469 if context is None:
2470 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002471
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002472 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002473 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002474 # number is always returned
2475 sn = self._isnan()
2476 on = other._isnan()
2477 if sn or on:
2478 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002479 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002480 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002481 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002482 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002483
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002484 c = self.__cmp__(other)
2485 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002486 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002487 # then an ordering is applied:
2488 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002489 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002490 # positive sign and min returns the operand with the negative sign
2491 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002492 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002493 # the result. This is exactly the ordering used in compare_total.
2494 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002495
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002496 if c == -1:
2497 ans = other
2498 else:
2499 ans = self
2500
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002501 if context._rounding_decision == ALWAYS_ROUND:
2502 return ans._fix(context)
2503 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002504
2505 def min(self, other, context=None):
2506 """Returns the smaller value.
2507
Guido van Rossumd8faa362007-04-27 19:54:29 +00002508 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002509 NaN (and signals if one is sNaN). Also rounds.
2510 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002511 other = _convert_other(other, raiseit=True)
2512
2513 if context is None:
2514 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002515
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002516 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002517 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002518 # number is always returned
2519 sn = self._isnan()
2520 on = other._isnan()
2521 if sn or on:
2522 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002523 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002524 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002525 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002526 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002527
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002528 c = self.__cmp__(other)
2529 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002530 c = self.compare_total(other)
2531
2532 if c == -1:
2533 ans = self
2534 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002535 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002536
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002537 if context._rounding_decision == ALWAYS_ROUND:
2538 return ans._fix(context)
2539 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002540
2541 def _isinteger(self):
2542 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002543 if self._is_special:
2544 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002545 if self._exp >= 0:
2546 return True
2547 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002548 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002549
2550 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002551 """Returns True if self is even. Assumes self is an integer."""
2552 if not self or self._exp > 0:
2553 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002554 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002555
2556 def adjusted(self):
2557 """Return the adjusted exponent of self"""
2558 try:
2559 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002560 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002561 except TypeError:
2562 return 0
2563
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002564 def canonical(self, context=None):
2565 """Returns the same Decimal object.
2566
2567 As we do not have different encodings for the same number, the
2568 received object already is in its canonical form.
2569 """
2570 return self
2571
2572 def compare_signal(self, other, context=None):
2573 """Compares self to the other operand numerically.
2574
2575 It's pretty much like compare(), but all NaNs signal, with signaling
2576 NaNs taking precedence over quiet NaNs.
2577 """
2578 if context is None:
2579 context = getcontext()
2580
2581 self_is_nan = self._isnan()
2582 other_is_nan = other._isnan()
2583 if self_is_nan == 2:
2584 return context._raise_error(InvalidOperation, 'sNaN',
2585 1, self)
2586 if other_is_nan == 2:
2587 return context._raise_error(InvalidOperation, 'sNaN',
2588 1, other)
2589 if self_is_nan:
2590 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2591 1, self)
2592 if other_is_nan:
2593 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2594 1, other)
2595 return self.compare(other, context=context)
2596
2597 def compare_total(self, other):
2598 """Compares self to other using the abstract representations.
2599
2600 This is not like the standard compare, which use their numerical
2601 value. Note that a total ordering is defined for all possible abstract
2602 representations.
2603 """
2604 # if one is negative and the other is positive, it's easy
2605 if self._sign and not other._sign:
2606 return Dec_n1
2607 if not self._sign and other._sign:
2608 return Dec_p1
2609 sign = self._sign
2610
2611 # let's handle both NaN types
2612 self_nan = self._isnan()
2613 other_nan = other._isnan()
2614 if self_nan or other_nan:
2615 if self_nan == other_nan:
2616 if self._int < other._int:
2617 if sign:
2618 return Dec_p1
2619 else:
2620 return Dec_n1
2621 if self._int > other._int:
2622 if sign:
2623 return Dec_n1
2624 else:
2625 return Dec_p1
2626 return Dec_0
2627
2628 if sign:
2629 if self_nan == 1:
2630 return Dec_n1
2631 if other_nan == 1:
2632 return Dec_p1
2633 if self_nan == 2:
2634 return Dec_n1
2635 if other_nan == 2:
2636 return Dec_p1
2637 else:
2638 if self_nan == 1:
2639 return Dec_p1
2640 if other_nan == 1:
2641 return Dec_n1
2642 if self_nan == 2:
2643 return Dec_p1
2644 if other_nan == 2:
2645 return Dec_n1
2646
2647 if self < other:
2648 return Dec_n1
2649 if self > other:
2650 return Dec_p1
2651
2652 if self._exp < other._exp:
2653 if sign:
2654 return Dec_p1
2655 else:
2656 return Dec_n1
2657 if self._exp > other._exp:
2658 if sign:
2659 return Dec_n1
2660 else:
2661 return Dec_p1
2662 return Dec_0
2663
2664
2665 def compare_total_mag(self, other):
2666 """Compares self to other using abstract repr., ignoring sign.
2667
2668 Like compare_total, but with operand's sign ignored and assumed to be 0.
2669 """
2670 s = self.copy_abs()
2671 o = other.copy_abs()
2672 return s.compare_total(o)
2673
2674 def copy_abs(self):
2675 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002676 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002677
2678 def copy_negate(self):
2679 """Returns a copy with the sign inverted."""
2680 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002681 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002682 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002683 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002684
2685 def copy_sign(self, other):
2686 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002687 return _dec_from_triple(other._sign, self._int,
2688 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002689
2690 def exp(self, context=None):
2691 """Returns e ** self."""
2692
2693 if context is None:
2694 context = getcontext()
2695
2696 # exp(NaN) = NaN
2697 ans = self._check_nans(context=context)
2698 if ans:
2699 return ans
2700
2701 # exp(-Infinity) = 0
2702 if self._isinfinity() == -1:
2703 return Dec_0
2704
2705 # exp(0) = 1
2706 if not self:
2707 return Dec_p1
2708
2709 # exp(Infinity) = Infinity
2710 if self._isinfinity() == 1:
2711 return Decimal(self)
2712
2713 # the result is now guaranteed to be inexact (the true
2714 # mathematical result is transcendental). There's no need to
2715 # raise Rounded and Inexact here---they'll always be raised as
2716 # a result of the call to _fix.
2717 p = context.prec
2718 adj = self.adjusted()
2719
2720 # we only need to do any computation for quite a small range
2721 # of adjusted exponents---for example, -29 <= adj <= 10 for
2722 # the default context. For smaller exponent the result is
2723 # indistinguishable from 1 at the given precision, while for
2724 # larger exponent the result either overflows or underflows.
2725 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2726 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002727 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002728 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2729 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002730 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002731 elif self._sign == 0 and adj < -p:
2732 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002733 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002734 elif self._sign == 1 and adj < -p-1:
2735 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002736 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002737 # general case
2738 else:
2739 op = _WorkRep(self)
2740 c, e = op.int, op.exp
2741 if op.sign == 1:
2742 c = -c
2743
2744 # compute correctly rounded result: increase precision by
2745 # 3 digits at a time until we get an unambiguously
2746 # roundable result
2747 extra = 3
2748 while True:
2749 coeff, exp = _dexp(c, e, p+extra)
2750 if coeff % (5*10**(len(str(coeff))-p-1)):
2751 break
2752 extra += 3
2753
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002754 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002755
2756 # at this stage, ans should round correctly with *any*
2757 # rounding mode, not just with ROUND_HALF_EVEN
2758 context = context._shallow_copy()
2759 rounding = context._set_rounding(ROUND_HALF_EVEN)
2760 ans = ans._fix(context)
2761 context.rounding = rounding
2762
2763 return ans
2764
2765 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002766 """Return True if self is canonical; otherwise return False.
2767
2768 Currently, the encoding of a Decimal instance is always
2769 canonical, so this method returns True for any Decimal.
2770 """
2771 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002772
2773 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002774 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002775
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002776 A Decimal instance is considered finite if it is neither
2777 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002778 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002779 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002780
2781 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002782 """Return True if self is infinite; otherwise return False."""
2783 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002784
2785 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002786 """Return True if self is a qNaN or sNaN; otherwise return False."""
2787 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002788
2789 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002790 """Return True if self is a normal number; otherwise return False."""
2791 if self._is_special or not self:
2792 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002793 if context is None:
2794 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002795 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002796
2797 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002798 """Return True if self is a quiet NaN; otherwise return False."""
2799 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002800
2801 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002802 """Return True if self is negative; otherwise return False."""
2803 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002804
2805 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002806 """Return True if self is a signaling NaN; otherwise return False."""
2807 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002808
2809 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002810 """Return True if self is subnormal; otherwise return False."""
2811 if self._is_special or not self:
2812 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002813 if context is None:
2814 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002815 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002816
2817 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002818 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002819 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002820
2821 def _ln_exp_bound(self):
2822 """Compute a lower bound for the adjusted exponent of self.ln().
2823 In other words, compute r such that self.ln() >= 10**r. Assumes
2824 that self is finite and positive and that self != 1.
2825 """
2826
2827 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2828 adj = self._exp + len(self._int) - 1
2829 if adj >= 1:
2830 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2831 return len(str(adj*23//10)) - 1
2832 if adj <= -2:
2833 # argument <= 0.1
2834 return len(str((-1-adj)*23//10)) - 1
2835 op = _WorkRep(self)
2836 c, e = op.int, op.exp
2837 if adj == 0:
2838 # 1 < self < 10
2839 num = str(c-10**-e)
2840 den = str(c)
2841 return len(num) - len(den) - (num < den)
2842 # adj == -1, 0.1 <= self < 1
2843 return e + len(str(10**-e - c)) - 1
2844
2845
2846 def ln(self, context=None):
2847 """Returns the natural (base e) logarithm of self."""
2848
2849 if context is None:
2850 context = getcontext()
2851
2852 # ln(NaN) = NaN
2853 ans = self._check_nans(context=context)
2854 if ans:
2855 return ans
2856
2857 # ln(0.0) == -Infinity
2858 if not self:
2859 return negInf
2860
2861 # ln(Infinity) = Infinity
2862 if self._isinfinity() == 1:
2863 return Inf
2864
2865 # ln(1.0) == 0.0
2866 if self == Dec_p1:
2867 return Dec_0
2868
2869 # ln(negative) raises InvalidOperation
2870 if self._sign == 1:
2871 return context._raise_error(InvalidOperation,
2872 'ln of a negative value')
2873
2874 # result is irrational, so necessarily inexact
2875 op = _WorkRep(self)
2876 c, e = op.int, op.exp
2877 p = context.prec
2878
2879 # correctly rounded result: repeatedly increase precision by 3
2880 # until we get an unambiguously roundable result
2881 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2882 while True:
2883 coeff = _dlog(c, e, places)
2884 # assert len(str(abs(coeff)))-p >= 1
2885 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2886 break
2887 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002888 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002889
2890 context = context._shallow_copy()
2891 rounding = context._set_rounding(ROUND_HALF_EVEN)
2892 ans = ans._fix(context)
2893 context.rounding = rounding
2894 return ans
2895
2896 def _log10_exp_bound(self):
2897 """Compute a lower bound for the adjusted exponent of self.log10().
2898 In other words, find r such that self.log10() >= 10**r.
2899 Assumes that self is finite and positive and that self != 1.
2900 """
2901
2902 # For x >= 10 or x < 0.1 we only need a bound on the integer
2903 # part of log10(self), and this comes directly from the
2904 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2905 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2906 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2907
2908 adj = self._exp + len(self._int) - 1
2909 if adj >= 1:
2910 # self >= 10
2911 return len(str(adj))-1
2912 if adj <= -2:
2913 # self < 0.1
2914 return len(str(-1-adj))-1
2915 op = _WorkRep(self)
2916 c, e = op.int, op.exp
2917 if adj == 0:
2918 # 1 < self < 10
2919 num = str(c-10**-e)
2920 den = str(231*c)
2921 return len(num) - len(den) - (num < den) + 2
2922 # adj == -1, 0.1 <= self < 1
2923 num = str(10**-e-c)
2924 return len(num) + e - (num < "231") - 1
2925
2926 def log10(self, context=None):
2927 """Returns the base 10 logarithm of self."""
2928
2929 if context is None:
2930 context = getcontext()
2931
2932 # log10(NaN) = NaN
2933 ans = self._check_nans(context=context)
2934 if ans:
2935 return ans
2936
2937 # log10(0.0) == -Infinity
2938 if not self:
2939 return negInf
2940
2941 # log10(Infinity) = Infinity
2942 if self._isinfinity() == 1:
2943 return Inf
2944
2945 # log10(negative or -Infinity) raises InvalidOperation
2946 if self._sign == 1:
2947 return context._raise_error(InvalidOperation,
2948 'log10 of a negative value')
2949
2950 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002951 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002952 # answer may need rounding
2953 ans = Decimal(self._exp + len(self._int) - 1)
2954 else:
2955 # result is irrational, so necessarily inexact
2956 op = _WorkRep(self)
2957 c, e = op.int, op.exp
2958 p = context.prec
2959
2960 # correctly rounded result: repeatedly increase precision
2961 # until result is unambiguously roundable
2962 places = p-self._log10_exp_bound()+2
2963 while True:
2964 coeff = _dlog10(c, e, places)
2965 # assert len(str(abs(coeff)))-p >= 1
2966 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2967 break
2968 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002969 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002970
2971 context = context._shallow_copy()
2972 rounding = context._set_rounding(ROUND_HALF_EVEN)
2973 ans = ans._fix(context)
2974 context.rounding = rounding
2975 return ans
2976
2977 def logb(self, context=None):
2978 """ Returns the exponent of the magnitude of self's MSD.
2979
2980 The result is the integer which is the exponent of the magnitude
2981 of the most significant digit of self (as though it were truncated
2982 to a single digit while maintaining the value of that digit and
2983 without limiting the resulting exponent).
2984 """
2985 # logb(NaN) = NaN
2986 ans = self._check_nans(context=context)
2987 if ans:
2988 return ans
2989
2990 if context is None:
2991 context = getcontext()
2992
2993 # logb(+/-Inf) = +Inf
2994 if self._isinfinity():
2995 return Inf
2996
2997 # logb(0) = -Inf, DivisionByZero
2998 if not self:
2999 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3000
3001 # otherwise, simply return the adjusted exponent of self, as a
3002 # Decimal. Note that no attempt is made to fit the result
3003 # into the current context.
3004 return Decimal(self.adjusted())
3005
3006 def _islogical(self):
3007 """Return True if self is a logical operand.
3008
3009 For being logical, it must be a finite numbers with a sign of 0,
3010 an exponent of 0, and a coefficient whose digits must all be
3011 either 0 or 1.
3012 """
3013 if self._sign != 0 or self._exp != 0:
3014 return False
3015 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003016 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003017 return False
3018 return True
3019
3020 def _fill_logical(self, context, opa, opb):
3021 dif = context.prec - len(opa)
3022 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003023 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003024 elif dif < 0:
3025 opa = opa[-context.prec:]
3026 dif = context.prec - len(opb)
3027 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003028 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003029 elif dif < 0:
3030 opb = opb[-context.prec:]
3031 return opa, opb
3032
3033 def logical_and(self, other, context=None):
3034 """Applies an 'and' operation between self and other's digits."""
3035 if context is None:
3036 context = getcontext()
3037 if not self._islogical() or not other._islogical():
3038 return context._raise_error(InvalidOperation)
3039
3040 # fill to context.prec
3041 (opa, opb) = self._fill_logical(context, self._int, other._int)
3042
3043 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003044 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3045 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003046
3047 def logical_invert(self, context=None):
3048 """Invert all its digits."""
3049 if context is None:
3050 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003051 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3052 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003053
3054 def logical_or(self, other, context=None):
3055 """Applies an 'or' 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_xor(self, other, context=None):
3069 """Applies an 'xor' operation between self and other's digits."""
3070 if context is None:
3071 context = getcontext()
3072 if not self._islogical() or not other._islogical():
3073 return context._raise_error(InvalidOperation)
3074
3075 # fill to context.prec
3076 (opa, opb) = self._fill_logical(context, self._int, other._int)
3077
3078 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003079 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3080 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003081
3082 def max_mag(self, other, context=None):
3083 """Compares the values numerically with their sign ignored."""
3084 other = _convert_other(other, raiseit=True)
3085
3086 if context is None:
3087 context = getcontext()
3088
3089 if self._is_special or other._is_special:
3090 # If one operand is a quiet NaN and the other is number, then the
3091 # number is always returned
3092 sn = self._isnan()
3093 on = other._isnan()
3094 if sn or on:
3095 if on == 1 and sn != 2:
3096 return self._fix_nan(context)
3097 if sn == 1 and on != 2:
3098 return other._fix_nan(context)
3099 return self._check_nans(other, context)
3100
3101 c = self.copy_abs().__cmp__(other.copy_abs())
3102 if c == 0:
3103 c = self.compare_total(other)
3104
3105 if c == -1:
3106 ans = other
3107 else:
3108 ans = self
3109
3110 if context._rounding_decision == ALWAYS_ROUND:
3111 return ans._fix(context)
3112 return ans
3113
3114 def min_mag(self, other, context=None):
3115 """Compares the values numerically with their sign ignored."""
3116 other = _convert_other(other, raiseit=True)
3117
3118 if context is None:
3119 context = getcontext()
3120
3121 if self._is_special or other._is_special:
3122 # If one operand is a quiet NaN and the other is number, then the
3123 # number is always returned
3124 sn = self._isnan()
3125 on = other._isnan()
3126 if sn or on:
3127 if on == 1 and sn != 2:
3128 return self._fix_nan(context)
3129 if sn == 1 and on != 2:
3130 return other._fix_nan(context)
3131 return self._check_nans(other, context)
3132
3133 c = self.copy_abs().__cmp__(other.copy_abs())
3134 if c == 0:
3135 c = self.compare_total(other)
3136
3137 if c == -1:
3138 ans = self
3139 else:
3140 ans = other
3141
3142 if context._rounding_decision == ALWAYS_ROUND:
3143 return ans._fix(context)
3144 return ans
3145
3146 def next_minus(self, context=None):
3147 """Returns the largest representable number smaller than itself."""
3148 if context is None:
3149 context = getcontext()
3150
3151 ans = self._check_nans(context=context)
3152 if ans:
3153 return ans
3154
3155 if self._isinfinity() == -1:
3156 return negInf
3157 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003158 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003159
3160 context = context.copy()
3161 context._set_rounding(ROUND_FLOOR)
3162 context._ignore_all_flags()
3163 new_self = self._fix(context)
3164 if new_self != self:
3165 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003166 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3167 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003168
3169 def next_plus(self, context=None):
3170 """Returns the smallest representable number larger than itself."""
3171 if context is None:
3172 context = getcontext()
3173
3174 ans = self._check_nans(context=context)
3175 if ans:
3176 return ans
3177
3178 if self._isinfinity() == 1:
3179 return Inf
3180 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003181 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003182
3183 context = context.copy()
3184 context._set_rounding(ROUND_CEILING)
3185 context._ignore_all_flags()
3186 new_self = self._fix(context)
3187 if new_self != self:
3188 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003189 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3190 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003191
3192 def next_toward(self, other, context=None):
3193 """Returns the number closest to self, in the direction towards other.
3194
3195 The result is the closest representable number to self
3196 (excluding self) that is in the direction towards other,
3197 unless both have the same value. If the two operands are
3198 numerically equal, then the result is a copy of self with the
3199 sign set to be the same as the sign of other.
3200 """
3201 other = _convert_other(other, raiseit=True)
3202
3203 if context is None:
3204 context = getcontext()
3205
3206 ans = self._check_nans(other, context)
3207 if ans:
3208 return ans
3209
3210 comparison = self.__cmp__(other)
3211 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003212 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003213
3214 if comparison == -1:
3215 ans = self.next_plus(context)
3216 else: # comparison == 1
3217 ans = self.next_minus(context)
3218
3219 # decide which flags to raise using value of ans
3220 if ans._isinfinity():
3221 context._raise_error(Overflow,
3222 'Infinite result from next_toward',
3223 ans._sign)
3224 context._raise_error(Rounded)
3225 context._raise_error(Inexact)
3226 elif ans.adjusted() < context.Emin:
3227 context._raise_error(Underflow)
3228 context._raise_error(Subnormal)
3229 context._raise_error(Rounded)
3230 context._raise_error(Inexact)
3231 # if precision == 1 then we don't raise Clamped for a
3232 # result 0E-Etiny.
3233 if not ans:
3234 context._raise_error(Clamped)
3235
3236 return ans
3237
3238 def number_class(self, context=None):
3239 """Returns an indication of the class of self.
3240
3241 The class is one of the following strings:
3242 -sNaN
3243 -NaN
3244 -Infinity
3245 -Normal
3246 -Subnormal
3247 -Zero
3248 +Zero
3249 +Subnormal
3250 +Normal
3251 +Infinity
3252 """
3253 if self.is_snan():
3254 return "sNaN"
3255 if self.is_qnan():
3256 return "NaN"
3257 inf = self._isinfinity()
3258 if inf == 1:
3259 return "+Infinity"
3260 if inf == -1:
3261 return "-Infinity"
3262 if self.is_zero():
3263 if self._sign:
3264 return "-Zero"
3265 else:
3266 return "+Zero"
3267 if context is None:
3268 context = getcontext()
3269 if self.is_subnormal(context=context):
3270 if self._sign:
3271 return "-Subnormal"
3272 else:
3273 return "+Subnormal"
3274 # just a normal, regular, boring number, :)
3275 if self._sign:
3276 return "-Normal"
3277 else:
3278 return "+Normal"
3279
3280 def radix(self):
3281 """Just returns 10, as this is Decimal, :)"""
3282 return Decimal(10)
3283
3284 def rotate(self, other, context=None):
3285 """Returns a rotated copy of self, value-of-other times."""
3286 if context is None:
3287 context = getcontext()
3288
3289 ans = self._check_nans(other, context)
3290 if ans:
3291 return ans
3292
3293 if other._exp != 0:
3294 return context._raise_error(InvalidOperation)
3295 if not (-context.prec <= int(other) <= context.prec):
3296 return context._raise_error(InvalidOperation)
3297
3298 if self._isinfinity():
3299 return Decimal(self)
3300
3301 # get values, pad if necessary
3302 torot = int(other)
3303 rotdig = self._int
3304 topad = context.prec - len(rotdig)
3305 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003306 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003307
3308 # let's rotate!
3309 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003310 return _dec_from_triple(self._sign,
3311 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003312
3313 def scaleb (self, other, context=None):
3314 """Returns self operand after adding the second value to its exp."""
3315 if context is None:
3316 context = getcontext()
3317
3318 ans = self._check_nans(other, context)
3319 if ans:
3320 return ans
3321
3322 if other._exp != 0:
3323 return context._raise_error(InvalidOperation)
3324 liminf = -2 * (context.Emax + context.prec)
3325 limsup = 2 * (context.Emax + context.prec)
3326 if not (liminf <= int(other) <= limsup):
3327 return context._raise_error(InvalidOperation)
3328
3329 if self._isinfinity():
3330 return Decimal(self)
3331
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003332 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003333 d = d._fix(context)
3334 return d
3335
3336 def shift(self, other, context=None):
3337 """Returns a shifted copy of self, value-of-other times."""
3338 if context is None:
3339 context = getcontext()
3340
3341 ans = self._check_nans(other, context)
3342 if ans:
3343 return ans
3344
3345 if other._exp != 0:
3346 return context._raise_error(InvalidOperation)
3347 if not (-context.prec <= int(other) <= context.prec):
3348 return context._raise_error(InvalidOperation)
3349
3350 if self._isinfinity():
3351 return Decimal(self)
3352
3353 # get values, pad if necessary
3354 torot = int(other)
3355 if not torot:
3356 return Decimal(self)
3357 rotdig = self._int
3358 topad = context.prec - len(rotdig)
3359 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003360 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003361
3362 # let's shift!
3363 if torot < 0:
3364 rotated = rotdig[:torot]
3365 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003366 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003367 rotated = rotated[-context.prec:]
3368
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003369 return _dec_from_triple(self._sign,
3370 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003371
Guido van Rossumd8faa362007-04-27 19:54:29 +00003372 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003373 def __reduce__(self):
3374 return (self.__class__, (str(self),))
3375
3376 def __copy__(self):
3377 if type(self) == Decimal:
3378 return self # I'm immutable; therefore I am my own clone
3379 return self.__class__(str(self))
3380
3381 def __deepcopy__(self, memo):
3382 if type(self) == Decimal:
3383 return self # My components are also immutable
3384 return self.__class__(str(self))
3385
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003386def _dec_from_triple(sign, coefficient, exponent, special=False):
3387 """Create a decimal instance directly, without any validation,
3388 normalization (e.g. removal of leading zeros) or argument
3389 conversion.
3390
3391 This function is for *internal use only*.
3392 """
3393
3394 self = object.__new__(Decimal)
3395 self._sign = sign
3396 self._int = coefficient
3397 self._exp = exponent
3398 self._is_special = special
3399
3400 return self
3401
Guido van Rossumd8faa362007-04-27 19:54:29 +00003402##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003403
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003404
3405# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003406rounding_functions = [name for name in Decimal.__dict__.keys()
3407 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003408for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003409 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003410 globalname = name[1:].upper()
3411 val = globals()[globalname]
3412 Decimal._pick_rounding_function[val] = name
3413
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003414del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003415
Thomas Wouters89f507f2006-12-13 04:49:30 +00003416class _ContextManager(object):
3417 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003418
Thomas Wouters89f507f2006-12-13 04:49:30 +00003419 Sets a copy of the supplied context in __enter__() and restores
3420 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003421 """
3422 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003423 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003424 def __enter__(self):
3425 self.saved_context = getcontext()
3426 setcontext(self.new_context)
3427 return self.new_context
3428 def __exit__(self, t, v, tb):
3429 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003430
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003431class Context(object):
3432 """Contains the context for a Decimal instance.
3433
3434 Contains:
3435 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003436 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003437 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003438 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003439 raised when it is caused. Otherwise, a value is
3440 substituted in.
3441 flags - When an exception is caused, flags[exception] is incremented.
3442 (Whether or not the trap_enabler is set)
3443 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003444 Emin - Minimum exponent
3445 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003446 capitals - If 1, 1*10^1 is printed as 1E+1.
3447 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003448 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003449 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003450
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003451 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003452 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003453 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003454 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003455 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003456 _ignored_flags=None):
3457 if flags is None:
3458 flags = []
3459 if _ignored_flags is None:
3460 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003461 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003462 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003463 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003464 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003465 for name, val in locals().items():
3466 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003467 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003468 else:
3469 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003470 del self.self
3471
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003472 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003473 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003474 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003475 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3476 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3477 % vars(self))
3478 names = [f.__name__ for f, v in self.flags.items() if v]
3479 s.append('flags=[' + ', '.join(names) + ']')
3480 names = [t.__name__ for t, v in self.traps.items() if v]
3481 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003482 return ', '.join(s) + ')'
3483
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003484 def clear_flags(self):
3485 """Reset all flags to zero"""
3486 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003487 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003488
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003489 def _shallow_copy(self):
3490 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003491 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003492 self._rounding_decision, self.Emin, self.Emax,
3493 self.capitals, self._clamp, self._ignored_flags)
3494 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003495
3496 def copy(self):
3497 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003498 nc = Context(self.prec, self.rounding, self.traps.copy(),
3499 self.flags.copy(), self._rounding_decision, self.Emin,
3500 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003501 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003502 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003503
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003504 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003505 """Handles an error
3506
3507 If the flag is in _ignored_flags, returns the default response.
3508 Otherwise, it increments the flag, then, if the corresponding
3509 trap_enabler is set, it reaises the exception. Otherwise, it returns
3510 the default value after incrementing the flag.
3511 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003512 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003513 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003514 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003515 return error().handle(self, *args)
3516
3517 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003518 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003519 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003520 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003521
3522 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003523 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003524 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003525
3526 def _ignore_all_flags(self):
3527 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003528 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003529
3530 def _ignore_flags(self, *flags):
3531 """Ignore the flags, if they are raised"""
3532 # Do not mutate-- This way, copies of a context leave the original
3533 # alone.
3534 self._ignored_flags = (self._ignored_flags + list(flags))
3535 return list(flags)
3536
3537 def _regard_flags(self, *flags):
3538 """Stop ignoring the flags, if they are raised"""
3539 if flags and isinstance(flags[0], (tuple,list)):
3540 flags = flags[0]
3541 for flag in flags:
3542 self._ignored_flags.remove(flag)
3543
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003544 def __hash__(self):
3545 """A Context cannot be hashed."""
3546 # We inherit object.__hash__, so we must deny this explicitly
Guido van Rossumd8faa362007-04-27 19:54:29 +00003547 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003548
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003549 def Etiny(self):
3550 """Returns Etiny (= Emin - prec + 1)"""
3551 return int(self.Emin - self.prec + 1)
3552
3553 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003554 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003555 return int(self.Emax - self.prec + 1)
3556
3557 def _set_rounding_decision(self, type):
3558 """Sets the rounding decision.
3559
3560 Sets the rounding decision, and returns the current (previous)
3561 rounding decision. Often used like:
3562
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003563 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003564 # That so you don't change the calling context
3565 # if an error occurs in the middle (say DivisionImpossible is raised).
3566
3567 rounding = context._set_rounding_decision(NEVER_ROUND)
3568 instance = instance / Decimal(2)
3569 context._set_rounding_decision(rounding)
3570
3571 This will make it not round for that operation.
3572 """
3573
3574 rounding = self._rounding_decision
3575 self._rounding_decision = type
3576 return rounding
3577
3578 def _set_rounding(self, type):
3579 """Sets the rounding type.
3580
3581 Sets the rounding type, and returns the current (previous)
3582 rounding type. Often used like:
3583
3584 context = context.copy()
3585 # so you don't change the calling context
3586 # if an error occurs in the middle.
3587 rounding = context._set_rounding(ROUND_UP)
3588 val = self.__sub__(other, context=context)
3589 context._set_rounding(rounding)
3590
3591 This will make it round up for that operation.
3592 """
3593 rounding = self.rounding
3594 self.rounding= type
3595 return rounding
3596
Raymond Hettingerfed52962004-07-14 15:41:57 +00003597 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003598 """Creates a new Decimal instance but using self as context."""
3599 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003600 if d._isnan() and len(d._int) > self.prec - self._clamp:
3601 return self._raise_error(ConversionSyntax,
3602 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003603 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003604
Guido van Rossumd8faa362007-04-27 19:54:29 +00003605 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003606 def abs(self, a):
3607 """Returns the absolute value of the operand.
3608
3609 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003610 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003611 the plus operation on the operand.
3612
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003613 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003614 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003615 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003616 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003617 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003618 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003619 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003620 Decimal("101.5")
3621 """
3622 return a.__abs__(context=self)
3623
3624 def add(self, a, b):
3625 """Return the sum of the two operands.
3626
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003627 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003628 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003629 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003630 Decimal("1.02E+4")
3631 """
3632 return a.__add__(b, context=self)
3633
3634 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003635 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003636
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003637 def canonical(self, a):
3638 """Returns the same Decimal object.
3639
3640 As we do not have different encodings for the same number, the
3641 received object already is in its canonical form.
3642
3643 >>> ExtendedContext.canonical(Decimal('2.50'))
3644 Decimal("2.50")
3645 """
3646 return a.canonical(context=self)
3647
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003648 def compare(self, a, b):
3649 """Compares values numerically.
3650
3651 If the signs of the operands differ, a value representing each operand
3652 ('-1' if the operand is less than zero, '0' if the operand is zero or
3653 negative zero, or '1' if the operand is greater than zero) is used in
3654 place of that operand for the comparison instead of the actual
3655 operand.
3656
3657 The comparison is then effected by subtracting the second operand from
3658 the first and then returning a value according to the result of the
3659 subtraction: '-1' if the result is less than zero, '0' if the result is
3660 zero or negative zero, or '1' if the result is greater than zero.
3661
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003662 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003663 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003664 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003665 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003666 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003667 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003668 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003669 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003670 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003671 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003672 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003673 Decimal("-1")
3674 """
3675 return a.compare(b, context=self)
3676
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003677 def compare_signal(self, a, b):
3678 """Compares the values of the two operands numerically.
3679
3680 It's pretty much like compare(), but all NaNs signal, with signaling
3681 NaNs taking precedence over quiet NaNs.
3682
3683 >>> c = ExtendedContext
3684 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3685 Decimal("-1")
3686 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3687 Decimal("0")
3688 >>> c.flags[InvalidOperation] = 0
3689 >>> print(c.flags[InvalidOperation])
3690 0
3691 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3692 Decimal("NaN")
3693 >>> print(c.flags[InvalidOperation])
3694 1
3695 >>> c.flags[InvalidOperation] = 0
3696 >>> print(c.flags[InvalidOperation])
3697 0
3698 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3699 Decimal("NaN")
3700 >>> print(c.flags[InvalidOperation])
3701 1
3702 """
3703 return a.compare_signal(b, context=self)
3704
3705 def compare_total(self, a, b):
3706 """Compares two operands using their abstract representation.
3707
3708 This is not like the standard compare, which use their numerical
3709 value. Note that a total ordering is defined for all possible abstract
3710 representations.
3711
3712 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3713 Decimal("-1")
3714 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3715 Decimal("-1")
3716 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3717 Decimal("-1")
3718 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3719 Decimal("0")
3720 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3721 Decimal("1")
3722 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3723 Decimal("-1")
3724 """
3725 return a.compare_total(b)
3726
3727 def compare_total_mag(self, a, b):
3728 """Compares two operands using their abstract representation ignoring sign.
3729
3730 Like compare_total, but with operand's sign ignored and assumed to be 0.
3731 """
3732 return a.compare_total_mag(b)
3733
3734 def copy_abs(self, a):
3735 """Returns a copy of the operand with the sign set to 0.
3736
3737 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3738 Decimal("2.1")
3739 >>> ExtendedContext.copy_abs(Decimal('-100'))
3740 Decimal("100")
3741 """
3742 return a.copy_abs()
3743
3744 def copy_decimal(self, a):
3745 """Returns a copy of the decimal objet.
3746
3747 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3748 Decimal("2.1")
3749 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3750 Decimal("-1.00")
3751 """
3752 return Decimal(a)
3753
3754 def copy_negate(self, a):
3755 """Returns a copy of the operand with the sign inverted.
3756
3757 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3758 Decimal("-101.5")
3759 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3760 Decimal("101.5")
3761 """
3762 return a.copy_negate()
3763
3764 def copy_sign(self, a, b):
3765 """Copies the second operand's sign to the first one.
3766
3767 In detail, it returns a copy of the first operand with the sign
3768 equal to the sign of the second operand.
3769
3770 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3771 Decimal("1.50")
3772 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3773 Decimal("1.50")
3774 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3775 Decimal("-1.50")
3776 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3777 Decimal("-1.50")
3778 """
3779 return a.copy_sign(b)
3780
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003781 def divide(self, a, b):
3782 """Decimal division in a specified context.
3783
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003784 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003785 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003786 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003787 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003788 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003789 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003790 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003791 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003792 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003793 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003794 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003795 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003796 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003797 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003798 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003799 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003800 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003801 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003802 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003803 Decimal("1.20E+6")
3804 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003805 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003806
3807 def divide_int(self, a, b):
3808 """Divides two numbers and returns the integer part of the result.
3809
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003810 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003811 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003812 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003813 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003814 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003815 Decimal("3")
3816 """
3817 return a.__floordiv__(b, context=self)
3818
3819 def divmod(self, a, b):
3820 return a.__divmod__(b, context=self)
3821
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003822 def exp(self, a):
3823 """Returns e ** a.
3824
3825 >>> c = ExtendedContext.copy()
3826 >>> c.Emin = -999
3827 >>> c.Emax = 999
3828 >>> c.exp(Decimal('-Infinity'))
3829 Decimal("0")
3830 >>> c.exp(Decimal('-1'))
3831 Decimal("0.367879441")
3832 >>> c.exp(Decimal('0'))
3833 Decimal("1")
3834 >>> c.exp(Decimal('1'))
3835 Decimal("2.71828183")
3836 >>> c.exp(Decimal('0.693147181'))
3837 Decimal("2.00000000")
3838 >>> c.exp(Decimal('+Infinity'))
3839 Decimal("Infinity")
3840 """
3841 return a.exp(context=self)
3842
3843 def fma(self, a, b, c):
3844 """Returns a multiplied by b, plus c.
3845
3846 The first two operands are multiplied together, using multiply,
3847 the third operand is then added to the result of that
3848 multiplication, using add, all with only one final rounding.
3849
3850 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3851 Decimal("22")
3852 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3853 Decimal("-8")
3854 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3855 Decimal("1.38435736E+12")
3856 """
3857 return a.fma(b, c, context=self)
3858
3859 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003860 """Return True if the operand is canonical; otherwise return False.
3861
3862 Currently, the encoding of a Decimal instance is always
3863 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003864
3865 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003866 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003867 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003868 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003869
3870 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003871 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003872
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003873 A Decimal instance is considered finite if it is neither
3874 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003875
3876 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003877 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003878 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003879 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003880 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003881 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003882 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003883 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003884 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003885 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003886 """
3887 return a.is_finite()
3888
3889 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003890 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003891
3892 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003893 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003894 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003895 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003896 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003897 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003898 """
3899 return a.is_infinite()
3900
3901 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003902 """Return True if the operand is a qNaN or sNaN;
3903 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003904
3905 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003906 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003907 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003908 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003909 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003910 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003911 """
3912 return a.is_nan()
3913
3914 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003915 """Return True if the operand is a normal number;
3916 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003917
3918 >>> c = ExtendedContext.copy()
3919 >>> c.Emin = -999
3920 >>> c.Emax = 999
3921 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003922 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003923 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003924 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003925 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003926 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003927 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003928 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003929 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003930 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003931 """
3932 return a.is_normal(context=self)
3933
3934 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003935 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003936
3937 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003938 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003939 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003940 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003941 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003942 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003943 """
3944 return a.is_qnan()
3945
3946 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003947 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003948
3949 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003950 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003951 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003952 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003953 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003954 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003955 """
3956 return a.is_signed()
3957
3958 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003959 """Return True if the operand is a signaling NaN;
3960 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003961
3962 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003963 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003964 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003965 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003966 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003967 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003968 """
3969 return a.is_snan()
3970
3971 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003972 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003973
3974 >>> c = ExtendedContext.copy()
3975 >>> c.Emin = -999
3976 >>> c.Emax = 999
3977 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003978 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003979 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003980 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003981 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003982 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003983 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003984 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003985 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003986 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003987 """
3988 return a.is_subnormal(context=self)
3989
3990 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003991 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003992
3993 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003994 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003995 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003996 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003997 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003998 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003999 """
4000 return a.is_zero()
4001
4002 def ln(self, a):
4003 """Returns the natural (base e) logarithm of the operand.
4004
4005 >>> c = ExtendedContext.copy()
4006 >>> c.Emin = -999
4007 >>> c.Emax = 999
4008 >>> c.ln(Decimal('0'))
4009 Decimal("-Infinity")
4010 >>> c.ln(Decimal('1.000'))
4011 Decimal("0")
4012 >>> c.ln(Decimal('2.71828183'))
4013 Decimal("1.00000000")
4014 >>> c.ln(Decimal('10'))
4015 Decimal("2.30258509")
4016 >>> c.ln(Decimal('+Infinity'))
4017 Decimal("Infinity")
4018 """
4019 return a.ln(context=self)
4020
4021 def log10(self, a):
4022 """Returns the base 10 logarithm of the operand.
4023
4024 >>> c = ExtendedContext.copy()
4025 >>> c.Emin = -999
4026 >>> c.Emax = 999
4027 >>> c.log10(Decimal('0'))
4028 Decimal("-Infinity")
4029 >>> c.log10(Decimal('0.001'))
4030 Decimal("-3")
4031 >>> c.log10(Decimal('1.000'))
4032 Decimal("0")
4033 >>> c.log10(Decimal('2'))
4034 Decimal("0.301029996")
4035 >>> c.log10(Decimal('10'))
4036 Decimal("1")
4037 >>> c.log10(Decimal('70'))
4038 Decimal("1.84509804")
4039 >>> c.log10(Decimal('+Infinity'))
4040 Decimal("Infinity")
4041 """
4042 return a.log10(context=self)
4043
4044 def logb(self, a):
4045 """ Returns the exponent of the magnitude of the operand's MSD.
4046
4047 The result is the integer which is the exponent of the magnitude
4048 of the most significant digit of the operand (as though the
4049 operand were truncated to a single digit while maintaining the
4050 value of that digit and without limiting the resulting exponent).
4051
4052 >>> ExtendedContext.logb(Decimal('250'))
4053 Decimal("2")
4054 >>> ExtendedContext.logb(Decimal('2.50'))
4055 Decimal("0")
4056 >>> ExtendedContext.logb(Decimal('0.03'))
4057 Decimal("-2")
4058 >>> ExtendedContext.logb(Decimal('0'))
4059 Decimal("-Infinity")
4060 """
4061 return a.logb(context=self)
4062
4063 def logical_and(self, a, b):
4064 """Applies the logical operation 'and' between each operand's digits.
4065
4066 The operands must be both logical numbers.
4067
4068 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4069 Decimal("0")
4070 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4071 Decimal("0")
4072 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4073 Decimal("0")
4074 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4075 Decimal("1")
4076 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4077 Decimal("1000")
4078 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4079 Decimal("10")
4080 """
4081 return a.logical_and(b, context=self)
4082
4083 def logical_invert(self, a):
4084 """Invert all the digits in the operand.
4085
4086 The operand must be a logical number.
4087
4088 >>> ExtendedContext.logical_invert(Decimal('0'))
4089 Decimal("111111111")
4090 >>> ExtendedContext.logical_invert(Decimal('1'))
4091 Decimal("111111110")
4092 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4093 Decimal("0")
4094 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4095 Decimal("10101010")
4096 """
4097 return a.logical_invert(context=self)
4098
4099 def logical_or(self, a, b):
4100 """Applies the logical operation 'or' between each operand's digits.
4101
4102 The operands must be both logical numbers.
4103
4104 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4105 Decimal("0")
4106 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4107 Decimal("1")
4108 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4109 Decimal("1")
4110 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4111 Decimal("1")
4112 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4113 Decimal("1110")
4114 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4115 Decimal("1110")
4116 """
4117 return a.logical_or(b, context=self)
4118
4119 def logical_xor(self, a, b):
4120 """Applies the logical operation 'xor' between each operand's digits.
4121
4122 The operands must be both logical numbers.
4123
4124 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4125 Decimal("0")
4126 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4127 Decimal("1")
4128 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4129 Decimal("1")
4130 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4131 Decimal("0")
4132 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4133 Decimal("110")
4134 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4135 Decimal("1101")
4136 """
4137 return a.logical_xor(b, context=self)
4138
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004139 def max(self, a,b):
4140 """max compares two values numerically and returns the maximum.
4141
4142 If either operand is a NaN then the general rules apply.
4143 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004144 operation. If they are numerically equal then the left-hand operand
4145 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004146 infinity) of the two operands is chosen as the result.
4147
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004148 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004149 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004150 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004151 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004152 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004153 Decimal("1")
4154 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4155 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004156 """
4157 return a.max(b, context=self)
4158
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004159 def max_mag(self, a, b):
4160 """Compares the values numerically with their sign ignored."""
4161 return a.max_mag(b, context=self)
4162
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004163 def min(self, a,b):
4164 """min compares two values numerically and returns the minimum.
4165
4166 If either operand is a NaN then the general rules apply.
4167 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004168 operation. If they are numerically equal then the left-hand operand
4169 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004170 infinity) of the two operands is chosen as the result.
4171
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004172 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004173 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004174 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004175 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004176 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004177 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004178 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4179 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004180 """
4181 return a.min(b, context=self)
4182
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004183 def min_mag(self, a, b):
4184 """Compares the values numerically with their sign ignored."""
4185 return a.min_mag(b, context=self)
4186
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004187 def minus(self, a):
4188 """Minus corresponds to unary prefix minus in Python.
4189
4190 The operation is evaluated using the same rules as subtract; the
4191 operation minus(a) is calculated as subtract('0', a) where the '0'
4192 has the same exponent as the operand.
4193
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004194 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004195 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004196 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004197 Decimal("1.3")
4198 """
4199 return a.__neg__(context=self)
4200
4201 def multiply(self, a, b):
4202 """multiply multiplies two operands.
4203
4204 If either operand is a special value then the general rules apply.
4205 Otherwise, the operands are multiplied together ('long multiplication'),
4206 resulting in a number which may be as long as the sum of the lengths
4207 of the two operands.
4208
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004209 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004210 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004211 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004212 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004213 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004214 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004215 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004216 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004217 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004218 Decimal("4.28135971E+11")
4219 """
4220 return a.__mul__(b, context=self)
4221
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004222 def next_minus(self, a):
4223 """Returns the largest representable number smaller than a.
4224
4225 >>> c = ExtendedContext.copy()
4226 >>> c.Emin = -999
4227 >>> c.Emax = 999
4228 >>> ExtendedContext.next_minus(Decimal('1'))
4229 Decimal("0.999999999")
4230 >>> c.next_minus(Decimal('1E-1007'))
4231 Decimal("0E-1007")
4232 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4233 Decimal("-1.00000004")
4234 >>> c.next_minus(Decimal('Infinity'))
4235 Decimal("9.99999999E+999")
4236 """
4237 return a.next_minus(context=self)
4238
4239 def next_plus(self, a):
4240 """Returns the smallest representable number larger than a.
4241
4242 >>> c = ExtendedContext.copy()
4243 >>> c.Emin = -999
4244 >>> c.Emax = 999
4245 >>> ExtendedContext.next_plus(Decimal('1'))
4246 Decimal("1.00000001")
4247 >>> c.next_plus(Decimal('-1E-1007'))
4248 Decimal("-0E-1007")
4249 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4250 Decimal("-1.00000002")
4251 >>> c.next_plus(Decimal('-Infinity'))
4252 Decimal("-9.99999999E+999")
4253 """
4254 return a.next_plus(context=self)
4255
4256 def next_toward(self, a, b):
4257 """Returns the number closest to a, in direction towards b.
4258
4259 The result is the closest representable number from the first
4260 operand (but not the first operand) that is in the direction
4261 towards the second operand, unless the operands have the same
4262 value.
4263
4264 >>> c = ExtendedContext.copy()
4265 >>> c.Emin = -999
4266 >>> c.Emax = 999
4267 >>> c.next_toward(Decimal('1'), Decimal('2'))
4268 Decimal("1.00000001")
4269 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4270 Decimal("-0E-1007")
4271 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4272 Decimal("-1.00000002")
4273 >>> c.next_toward(Decimal('1'), Decimal('0'))
4274 Decimal("0.999999999")
4275 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4276 Decimal("0E-1007")
4277 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4278 Decimal("-1.00000004")
4279 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4280 Decimal("-0.00")
4281 """
4282 return a.next_toward(b, context=self)
4283
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004284 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004285 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004286
4287 Essentially a plus operation with all trailing zeros removed from the
4288 result.
4289
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004290 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004291 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004292 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004293 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004294 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004295 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004296 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004297 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004298 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004299 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004300 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004301 Decimal("0")
4302 """
4303 return a.normalize(context=self)
4304
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004305 def number_class(self, a):
4306 """Returns an indication of the class of the operand.
4307
4308 The class is one of the following strings:
4309 -sNaN
4310 -NaN
4311 -Infinity
4312 -Normal
4313 -Subnormal
4314 -Zero
4315 +Zero
4316 +Subnormal
4317 +Normal
4318 +Infinity
4319
4320 >>> c = Context(ExtendedContext)
4321 >>> c.Emin = -999
4322 >>> c.Emax = 999
4323 >>> c.number_class(Decimal('Infinity'))
4324 '+Infinity'
4325 >>> c.number_class(Decimal('1E-10'))
4326 '+Normal'
4327 >>> c.number_class(Decimal('2.50'))
4328 '+Normal'
4329 >>> c.number_class(Decimal('0.1E-999'))
4330 '+Subnormal'
4331 >>> c.number_class(Decimal('0'))
4332 '+Zero'
4333 >>> c.number_class(Decimal('-0'))
4334 '-Zero'
4335 >>> c.number_class(Decimal('-0.1E-999'))
4336 '-Subnormal'
4337 >>> c.number_class(Decimal('-1E-10'))
4338 '-Normal'
4339 >>> c.number_class(Decimal('-2.50'))
4340 '-Normal'
4341 >>> c.number_class(Decimal('-Infinity'))
4342 '-Infinity'
4343 >>> c.number_class(Decimal('NaN'))
4344 'NaN'
4345 >>> c.number_class(Decimal('-NaN'))
4346 'NaN'
4347 >>> c.number_class(Decimal('sNaN'))
4348 'sNaN'
4349 """
4350 return a.number_class(context=self)
4351
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004352 def plus(self, a):
4353 """Plus corresponds to unary prefix plus in Python.
4354
4355 The operation is evaluated using the same rules as add; the
4356 operation plus(a) is calculated as add('0', a) where the '0'
4357 has the same exponent as the operand.
4358
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004359 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004360 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004361 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004362 Decimal("-1.3")
4363 """
4364 return a.__pos__(context=self)
4365
4366 def power(self, a, b, modulo=None):
4367 """Raises a to the power of b, to modulo if given.
4368
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004369 With two arguments, compute a**b. If a is negative then b
4370 must be integral. The result will be inexact unless b is
4371 integral and the result is finite and can be expressed exactly
4372 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004373
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004374 With three arguments, compute (a**b) % modulo. For the
4375 three argument form, the following restrictions on the
4376 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004377
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004378 - all three arguments must be integral
4379 - b must be nonnegative
4380 - at least one of a or b must be nonzero
4381 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004382
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004383 The result of pow(a, b, modulo) is identical to the result
4384 that would be obtained by computing (a**b) % modulo with
4385 unbounded precision, but is computed more efficiently. It is
4386 always exact.
4387
4388 >>> c = ExtendedContext.copy()
4389 >>> c.Emin = -999
4390 >>> c.Emax = 999
4391 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004392 Decimal("8")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004393 >>> c.power(Decimal('-2'), Decimal('3'))
4394 Decimal("-8")
4395 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004396 Decimal("0.125")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004397 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004398 Decimal("69.7575744")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004399 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4400 Decimal("2.00000000")
4401 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004402 Decimal("0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004403 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004404 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004405 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004406 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004407 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004408 Decimal("-0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004409 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004410 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004411 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004412 Decimal("-Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004413 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004414 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004415 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004416 Decimal("NaN")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004417
4418 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4419 Decimal("11")
4420 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4421 Decimal("-11")
4422 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4423 Decimal("1")
4424 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4425 Decimal("11")
4426 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4427 Decimal("11729830")
4428 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4429 Decimal("-0")
4430 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4431 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004432 """
4433 return a.__pow__(b, modulo, context=self)
4434
4435 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004436 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004437
4438 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004439 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004440 exponent is being increased), multiplied by a positive power of ten (if
4441 the exponent is being decreased), or is unchanged (if the exponent is
4442 already equal to that of the right-hand operand).
4443
4444 Unlike other operations, if the length of the coefficient after the
4445 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004446 operation condition is raised. This guarantees that, unless there is
4447 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004448 equal to that of the right-hand operand.
4449
4450 Also unlike other operations, quantize will never raise Underflow, even
4451 if the result is subnormal and inexact.
4452
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004453 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004454 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004455 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004456 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004457 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004458 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004459 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004460 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004461 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004462 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004463 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004464 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004465 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004466 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004467 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004468 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004469 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004470 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004471 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004472 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004473 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004474 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004475 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004476 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004477 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004478 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004479 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004480 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004481 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004482 Decimal("2E+2")
4483 """
4484 return a.quantize(b, context=self)
4485
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004486 def radix(self):
4487 """Just returns 10, as this is Decimal, :)
4488
4489 >>> ExtendedContext.radix()
4490 Decimal("10")
4491 """
4492 return Decimal(10)
4493
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004494 def remainder(self, a, b):
4495 """Returns the remainder from integer division.
4496
4497 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004498 calculating integer division as described for divide-integer, rounded
4499 to precision digits if necessary. The sign of the result, if
4500 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004501
4502 This operation will fail under the same conditions as integer division
4503 (that is, if integer division on the same two operands would fail, the
4504 remainder cannot be calculated).
4505
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004506 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004507 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004508 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004509 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004510 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004511 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004512 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004513 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004514 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004515 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004516 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004517 Decimal("1.0")
4518 """
4519 return a.__mod__(b, context=self)
4520
4521 def remainder_near(self, a, b):
4522 """Returns to be "a - b * n", where n is the integer nearest the exact
4523 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004524 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004525 sign of a.
4526
4527 This operation will fail under the same conditions as integer division
4528 (that is, if integer division on the same two operands would fail, the
4529 remainder cannot be calculated).
4530
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004531 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004532 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004533 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004534 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004535 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004536 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004537 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004538 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004539 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004540 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004541 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004542 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004543 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004544 Decimal("-0.3")
4545 """
4546 return a.remainder_near(b, context=self)
4547
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004548 def rotate(self, a, b):
4549 """Returns a rotated copy of a, b times.
4550
4551 The coefficient of the result is a rotated copy of the digits in
4552 the coefficient of the first operand. The number of places of
4553 rotation is taken from the absolute value of the second operand,
4554 with the rotation being to the left if the second operand is
4555 positive or to the right otherwise.
4556
4557 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4558 Decimal("400000003")
4559 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4560 Decimal("12")
4561 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4562 Decimal("891234567")
4563 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4564 Decimal("123456789")
4565 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4566 Decimal("345678912")
4567 """
4568 return a.rotate(b, context=self)
4569
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004570 def same_quantum(self, a, b):
4571 """Returns True if the two operands have the same exponent.
4572
4573 The result is never affected by either the sign or the coefficient of
4574 either operand.
4575
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004576 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004577 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004578 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004579 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004580 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004581 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004582 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004583 True
4584 """
4585 return a.same_quantum(b)
4586
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004587 def scaleb (self, a, b):
4588 """Returns the first operand after adding the second value its exp.
4589
4590 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4591 Decimal("0.0750")
4592 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4593 Decimal("7.50")
4594 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4595 Decimal("7.50E+3")
4596 """
4597 return a.scaleb (b, context=self)
4598
4599 def shift(self, a, b):
4600 """Returns a shifted copy of a, b times.
4601
4602 The coefficient of the result is a shifted copy of the digits
4603 in the coefficient of the first operand. The number of places
4604 to shift is taken from the absolute value of the second operand,
4605 with the shift being to the left if the second operand is
4606 positive or to the right otherwise. Digits shifted into the
4607 coefficient are zeros.
4608
4609 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4610 Decimal("400000000")
4611 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4612 Decimal("0")
4613 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4614 Decimal("1234567")
4615 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4616 Decimal("123456789")
4617 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4618 Decimal("345678900")
4619 """
4620 return a.shift(b, context=self)
4621
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004622 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004623 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004624
4625 If the result must be inexact, it is rounded using the round-half-even
4626 algorithm.
4627
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004628 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004629 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004630 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004631 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004632 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004633 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004634 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004635 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004636 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004637 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004638 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004639 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004640 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004641 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004642 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004643 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004644 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004645 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004646 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004647 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004648 """
4649 return a.sqrt(context=self)
4650
4651 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004652 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004653
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004654 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004655 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004656 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004657 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004658 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004659 Decimal("-0.77")
4660 """
4661 return a.__sub__(b, context=self)
4662
4663 def to_eng_string(self, a):
4664 """Converts a number to a string, using scientific notation.
4665
4666 The operation is not affected by the context.
4667 """
4668 return a.to_eng_string(context=self)
4669
4670 def to_sci_string(self, a):
4671 """Converts a number to a string, using scientific notation.
4672
4673 The operation is not affected by the context.
4674 """
4675 return a.__str__(context=self)
4676
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004677 def to_integral_exact(self, a):
4678 """Rounds to an integer.
4679
4680 When the operand has a negative exponent, the result is the same
4681 as using the quantize() operation using the given operand as the
4682 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4683 of the operand as the precision setting; Inexact and Rounded flags
4684 are allowed in this operation. The rounding mode is taken from the
4685 context.
4686
4687 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4688 Decimal("2")
4689 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4690 Decimal("100")
4691 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4692 Decimal("100")
4693 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4694 Decimal("102")
4695 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4696 Decimal("-102")
4697 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4698 Decimal("1.0E+6")
4699 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4700 Decimal("7.89E+77")
4701 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4702 Decimal("-Infinity")
4703 """
4704 return a.to_integral_exact(context=self)
4705
4706 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004707 """Rounds to an integer.
4708
4709 When the operand has a negative exponent, the result is the same
4710 as using the quantize() operation using the given operand as the
4711 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4712 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004713 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004714
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004715 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004716 Decimal("2")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004717 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004718 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004719 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004720 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004721 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004722 Decimal("102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004723 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004724 Decimal("-102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004725 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004726 Decimal("1.0E+6")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004727 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004728 Decimal("7.89E+77")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004729 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004730 Decimal("-Infinity")
4731 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004732 return a.to_integral_value(context=self)
4733
4734 # the method name changed, but we provide also the old one, for compatibility
4735 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004736
4737class _WorkRep(object):
4738 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004739 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004740 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004741 # exp: None, int, or string
4742
4743 def __init__(self, value=None):
4744 if value is None:
4745 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004746 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004747 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004748 elif isinstance(value, Decimal):
4749 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00004750 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004751 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004752 else:
4753 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004754 self.sign = value[0]
4755 self.int = value[1]
4756 self.exp = value[2]
4757
4758 def __repr__(self):
4759 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4760
4761 __str__ = __repr__
4762
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004763
4764
4765def _normalize(op1, op2, shouldround = 0, prec = 0):
4766 """Normalizes op1, op2 to have the same exp and length of coefficient.
4767
4768 Done during addition.
4769 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004770 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004771 tmp = op2
4772 other = op1
4773 else:
4774 tmp = op1
4775 other = op2
4776
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004777 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4778 # Then adding 10**exp to tmp has the same effect (after rounding)
4779 # as adding any positive quantity smaller than 10**exp; similarly
4780 # for subtraction. So if other is smaller than 10**exp we replace
4781 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4782 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004783 tmp_len = len(str(tmp.int))
4784 other_len = len(str(other.int))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004785 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4786 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004787 other.int = 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004788 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004789
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004790 tmp.int *= 10 ** (tmp.exp - other.exp)
4791 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004792 return op1, op2
4793
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004794##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004795
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004796# This function from Tim Peters was taken from here:
4797# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4798# The correction being in the function definition is for speed, and
4799# the whole function is not resolved with math.log because of avoiding
4800# the use of floats.
4801def _nbits(n, correction = {
4802 '0': 4, '1': 3, '2': 2, '3': 2,
4803 '4': 1, '5': 1, '6': 1, '7': 1,
4804 '8': 0, '9': 0, 'a': 0, 'b': 0,
4805 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4806 """Number of bits in binary representation of the positive integer n,
4807 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004808 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004809 if n < 0:
4810 raise ValueError("The argument to _nbits should be nonnegative.")
4811 hex_n = "%x" % n
4812 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004813
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004814def _sqrt_nearest(n, a):
4815 """Closest integer to the square root of the positive integer n. a is
4816 an initial approximation to the square root. Any positive integer
4817 will do for a, but the closer a is to the square root of n the
4818 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004819
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004820 """
4821 if n <= 0 or a <= 0:
4822 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4823
4824 b=0
4825 while a != b:
4826 b, a = a, a--n//a>>1
4827 return a
4828
4829def _rshift_nearest(x, shift):
4830 """Given an integer x and a nonnegative integer shift, return closest
4831 integer to x / 2**shift; use round-to-even in case of a tie.
4832
4833 """
4834 b, q = 1 << shift, x >> shift
4835 return q + (2*(x & (b-1)) + (q&1) > b)
4836
4837def _div_nearest(a, b):
4838 """Closest integer to a/b, a and b positive integers; rounds to even
4839 in the case of a tie.
4840
4841 """
4842 q, r = divmod(a, b)
4843 return q + (2*r + (q&1) > b)
4844
4845def _ilog(x, M, L = 8):
4846 """Integer approximation to M*log(x/M), with absolute error boundable
4847 in terms only of x/M.
4848
4849 Given positive integers x and M, return an integer approximation to
4850 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4851 between the approximation and the exact result is at most 22. For
4852 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4853 both cases these are upper bounds on the error; it will usually be
4854 much smaller."""
4855
4856 # The basic algorithm is the following: let log1p be the function
4857 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4858 # the reduction
4859 #
4860 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4861 #
4862 # repeatedly until the argument to log1p is small (< 2**-L in
4863 # absolute value). For small y we can use the Taylor series
4864 # expansion
4865 #
4866 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4867 #
4868 # truncating at T such that y**T is small enough. The whole
4869 # computation is carried out in a form of fixed-point arithmetic,
4870 # with a real number z being represented by an integer
4871 # approximation to z*M. To avoid loss of precision, the y below
4872 # is actually an integer approximation to 2**R*y*M, where R is the
4873 # number of reductions performed so far.
4874
4875 y = x-M
4876 # argument reduction; R = number of reductions performed
4877 R = 0
4878 while (R <= L and abs(y) << L-R >= M or
4879 R > L and abs(y) >> R-L >= M):
4880 y = _div_nearest((M*y) << 1,
4881 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4882 R += 1
4883
4884 # Taylor series with T terms
4885 T = -int(-10*len(str(M))//(3*L))
4886 yshift = _rshift_nearest(y, R)
4887 w = _div_nearest(M, T)
4888 for k in range(T-1, 0, -1):
4889 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4890
4891 return _div_nearest(w*y, M)
4892
4893def _dlog10(c, e, p):
4894 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4895 approximation to 10**p * log10(c*10**e), with an absolute error of
4896 at most 1. Assumes that c*10**e is not exactly 1."""
4897
4898 # increase precision by 2; compensate for this by dividing
4899 # final result by 100
4900 p += 2
4901
4902 # write c*10**e as d*10**f with either:
4903 # f >= 0 and 1 <= d <= 10, or
4904 # f <= 0 and 0.1 <= d <= 1.
4905 # Thus for c*10**e close to 1, f = 0
4906 l = len(str(c))
4907 f = e+l - (e+l >= 1)
4908
4909 if p > 0:
4910 M = 10**p
4911 k = e+p-f
4912 if k >= 0:
4913 c *= 10**k
4914 else:
4915 c = _div_nearest(c, 10**-k)
4916
4917 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004918 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004919 log_d = _div_nearest(log_d*M, log_10)
4920 log_tenpower = f*M # exact
4921 else:
4922 log_d = 0 # error < 2.31
4923 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4924
4925 return _div_nearest(log_tenpower+log_d, 100)
4926
4927def _dlog(c, e, p):
4928 """Given integers c, e and p with c > 0, compute an integer
4929 approximation to 10**p * log(c*10**e), with an absolute error of
4930 at most 1. Assumes that c*10**e is not exactly 1."""
4931
4932 # Increase precision by 2. The precision increase is compensated
4933 # for at the end with a division by 100.
4934 p += 2
4935
4936 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4937 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4938 # as 10**p * log(d) + 10**p*f * log(10).
4939 l = len(str(c))
4940 f = e+l - (e+l >= 1)
4941
4942 # compute approximation to 10**p*log(d), with error < 27
4943 if p > 0:
4944 k = e+p-f
4945 if k >= 0:
4946 c *= 10**k
4947 else:
4948 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4949
4950 # _ilog magnifies existing error in c by a factor of at most 10
4951 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4952 else:
4953 # p <= 0: just approximate the whole thing by 0; error < 2.31
4954 log_d = 0
4955
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004956 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004957 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004958 extra = len(str(abs(f)))-1
4959 if p + extra >= 0:
4960 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4961 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4962 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004963 else:
4964 f_log_ten = 0
4965 else:
4966 f_log_ten = 0
4967
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004968 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004969 return _div_nearest(f_log_ten + log_d, 100)
4970
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004971class _Log10Memoize(object):
4972 """Class to compute, store, and allow retrieval of, digits of the
4973 constant log(10) = 2.302585.... This constant is needed by
4974 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4975 def __init__(self):
4976 self.digits = "23025850929940456840179914546843642076011014886"
4977
4978 def getdigits(self, p):
4979 """Given an integer p >= 0, return floor(10**p)*log(10).
4980
4981 For example, self.getdigits(3) returns 2302.
4982 """
4983 # digits are stored as a string, for quick conversion to
4984 # integer in the case that we've already computed enough
4985 # digits; the stored digits should always be correct
4986 # (truncated, not rounded to nearest).
4987 if p < 0:
4988 raise ValueError("p should be nonnegative")
4989
4990 if p >= len(self.digits):
4991 # compute p+3, p+6, p+9, ... digits; continue until at
4992 # least one of the extra digits is nonzero
4993 extra = 3
4994 while True:
4995 # compute p+extra digits, correct to within 1ulp
4996 M = 10**(p+extra+2)
4997 digits = str(_div_nearest(_ilog(10*M, M), 100))
4998 if digits[-extra:] != '0'*extra:
4999 break
5000 extra += 3
5001 # keep all reliable digits so far; remove trailing zeros
5002 # and next nonzero digit
5003 self.digits = digits.rstrip('0')[:-1]
5004 return int(self.digits[:p+1])
5005
5006_log10_digits = _Log10Memoize().getdigits
5007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005008def _iexp(x, M, L=8):
5009 """Given integers x and M, M > 0, such that x/M is small in absolute
5010 value, compute an integer approximation to M*exp(x/M). For 0 <=
5011 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5012 is usually much smaller)."""
5013
5014 # Algorithm: to compute exp(z) for a real number z, first divide z
5015 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5016 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5017 # series
5018 #
5019 # expm1(x) = x + x**2/2! + x**3/3! + ...
5020 #
5021 # Now use the identity
5022 #
5023 # expm1(2x) = expm1(x)*(expm1(x)+2)
5024 #
5025 # R times to compute the sequence expm1(z/2**R),
5026 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5027
5028 # Find R such that x/2**R/M <= 2**-L
5029 R = _nbits((x<<L)//M)
5030
5031 # Taylor series. (2**L)**T > M
5032 T = -int(-10*len(str(M))//(3*L))
5033 y = _div_nearest(x, T)
5034 Mshift = M<<R
5035 for i in range(T-1, 0, -1):
5036 y = _div_nearest(x*(Mshift + y), Mshift * i)
5037
5038 # Expansion
5039 for k in range(R-1, -1, -1):
5040 Mshift = M<<(k+2)
5041 y = _div_nearest(y*(y+Mshift), Mshift)
5042
5043 return M+y
5044
5045def _dexp(c, e, p):
5046 """Compute an approximation to exp(c*10**e), with p decimal places of
5047 precision.
5048
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005049 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005050
5051 10**(p-1) <= d <= 10**p, and
5052 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5053
5054 In other words, d*10**f is an approximation to exp(c*10**e) with p
5055 digits of precision, and with an error in d of at most 1. This is
5056 almost, but not quite, the same as the error being < 1ulp: when d
5057 = 10**(p-1) the error could be up to 10 ulp."""
5058
5059 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5060 p += 2
5061
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005062 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005063 extra = max(0, e + len(str(c)) - 1)
5064 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005065
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005066 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005067 # rounding down
5068 shift = e+q
5069 if shift >= 0:
5070 cshift = c*10**shift
5071 else:
5072 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005073 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005074
5075 # reduce remainder back to original precision
5076 rem = _div_nearest(rem, 10**extra)
5077
5078 # error in result of _iexp < 120; error after division < 0.62
5079 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5080
5081def _dpower(xc, xe, yc, ye, p):
5082 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5083 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5084
5085 10**(p-1) <= c <= 10**p, and
5086 (c-1)*10**e < x**y < (c+1)*10**e
5087
5088 in other words, c*10**e is an approximation to x**y with p digits
5089 of precision, and with an error in c of at most 1. (This is
5090 almost, but not quite, the same as the error being < 1ulp: when c
5091 == 10**(p-1) we can only guarantee error < 10ulp.)
5092
5093 We assume that: x is positive and not equal to 1, and y is nonzero.
5094 """
5095
5096 # Find b such that 10**(b-1) <= |y| <= 10**b
5097 b = len(str(abs(yc))) + ye
5098
5099 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5100 lxc = _dlog(xc, xe, p+b+1)
5101
5102 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5103 shift = ye-b
5104 if shift >= 0:
5105 pc = lxc*yc*10**shift
5106 else:
5107 pc = _div_nearest(lxc*yc, 10**-shift)
5108
5109 if pc == 0:
5110 # we prefer a result that isn't exactly 1; this makes it
5111 # easier to compute a correctly rounded result in __pow__
5112 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5113 coeff, exp = 10**(p-1)+1, 1-p
5114 else:
5115 coeff, exp = 10**p-1, -p
5116 else:
5117 coeff, exp = _dexp(pc, -(p+1), p+1)
5118 coeff = _div_nearest(coeff, 10)
5119 exp += 1
5120
5121 return coeff, exp
5122
5123def _log10_lb(c, correction = {
5124 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5125 '6': 23, '7': 16, '8': 10, '9': 5}):
5126 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5127 if c <= 0:
5128 raise ValueError("The argument to _log10_lb should be nonnegative.")
5129 str_c = str(c)
5130 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005131
Guido van Rossumd8faa362007-04-27 19:54:29 +00005132##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005133
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005134def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005135 """Convert other to Decimal.
5136
5137 Verifies that it's ok to use in an implicit construction.
5138 """
5139 if isinstance(other, Decimal):
5140 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005141 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005142 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005143 if raiseit:
5144 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005145 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005146
Guido van Rossumd8faa362007-04-27 19:54:29 +00005147##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005148
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005149# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005150# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005151
5152DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005153 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005154 traps=[DivisionByZero, Overflow, InvalidOperation],
5155 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005156 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005157 Emax=999999999,
5158 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005159 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005160)
5161
5162# Pre-made alternate contexts offered by the specification
5163# Don't change these; the user should be able to select these
5164# contexts and be able to reproduce results from other implementations
5165# of the spec.
5166
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005167BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005168 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005169 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5170 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005171)
5172
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005173ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005174 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005175 traps=[],
5176 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005177)
5178
5179
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005180##### crud for parsing strings #############################################
5181import re
5182
5183# Regular expression used for parsing numeric strings. Additional
5184# comments:
5185#
5186# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5187# whitespace. But note that the specification disallows whitespace in
5188# a numeric string.
5189#
5190# 2. For finite numbers (not infinities and NaNs) the body of the
5191# number between the optional sign and the optional exponent must have
5192# at least one decimal digit, possibly after the decimal point. The
5193# lookahead expression '(?=\d|\.\d)' checks this.
5194#
5195# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5196# other meaning for \d than the numbers [0-9].
5197
5198import re
5199_parser = re.compile(r""" # A numeric string consists of:
5200# \s*
5201 (?P<sign>[-+])? # an optional sign, followed by either...
5202 (
5203 (?=\d|\.\d) # ...a number (with at least one digit)
5204 (?P<int>\d*) # consisting of a (possibly empty) integer part
5205 (\.(?P<frac>\d*))? # followed by an optional fractional part
5206 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5207 |
5208 Inf(inity)? # ...an infinity, or...
5209 |
5210 (?P<signal>s)? # ...an (optionally signaling)
5211 NaN # NaN
5212 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5213 )
5214# \s*
5215 $
5216""", re.VERBOSE | re.IGNORECASE).match
5217
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005218_all_zeros = re.compile('0*$').match
5219_exact_half = re.compile('50*$').match
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005220del re
5221
5222
Guido van Rossumd8faa362007-04-27 19:54:29 +00005223##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005224
Guido van Rossumd8faa362007-04-27 19:54:29 +00005225# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005226Inf = Decimal('Inf')
5227negInf = Decimal('-Inf')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005228NaN = Decimal('NaN')
5229Dec_0 = Decimal(0)
5230Dec_p1 = Decimal(1)
5231Dec_n1 = Decimal(-1)
5232Dec_p2 = Decimal(2)
5233Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005234
Guido van Rossumd8faa362007-04-27 19:54:29 +00005235# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005236Infsign = (Inf, negInf)
5237
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005238
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005239
5240if __name__ == '__main__':
5241 import doctest, sys
5242 doctest.testmod(sys.modules[__name__])