blob: d7bd1275cd29064f1459527e206d8a5597651015 [file] [log] [blame]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001# Copyright (c) 2004 Python Software Foundation.
2# All rights reserved.
3
4# Written by Eric Price <eprice at tjhsst.edu>
5# and Facundo Batista <facundo at taniquetil.com.ar>
6# and Raymond Hettinger <python at rcn.com>
Fred Drake1f34eb12004-07-01 14:28:36 +00007# and Aahz <aahz at pobox.com>
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00008# and Tim Peters
9
Raymond Hettinger27dbcf22004-08-19 22:39:55 +000010# This module is currently Py2.3 compatible and should be kept that way
11# unless a major compelling advantage arises. IOW, 2.3 compatibility is
12# strongly preferred, but not guaranteed.
13
14# Also, this module should be kept in sync with the latest updates of
15# the IBM specification as it evolves. Those updates will be treated
16# as bug fixes (deviation from the spec is a compatibility, usability
17# bug) and will be backported. At this point the spec is stabilizing
18# and the updates are becoming fewer, smaller, and less significant.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000019
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000020"""
21This is a Py2.3 implementation of decimal floating point arithmetic based on
22the General Decimal Arithmetic Specification:
23
24 www2.hursley.ibm.com/decimal/decarith.html
25
Raymond Hettinger0ea241e2004-07-04 13:53:24 +000026and IEEE standard 854-1987:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000027
28 www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
29
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000030Decimal floating point has finite precision with arbitrarily large bounds.
31
Guido van Rossumd8faa362007-04-27 19:54:29 +000032The purpose of this module is to support arithmetic using familiar
33"schoolhouse" rules and to avoid some of the tricky representation
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000034issues associated with binary floating point. The package is especially
35useful for financial applications or for contexts where users have
36expectations that are at odds with binary floating point (for instance,
37in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
38of the expected Decimal("0.00") returned by decimal floating point).
39
40Here are some examples of using the decimal module:
41
42>>> from decimal import *
Raymond Hettingerbd7f76d2004-07-08 00:49:18 +000043>>> setcontext(ExtendedContext)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000044>>> Decimal(0)
45Decimal("0")
46>>> Decimal("1")
47Decimal("1")
48>>> Decimal("-.0123")
49Decimal("-0.0123")
50>>> Decimal(123456)
51Decimal("123456")
52>>> Decimal("123.45e12345678901234567890")
53Decimal("1.2345E+12345678901234567892")
54>>> Decimal("1.33") + Decimal("1.27")
55Decimal("2.60")
56>>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41")
57Decimal("-2.20")
58>>> dig = Decimal(1)
Guido van Rossum7131f842007-02-09 20:13:25 +000059>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000600.333333333
61>>> getcontext().prec = 18
Guido van Rossum7131f842007-02-09 20:13:25 +000062>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000630.333333333333333333
Guido van Rossum7131f842007-02-09 20:13:25 +000064>>> print(dig.sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000651
Guido van Rossum7131f842007-02-09 20:13:25 +000066>>> print(Decimal(3).sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000671.73205080756887729
Guido van Rossum7131f842007-02-09 20:13:25 +000068>>> print(Decimal(3) ** 123)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000694.85192780976896427E+58
70>>> inf = Decimal(1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000071>>> print(inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000072Infinity
73>>> neginf = Decimal(-1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000074>>> print(neginf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000075-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000076>>> print(neginf + inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000077NaN
Guido van Rossum7131f842007-02-09 20:13:25 +000078>>> print(neginf * inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000079-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000080>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000081Infinity
Raymond Hettingerbf440692004-07-10 14:14:37 +000082>>> getcontext().traps[DivisionByZero] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000083>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000084Traceback (most recent call last):
85 ...
86 ...
87 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +000088decimal.DivisionByZero: x / 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000089>>> c = Context()
Raymond Hettingerbf440692004-07-10 14:14:37 +000090>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000091>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000920
93>>> c.divide(Decimal(0), Decimal(0))
94Decimal("NaN")
Raymond Hettingerbf440692004-07-10 14:14:37 +000095>>> c.traps[InvalidOperation] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000096>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000098>>> c.flags[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000099>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000
Guido van Rossum7131f842007-02-09 20:13:25 +0000101>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000102Traceback (most recent call last):
103 ...
104 ...
105 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +0000106decimal.InvalidOperation: 0 / 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000107>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000109>>> c.flags[InvalidOperation] = 0
Raymond Hettingerbf440692004-07-10 14:14:37 +0000110>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000111>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000112NaN
Guido van Rossum7131f842007-02-09 20:13:25 +0000113>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141
115>>>
116"""
117
118__all__ = [
119 # Two major classes
120 'Decimal', 'Context',
121
122 # Contexts
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +0000123 'DefaultContext', 'BasicContext', 'ExtendedContext',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000124
125 # Exceptions
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +0000126 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
127 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000128
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000129 # Constants for use in setting up contexts
130 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000131 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000132
133 # Functions for manipulating contexts
Thomas Wouters89f507f2006-12-13 04:49:30 +0000134 'setcontext', 'getcontext', 'localcontext'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000135]
136
Raymond Hettingereb260842005-06-07 18:52:34 +0000137import copy as _copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000138
Guido van Rossumd8faa362007-04-27 19:54:29 +0000139# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000140ROUND_DOWN = 'ROUND_DOWN'
141ROUND_HALF_UP = 'ROUND_HALF_UP'
142ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
143ROUND_CEILING = 'ROUND_CEILING'
144ROUND_FLOOR = 'ROUND_FLOOR'
145ROUND_UP = 'ROUND_UP'
146ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000147ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000148
Guido van Rossumd8faa362007-04-27 19:54:29 +0000149# Rounding decision (not part of the public API)
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000150NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY
151ALWAYS_ROUND = 'ALWAYS_ROUND' # Every operation rounds at end.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000152
Guido van Rossumd8faa362007-04-27 19:54:29 +0000153# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000154
155class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000156 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000157
158 Used exceptions derive from this.
159 If an exception derives from another exception besides this (such as
160 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
161 called if the others are present. This isn't actually used for
162 anything, though.
163
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000164 handle -- Called when context._raise_error is called and the
165 trap_enabler is set. First argument is self, second is the
166 context. More arguments can be given, those being after
167 the explanation in _raise_error (For example,
168 context._raise_error(NewError, '(-x)!', self._sign) would
169 call NewError().handle(context, self._sign).)
170
171 To define a new exception, it should be sufficient to have it derive
172 from DecimalException.
173 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000174 def handle(self, context, *args):
175 pass
176
177
178class Clamped(DecimalException):
179 """Exponent of a 0 changed to fit bounds.
180
181 This occurs and signals clamped if the exponent of a result has been
182 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000183 representation. This may occur when the exponent of a zero result would
184 be outside the bounds of a representation, or when a large normal
185 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000186 this latter case, the exponent is reduced to fit and the corresponding
187 number of zero digits are appended to the coefficient ("fold-down").
188 """
189
190
191class InvalidOperation(DecimalException):
192 """An invalid operation was performed.
193
194 Various bad things cause this:
195
196 Something creates a signaling NaN
197 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000198 0 * (+-)INF
199 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000200 x % 0
201 (+-)INF % x
202 x._rescale( non-integer )
203 sqrt(-x) , x > 0
204 0 ** 0
205 x ** (non-integer)
206 x ** (+-)INF
207 An operand is invalid
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000208
209 The result of the operation after these is a quiet positive NaN,
210 except when the cause is a signaling NaN, in which case the result is
211 also a quiet NaN, but with the original sign, and an optional
212 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000213 """
214 def handle(self, context, *args):
215 if args:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000216 if args[0] == 1: # sNaN, must drop 's' but keep diagnostics
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000217 ans = Decimal((args[1]._sign, args[1]._int, 'n'))
218 return ans._fix_nan(context)
219 elif args[0] == 2:
220 return Decimal( (args[1], args[2], 'n') )
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000221 return NaN
222
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000223
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000224class ConversionSyntax(InvalidOperation):
225 """Trying to convert badly formed string.
226
227 This occurs and signals invalid-operation if an string is being
228 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000229 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000230 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000231 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000232 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000233
234class DivisionByZero(DecimalException, ZeroDivisionError):
235 """Division by 0.
236
237 This occurs and signals division-by-zero if division of a finite number
238 by zero was attempted (during a divide-integer or divide operation, or a
239 power operation with negative right-hand operand), and the dividend was
240 not zero.
241
242 The result of the operation is [sign,inf], where sign is the exclusive
243 or of the signs of the operands for divide, or is 1 for an odd power of
244 -0, for power.
245 """
246
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000247 def handle(self, context, sign, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000248 return Infsign[sign]
249
250class DivisionImpossible(InvalidOperation):
251 """Cannot perform the division adequately.
252
253 This occurs and signals invalid-operation if the integer result of a
254 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000255 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000256 """
257
258 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000259 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000260
261class DivisionUndefined(InvalidOperation, ZeroDivisionError):
262 """Undefined result of division.
263
264 This occurs and signals invalid-operation if division by zero was
265 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000266 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000267 """
268
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000269 def handle(self, context, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000270 return NaN
271
272class Inexact(DecimalException):
273 """Had to round, losing information.
274
275 This occurs and signals inexact whenever the result of an operation is
276 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000277 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000278 result in all cases is unchanged.
279
280 The inexact signal may be tested (or trapped) to determine if a given
281 operation (or sequence of operations) was inexact.
282 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000283 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000284
285class InvalidContext(InvalidOperation):
286 """Invalid context. Unknown rounding, for example.
287
288 This occurs and signals invalid-operation if an invalid context was
Guido van Rossumd8faa362007-04-27 19:54:29 +0000289 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000290 on creation and either the precision exceeds the capability of the
291 underlying concrete representation or an unknown or unsupported rounding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000292 was specified. These aspects of the context need only be checked when
293 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000294 """
295
296 def handle(self, context, *args):
297 return NaN
298
299class Rounded(DecimalException):
300 """Number got rounded (not necessarily changed during rounding).
301
302 This occurs and signals rounded whenever the result of an operation is
303 rounded (that is, some zero or non-zero digits were discarded from the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000304 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000305 result in all cases is unchanged.
306
307 The rounded signal may be tested (or trapped) to determine if a given
308 operation (or sequence of operations) caused a loss of precision.
309 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000310 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000311
312class Subnormal(DecimalException):
313 """Exponent < Emin before rounding.
314
315 This occurs and signals subnormal whenever the result of a conversion or
316 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000317 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000318
319 The subnormal signal may be tested (or trapped) to determine if a given
320 or operation (or sequence of operations) yielded a subnormal result.
321 """
322 pass
323
324class Overflow(Inexact, Rounded):
325 """Numerical overflow.
326
327 This occurs and signals overflow if the adjusted exponent of a result
328 (from a conversion or from an operation that is not an attempt to divide
329 by zero), after rounding, would be greater than the largest value that
330 can be handled by the implementation (the value Emax).
331
332 The result depends on the rounding mode:
333
334 For round-half-up and round-half-even (and for round-half-down and
335 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000336 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000338 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000339 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000340 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000341 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000342 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000343 will also be raised.
344 """
345
346 def handle(self, context, sign, *args):
347 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000348 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000349 return Infsign[sign]
350 if sign == 0:
351 if context.rounding == ROUND_CEILING:
352 return Infsign[sign]
353 return Decimal((sign, (9,)*context.prec,
354 context.Emax-context.prec+1))
355 if sign == 1:
356 if context.rounding == ROUND_FLOOR:
357 return Infsign[sign]
358 return Decimal( (sign, (9,)*context.prec,
359 context.Emax-context.prec+1))
360
361
362class Underflow(Inexact, Rounded, Subnormal):
363 """Numerical underflow with result rounded to 0.
364
365 This occurs and signals underflow if a result is inexact and the
366 adjusted exponent of the result would be smaller (more negative) than
367 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000368 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000369
370 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000371 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000372 in 0 with the sign of the intermediate result and an exponent of Etiny.
373
374 In all cases, Inexact, Rounded, and Subnormal will also be raised.
375 """
376
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000377# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000378_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000379 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000380
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000381# Map conditions (per the spec) to signals
382_condition_map = {ConversionSyntax:InvalidOperation,
383 DivisionImpossible:InvalidOperation,
384 DivisionUndefined:InvalidOperation,
385 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000386
Guido van Rossumd8faa362007-04-27 19:54:29 +0000387##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000388
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000389# The getcontext() and setcontext() function manage access to a thread-local
390# current context. Py2.4 offers direct support for thread locals. If that
391# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000392# work for older Pythons. If threads are not part of the build, create a
393# mock threading object with threading.local() returning the module namespace.
394
395try:
396 import threading
397except ImportError:
398 # Python was compiled without threads; create a mock object instead
399 import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +0000400 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000401 def local(self, sys=sys):
402 return sys.modules[__name__]
403 threading = MockThreading()
404 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000405
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000406try:
407 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000408
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000409except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000410
Guido van Rossumd8faa362007-04-27 19:54:29 +0000411 # To fix reloading, force it to create a new context
412 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000413 if hasattr(threading.currentThread(), '__decimal_context__'):
414 del threading.currentThread().__decimal_context__
415
416 def setcontext(context):
417 """Set this thread's context to context."""
418 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000419 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000420 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000421 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000422
423 def getcontext():
424 """Returns this thread's context.
425
426 If this thread does not yet have a context, returns
427 a new context and sets this thread's context.
428 New contexts are copies of DefaultContext.
429 """
430 try:
431 return threading.currentThread().__decimal_context__
432 except AttributeError:
433 context = Context()
434 threading.currentThread().__decimal_context__ = context
435 return context
436
437else:
438
439 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000440 if hasattr(local, '__decimal_context__'):
441 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000442
443 def getcontext(_local=local):
444 """Returns this thread's context.
445
446 If this thread does not yet have a context, returns
447 a new context and sets this thread's context.
448 New contexts are copies of DefaultContext.
449 """
450 try:
451 return _local.__decimal_context__
452 except AttributeError:
453 context = Context()
454 _local.__decimal_context__ = context
455 return context
456
457 def setcontext(context, _local=local):
458 """Set this thread's context to context."""
459 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000460 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000461 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000462 _local.__decimal_context__ = context
463
464 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000465
Thomas Wouters89f507f2006-12-13 04:49:30 +0000466def localcontext(ctx=None):
467 """Return a context manager for a copy of the supplied context
468
469 Uses a copy of the current context if no context is specified
470 The returned context manager creates a local decimal context
471 in a with statement:
472 def sin(x):
473 with localcontext() as ctx:
474 ctx.prec += 2
475 # Rest of sin calculation algorithm
476 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000477 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000478
479 def sin(x):
480 with localcontext(ExtendedContext):
481 # Rest of sin calculation algorithm
482 # uses the Extended Context from the
483 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000484 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000485
486 """
487 # The string below can't be included in the docstring until Python 2.6
488 # as the doctest module doesn't understand __future__ statements
489 """
490 >>> from __future__ import with_statement
Guido van Rossum7131f842007-02-09 20:13:25 +0000491 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000492 28
493 >>> with localcontext():
494 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000495 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000496 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000497 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000498 30
499 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000500 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000501 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000502 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000503 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000504 28
505 """
506 if ctx is None: ctx = getcontext()
507 return _ContextManager(ctx)
508
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000509
Guido van Rossumd8faa362007-04-27 19:54:29 +0000510##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000511
512class Decimal(object):
513 """Floating point class for decimal arithmetic."""
514
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000515 __slots__ = ('_exp','_int','_sign', '_is_special')
516 # Generally, the value of the Decimal instance is given by
517 # (-1)**_sign * _int * 10**_exp
518 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000519
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000520 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000521 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000522 """Create a decimal point instance.
523
524 >>> Decimal('3.14') # string input
525 Decimal("3.14")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000526 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000527 Decimal("3.14")
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000528 >>> Decimal(314) # int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000529 Decimal("314")
530 >>> Decimal(Decimal(314)) # another decimal instance
531 Decimal("314")
532 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000533
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000534 self = object.__new__(cls)
535 self._is_special = False
536
537 # From an internal working value
538 if isinstance(value, _WorkRep):
Raymond Hettinger17931de2004-10-27 06:21:46 +0000539 self._sign = value.sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000540 self._int = tuple(map(int, str(value.int)))
541 self._exp = int(value.exp)
542 return self
543
544 # From another decimal
545 if isinstance(value, Decimal):
546 self._exp = value._exp
547 self._sign = value._sign
548 self._int = value._int
549 self._is_special = value._is_special
550 return self
551
552 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000553 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000554 if value >= 0:
555 self._sign = 0
556 else:
557 self._sign = 1
558 self._exp = 0
559 self._int = tuple(map(int, str(abs(value))))
560 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000561
562 # tuple/list conversion (possibly from as_tuple())
563 if isinstance(value, (list,tuple)):
564 if len(value) != 3:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000565 raise ValueError('Invalid arguments')
Raymond Hettingerdbecd932005-02-06 06:57:08 +0000566 if value[0] not in (0,1):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000567 raise ValueError('Invalid sign')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000568 for digit in value[1]:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000569 if not isinstance(digit, int) or digit < 0:
570 raise ValueError("The second value in the tuple must be "
Guido van Rossumd8faa362007-04-27 19:54:29 +0000571 "composed of non negative integer elements.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000572 self._sign = value[0]
573 self._int = tuple(value[1])
574 if value[2] in ('F','n','N'):
575 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000576 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000577 else:
578 self._exp = int(value[2])
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000579 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000580
Raymond Hettingerbf440692004-07-10 14:14:37 +0000581 if isinstance(value, float):
582 raise TypeError("Cannot convert float to Decimal. " +
583 "First convert the float to a string")
584
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000585 # Other argument types may require the context during interpretation
586 if context is None:
587 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000588
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000589 # From a string
590 # REs insist on real strings, so we can too.
591 if isinstance(value, basestring):
592 if _isinfinity(value):
593 self._exp = 'F'
594 self._int = (0,)
595 self._is_special = True
596 if _isinfinity(value) == 1:
597 self._sign = 0
598 else:
599 self._sign = 1
600 return self
601 if _isnan(value):
602 sig, sign, diag = _isnan(value)
603 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000604 if sig == 1:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000605 self._exp = 'n' # qNaN
606 else: # sig == 2
607 self._exp = 'N' # sNaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000608 self._sign = sign
Guido van Rossumd8faa362007-04-27 19:54:29 +0000609 self._int = tuple(map(int, diag)) # Diagnostic info
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000610 return self
611 try:
612 self._sign, self._int, self._exp = _string2exact(value)
613 except ValueError:
614 self._is_special = True
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000615 return context._raise_error(ConversionSyntax,
616 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000617 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000618
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000619 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000620
621 def _isnan(self):
622 """Returns whether the number is not actually one.
623
624 0 if a number
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000625 1 if NaN (it could be a normal quiet NaN or a phantom one)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000626 2 if sNaN
627 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000628 if self._is_special:
629 exp = self._exp
630 if exp == 'n':
631 return 1
632 elif exp == 'N':
633 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000634 return 0
635
636 def _isinfinity(self):
637 """Returns whether the number is infinite
638
639 0 if finite or not a number
640 1 if +INF
641 -1 if -INF
642 """
643 if self._exp == 'F':
644 if self._sign:
645 return -1
646 return 1
647 return 0
648
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000649 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000650 """Returns whether the number is not actually one.
651
652 if self, other are sNaN, signal
653 if self, other are NaN return nan
654 return 0
655
656 Done before operations.
657 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000658
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000659 self_is_nan = self._isnan()
660 if other is None:
661 other_is_nan = False
662 else:
663 other_is_nan = other._isnan()
664
665 if self_is_nan or other_is_nan:
666 if context is None:
667 context = getcontext()
668
669 if self_is_nan == 2:
670 return context._raise_error(InvalidOperation, 'sNaN',
671 1, self)
672 if other_is_nan == 2:
673 return context._raise_error(InvalidOperation, 'sNaN',
674 1, other)
675 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000676 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000677
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000678 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000679 return 0
680
Jack Diederich4dafcc42006-11-28 19:15:13 +0000681 def __bool__(self):
Jack Diederich030debb2006-11-28 22:22:22 +0000682 """return True if the number is non-zero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000683
Jack Diederich030debb2006-11-28 22:22:22 +0000684 False if self == 0
685 True if self != 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000686 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000687 if self._is_special:
Jack Diederich4dafcc42006-11-28 19:15:13 +0000688 return True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000689 return sum(self._int) != 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000690
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000691 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000692 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000693 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000694 # Never return NotImplemented
695 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000696
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000697 if self._is_special or other._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000698 # check for nans, without raising on a signaling nan
699 if self._isnan() or other._isnan():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000700 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000701
702 # INF = INF
703 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000704
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000705 # check for zeros; note that cmp(0, -0) should return 0
706 if not self:
707 if not other:
708 return 0
709 else:
710 return -((-1)**other._sign)
711 if not other:
712 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000713
Guido van Rossumd8faa362007-04-27 19:54:29 +0000714 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000715 if other._sign < self._sign:
716 return -1
717 if self._sign < other._sign:
718 return 1
719
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000720 self_adjusted = self.adjusted()
721 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000722 if self_adjusted == other_adjusted:
723 self_padded = self._int + (0,)*(self._exp - other._exp)
724 other_padded = other._int + (0,)*(other._exp - self._exp)
725 return cmp(self_padded, other_padded) * (-1)**self._sign
726 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000727 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000728 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000729 return -((-1)**self._sign)
730
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000731 def __eq__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000732 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000733 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000734 return self.__cmp__(other) == 0
735
736 def __ne__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000737 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000738 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000739 return self.__cmp__(other) != 0
740
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000741 def __lt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000742 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000743 return NotImplemented
744 return self.__cmp__(other) < 0
745
746 def __le__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000747 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000748 return NotImplemented
749 return self.__cmp__(other) <= 0
750
751 def __gt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000752 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000753 return NotImplemented
754 return self.__cmp__(other) > 0
755
756 def __ge__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000757 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000758 return NotImplemented
759 return self.__cmp__(other) >= 0
760
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000761 def compare(self, other, context=None):
762 """Compares one to another.
763
764 -1 => a < b
765 0 => a = b
766 1 => a > b
767 NaN => one is NaN
768 Like __cmp__, but returns Decimal instances.
769 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000770 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000771
Guido van Rossumd8faa362007-04-27 19:54:29 +0000772 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000773 if (self._is_special or other and other._is_special):
774 ans = self._check_nans(other, context)
775 if ans:
776 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000777
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000778 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000779
780 def __hash__(self):
781 """x.__hash__() <==> hash(x)"""
782 # Decimal integers must hash the same as the ints
783 # Non-integer decimals are normalized and hashed as strings
Thomas Wouters477c8d52006-05-27 19:21:47 +0000784 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000785 if self._is_special:
786 if self._isnan():
787 raise TypeError('Cannot hash a NaN value.')
788 return hash(str(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000789 i = int(self)
790 if self == Decimal(i):
791 return hash(i)
Jack Diederich4dafcc42006-11-28 19:15:13 +0000792 assert self.__bool__() # '-0' handled by integer case
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000793 return hash(str(self.normalize()))
794
795 def as_tuple(self):
796 """Represents the number as a triple tuple.
797
798 To show the internals exactly as they are.
799 """
800 return (self._sign, self._int, self._exp)
801
802 def __repr__(self):
803 """Represents the number as an instance of Decimal."""
804 # Invariant: eval(repr(d)) == d
805 return 'Decimal("%s")' % str(self)
806
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000807 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000808 """Return string representation of the number in scientific notation.
809
810 Captures all of the information in the underlying representation.
811 """
812
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000813 if self._is_special:
814 if self._isnan():
815 minus = '-'*self._sign
816 if self._int == (0,):
817 info = ''
818 else:
819 info = ''.join(map(str, self._int))
820 if self._isnan() == 2:
821 return minus + 'sNaN' + info
822 return minus + 'NaN' + info
823 if self._isinfinity():
824 minus = '-'*self._sign
825 return minus + 'Infinity'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000826
827 if context is None:
828 context = getcontext()
829
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000830 tmp = list(map(str, self._int))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000831 numdigits = len(self._int)
832 leftdigits = self._exp + numdigits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000833 if eng and not self: # self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
834 if self._exp < 0 and self._exp >= -6: # short, no need for e/E
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000835 s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
836 return s
Guido van Rossumd8faa362007-04-27 19:54:29 +0000837 # exp is closest mult. of 3 >= self._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000838 exp = ((self._exp - 1)// 3 + 1) * 3
839 if exp != self._exp:
840 s = '0.'+'0'*(exp - self._exp)
841 else:
842 s = '0'
843 if exp != 0:
844 if context.capitals:
845 s += 'E'
846 else:
847 s += 'e'
848 if exp > 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000849 s += '+' # 0.0e+3, not 0.0e3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000850 s += str(exp)
851 s = '-'*self._sign + s
852 return s
853 if eng:
854 dotplace = (leftdigits-1)%3+1
855 adjexp = leftdigits -1 - (leftdigits-1)%3
856 else:
857 adjexp = leftdigits-1
858 dotplace = 1
859 if self._exp == 0:
860 pass
861 elif self._exp < 0 and adjexp >= 0:
862 tmp.insert(leftdigits, '.')
863 elif self._exp < 0 and adjexp >= -6:
864 tmp[0:0] = ['0'] * int(-leftdigits)
865 tmp.insert(0, '0.')
866 else:
867 if numdigits > dotplace:
868 tmp.insert(dotplace, '.')
869 elif numdigits < dotplace:
870 tmp.extend(['0']*(dotplace-numdigits))
871 if adjexp:
872 if not context.capitals:
873 tmp.append('e')
874 else:
875 tmp.append('E')
876 if adjexp > 0:
877 tmp.append('+')
878 tmp.append(str(adjexp))
879 if eng:
880 while tmp[0:1] == ['0']:
881 tmp[0:1] = []
882 if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
883 tmp[0:0] = ['0']
884 if self._sign:
885 tmp.insert(0, '-')
886
887 return ''.join(tmp)
888
889 def to_eng_string(self, context=None):
890 """Convert to engineering-type string.
891
892 Engineering notation has an exponent which is a multiple of 3, so there
893 are up to 3 digits left of the decimal place.
894
895 Same rules for when in exponential and when as a value as in __str__.
896 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000897 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000898
899 def __neg__(self, context=None):
900 """Returns a copy with the sign switched.
901
902 Rounds, if it has reason.
903 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000904 if self._is_special:
905 ans = self._check_nans(context=context)
906 if ans:
907 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000908
909 if not self:
910 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000911 ans = self.copy_sign(Dec_0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000912 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000913 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000914
915 if context is None:
916 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000917 if context._rounding_decision == ALWAYS_ROUND:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000918 return ans._fix(context)
919 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000920
921 def __pos__(self, context=None):
922 """Returns a copy, unless it is a sNaN.
923
924 Rounds the number (if more then precision digits)
925 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000926 if self._is_special:
927 ans = self._check_nans(context=context)
928 if ans:
929 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000930
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000931 if not self:
932 # + (-0) = 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000933 ans = self.copy_sign(Dec_0)
934 else:
935 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000936
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000937 if context is None:
938 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000939 if context._rounding_decision == ALWAYS_ROUND:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000940 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000941 return ans
942
943 def __abs__(self, round=1, context=None):
944 """Returns the absolute value of self.
945
946 If the second argument is 0, do not round.
947 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000948 if self._is_special:
949 ans = self._check_nans(context=context)
950 if ans:
951 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000952
953 if not round:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000954 if context is None:
955 context = getcontext()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000956 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000957 context._set_rounding_decision(NEVER_ROUND)
958
959 if self._sign:
960 ans = self.__neg__(context=context)
961 else:
962 ans = self.__pos__(context=context)
963
964 return ans
965
966 def __add__(self, other, context=None):
967 """Returns self + other.
968
969 -INF + INF (or the reverse) cause InvalidOperation errors.
970 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000971 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000972 if other is NotImplemented:
973 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000974
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000975 if context is None:
976 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000977
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000978 if self._is_special or other._is_special:
979 ans = self._check_nans(other, context)
980 if ans:
981 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000982
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000983 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000984 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000985 if self._sign != other._sign and other._isinfinity():
986 return context._raise_error(InvalidOperation, '-INF + INF')
987 return Decimal(self)
988 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000989 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000990
991 shouldround = context._rounding_decision == ALWAYS_ROUND
992
993 exp = min(self._exp, other._exp)
994 negativezero = 0
995 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000996 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000997 negativezero = 1
998
999 if not self and not other:
1000 sign = min(self._sign, other._sign)
1001 if negativezero:
1002 sign = 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001003 ans = Decimal( (sign, (0,), exp))
1004 if shouldround:
1005 ans = ans._fix(context)
1006 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001007 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001008 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001009 ans = other._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001010 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001011 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001012 return ans
1013 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001014 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001015 ans = self._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001016 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001017 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001018 return ans
1019
1020 op1 = _WorkRep(self)
1021 op2 = _WorkRep(other)
1022 op1, op2 = _normalize(op1, op2, shouldround, context.prec)
1023
1024 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001025 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001026 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001027 if op1.int == op2.int:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001028 ans = Decimal((negativezero, (0,), exp))
1029 if shouldround:
1030 ans = ans._fix(context)
1031 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001032 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001033 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001034 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001035 if op1.sign == 1:
1036 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001037 op1.sign, op2.sign = op2.sign, op1.sign
1038 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001039 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001040 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001041 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001042 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001043 op1.sign, op2.sign = (0, 0)
1044 else:
1045 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001046 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001047
Raymond Hettinger17931de2004-10-27 06:21:46 +00001048 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001049 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001050 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001051 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001052
1053 result.exp = op1.exp
1054 ans = Decimal(result)
1055 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001056 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001057 return ans
1058
1059 __radd__ = __add__
1060
1061 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001062 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001063 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001064 if other is NotImplemented:
1065 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001066
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001067 if self._is_special or other._is_special:
1068 ans = self._check_nans(other, context=context)
1069 if ans:
1070 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001071
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001072 # self - other is computed as self + other.copy_negate()
1073 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001074
1075 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001076 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001077 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001078 if other is NotImplemented:
1079 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001080
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001081 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001082
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001083 def _increment(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001084 """Special case of add, adding 1eExponent
1085
1086 Since it is common, (rounding, for example) this adds
1087 (sign)*one E self._exp to the number more efficiently than add.
1088
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001089 Assumes that self is nonspecial.
1090
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001091 For example:
1092 Decimal('5.624e10')._increment() == Decimal('5.625e10')
1093 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001094 L = list(self._int)
1095 L[-1] += 1
1096 spot = len(L)-1
1097 while L[spot] == 10:
1098 L[spot] = 0
1099 if spot == 0:
1100 L[0:0] = [1]
1101 break
1102 L[spot-1] += 1
1103 spot -= 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001104 return Decimal((self._sign, L, self._exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001105
1106 def __mul__(self, other, context=None):
1107 """Return self * other.
1108
1109 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1110 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001111 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001112 if other is NotImplemented:
1113 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001114
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001115 if context is None:
1116 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001117
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001118 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001119
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001120 if self._is_special or other._is_special:
1121 ans = self._check_nans(other, context)
1122 if ans:
1123 return ans
1124
1125 if self._isinfinity():
1126 if not other:
1127 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1128 return Infsign[resultsign]
1129
1130 if other._isinfinity():
1131 if not self:
1132 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1133 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001134
1135 resultexp = self._exp + other._exp
1136 shouldround = context._rounding_decision == ALWAYS_ROUND
1137
1138 # Special case for multiplying by zero
1139 if not self or not other:
1140 ans = Decimal((resultsign, (0,), resultexp))
1141 if shouldround:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001142 # Fixing in case the exponent is out of bounds
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001143 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001144 return ans
1145
1146 # Special case for multiplying by power of 10
1147 if self._int == (1,):
1148 ans = Decimal((resultsign, other._int, resultexp))
1149 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 if other._int == (1,):
1153 ans = Decimal((resultsign, self._int, resultexp))
1154 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001155 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001156 return ans
1157
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001158 op1 = _WorkRep(self)
1159 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001160
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001161 ans = Decimal((resultsign,
1162 tuple(map(int, str(op1.int * op2.int))),
1163 resultexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001164 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001165 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001166
1167 return ans
1168 __rmul__ = __mul__
1169
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001170 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001171 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001172 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001173 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001174 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001175
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001176 if context is None:
1177 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001178
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001179 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001180
1181 if self._is_special or other._is_special:
1182 ans = self._check_nans(other, context)
1183 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001184 return ans
1185
1186 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001187 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001188
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001189 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001190 return Infsign[sign]
1191
1192 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001193 context._raise_error(Clamped, 'Division by infinity')
1194 return Decimal((sign, (0,), context.Etiny()))
1195
1196 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001197 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001198 if not self:
1199 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001200 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001201
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001202 if not self:
1203 exp = self._exp - other._exp
1204 coeff = 0
1205 else:
1206 # OK, so neither = 0, INF or NaN
1207 shift = len(other._int) - len(self._int) + context.prec + 1
1208 exp = self._exp - other._exp - shift
1209 op1 = _WorkRep(self)
1210 op2 = _WorkRep(other)
1211 if shift >= 0:
1212 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1213 else:
1214 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1215 if remainder:
1216 # result is not exact; adjust to ensure correct rounding
1217 if coeff % 5 == 0:
1218 coeff += 1
1219 else:
1220 # result is exact; get as close to ideal exponent as possible
1221 ideal_exp = self._exp - other._exp
1222 while exp < ideal_exp and coeff % 10 == 0:
1223 coeff //= 10
1224 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001225
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001226 ans = Decimal((sign, list(map(int, str(coeff))), exp))
1227 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001228
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001229 def _divide(self, other, context):
1230 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001231
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001232 Assumes that neither self nor other is a NaN, that self is not
1233 infinite and that other is nonzero.
1234 """
1235 sign = self._sign ^ other._sign
1236 if other._isinfinity():
1237 ideal_exp = self._exp
1238 else:
1239 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001240
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001241 expdiff = self.adjusted() - other.adjusted()
1242 if not self or other._isinfinity() or expdiff <= -2:
1243 return (Decimal((sign, (0,), 0)),
1244 self._rescale(ideal_exp, context.rounding))
1245 if expdiff <= context.prec:
1246 op1 = _WorkRep(self)
1247 op2 = _WorkRep(other)
1248 if op1.exp >= op2.exp:
1249 op1.int *= 10**(op1.exp - op2.exp)
1250 else:
1251 op2.int *= 10**(op2.exp - op1.exp)
1252 q, r = divmod(op1.int, op2.int)
1253 if q < 10**context.prec:
1254 return (Decimal((sign, list(map(int, str(q))), 0)),
1255 Decimal((self._sign, list(map(int, str(r))),
1256 ideal_exp)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001257
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001258 # Here the quotient is too large to be representable
1259 ans = context._raise_error(DivisionImpossible,
1260 'quotient too large in //, % or divmod')
1261 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001262
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001263 def __rtruediv__(self, other, context=None):
1264 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001265 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001266 if other is NotImplemented:
1267 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001268 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001269
1270 def __divmod__(self, other, context=None):
1271 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001272 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001273 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001274 other = _convert_other(other)
1275 if other is NotImplemented:
1276 return other
1277
1278 if context is None:
1279 context = getcontext()
1280
1281 ans = self._check_nans(other, context)
1282 if ans:
1283 return (ans, ans)
1284
1285 sign = self._sign ^ other._sign
1286 if self._isinfinity():
1287 if other._isinfinity():
1288 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1289 return ans, ans
1290 else:
1291 return (Infsign[sign],
1292 context._raise_error(InvalidOperation, 'INF % x'))
1293
1294 if not other:
1295 if not self:
1296 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1297 return ans, ans
1298 else:
1299 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1300 context._raise_error(InvalidOperation, 'x % 0'))
1301
1302 quotient, remainder = self._divide(other, context)
1303 if context._rounding_decision == ALWAYS_ROUND:
1304 remainder = remainder._fix(context)
1305 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001306
1307 def __rdivmod__(self, other, context=None):
1308 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001309 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001310 if other is NotImplemented:
1311 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001312 return other.__divmod__(self, context=context)
1313
1314 def __mod__(self, other, context=None):
1315 """
1316 self % other
1317 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001318 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001319 if other is NotImplemented:
1320 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001321
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001322 if context is None:
1323 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001324
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001325 ans = self._check_nans(other, context)
1326 if ans:
1327 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001328
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001329 if self._isinfinity():
1330 return context._raise_error(InvalidOperation, 'INF % x')
1331 elif not other:
1332 if self:
1333 return context._raise_error(InvalidOperation, 'x % 0')
1334 else:
1335 return context._raise_error(DivisionUndefined, '0 % 0')
1336
1337 remainder = self._divide(other, context)[1]
1338 if context._rounding_decision == ALWAYS_ROUND:
1339 remainder = remainder._fix(context)
1340 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001341
1342 def __rmod__(self, other, context=None):
1343 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001344 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001345 if other is NotImplemented:
1346 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001347 return other.__mod__(self, context=context)
1348
1349 def remainder_near(self, other, context=None):
1350 """
1351 Remainder nearest to 0- abs(remainder-near) <= other/2
1352 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001353 if context is None:
1354 context = getcontext()
1355
1356 other = _convert_other(other, raiseit=True)
1357
1358 ans = self._check_nans(other, context)
1359 if ans:
1360 return ans
1361
1362 # self == +/-infinity -> InvalidOperation
1363 if self._isinfinity():
1364 return context._raise_error(InvalidOperation,
1365 'remainder_near(infinity, x)')
1366
1367 # other == 0 -> either InvalidOperation or DivisionUndefined
1368 if not other:
1369 if self:
1370 return context._raise_error(InvalidOperation,
1371 'remainder_near(x, 0)')
1372 else:
1373 return context._raise_error(DivisionUndefined,
1374 'remainder_near(0, 0)')
1375
1376 # other = +/-infinity -> remainder = self
1377 if other._isinfinity():
1378 ans = Decimal(self)
1379 return ans._fix(context)
1380
1381 # self = 0 -> remainder = self, with ideal exponent
1382 ideal_exponent = min(self._exp, other._exp)
1383 if not self:
1384 ans = Decimal((self._sign, (0,), ideal_exponent))
1385 return ans._fix(context)
1386
1387 # catch most cases of large or small quotient
1388 expdiff = self.adjusted() - other.adjusted()
1389 if expdiff >= context.prec + 1:
1390 # expdiff >= prec+1 => abs(self/other) > 10**prec
1391 return context._raise_error(DivisionImpossible)
1392 if expdiff <= -2:
1393 # expdiff <= -2 => abs(self/other) < 0.1
1394 ans = self._rescale(ideal_exponent, context.rounding)
1395 return ans._fix(context)
1396
1397 # adjust both arguments to have the same exponent, then divide
1398 op1 = _WorkRep(self)
1399 op2 = _WorkRep(other)
1400 if op1.exp >= op2.exp:
1401 op1.int *= 10**(op1.exp - op2.exp)
1402 else:
1403 op2.int *= 10**(op2.exp - op1.exp)
1404 q, r = divmod(op1.int, op2.int)
1405 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1406 # 10**ideal_exponent. Apply correction to ensure that
1407 # abs(remainder) <= abs(other)/2
1408 if 2*r + (q&1) > op2.int:
1409 r -= op2.int
1410 q += 1
1411
1412 if q >= 10**context.prec:
1413 return context._raise_error(DivisionImpossible)
1414
1415 # result has same sign as self unless r is negative
1416 sign = self._sign
1417 if r < 0:
1418 sign = 1-sign
1419 r = -r
1420
1421 ans = Decimal((sign, list(map(int, str(r))), ideal_exponent))
1422 return ans._fix(context)
1423
1424 def __floordiv__(self, other, context=None):
1425 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001426 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001427 if other is NotImplemented:
1428 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001429
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001430 if context is None:
1431 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001432
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001433 ans = self._check_nans(other, context)
1434 if ans:
1435 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001436
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001437 if self._isinfinity():
1438 if other._isinfinity():
1439 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001440 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001441 return Infsign[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001442
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001443 if not other:
1444 if self:
1445 return context._raise_error(DivisionByZero, 'x // 0',
1446 self._sign ^ other._sign)
1447 else:
1448 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001449
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001450 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001451
1452 def __rfloordiv__(self, other, context=None):
1453 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001454 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001455 if other is NotImplemented:
1456 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001457 return other.__floordiv__(self, context=context)
1458
1459 def __float__(self):
1460 """Float representation."""
1461 return float(str(self))
1462
1463 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001464 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001465 if self._is_special:
1466 if self._isnan():
1467 context = getcontext()
1468 return context._raise_error(InvalidContext)
1469 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001470 raise OverflowError("Cannot convert infinity to int")
1471 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001472 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001473 return s*int(''.join(map(str, self._int)))*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001474 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001475 return s*int(''.join(map(str, self._int))[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001476
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001477 def _fix_nan(self, context):
1478 """Decapitate the payload of a NaN to fit the context"""
1479 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001480
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001481 # maximum length of payload is precision if _clamp=0,
1482 # precision-1 if _clamp=1.
1483 max_payload_len = context.prec - context._clamp
1484 if len(payload) > max_payload_len:
1485 pos = len(payload)-max_payload_len
1486 while pos < len(payload) and payload[pos] == 0:
1487 pos += 1
1488 payload = payload[pos:]
1489 return Decimal((self._sign, payload, self._exp))
1490 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001491
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001492 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001493 """Round if it is necessary to keep self within prec precision.
1494
1495 Rounds and fixes the exponent. Does not raise on a sNaN.
1496
1497 Arguments:
1498 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001499 context - context used.
1500 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001501
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001502 if context is None:
1503 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001504
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001505 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001506 if self._isnan():
1507 # decapitate payload if necessary
1508 return self._fix_nan(context)
1509 else:
1510 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001511 return Decimal(self)
1512
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001513 # if self is zero then exponent should be between Etiny and
1514 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1515 Etiny = context.Etiny()
1516 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001517 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001518 exp_max = [context.Emax, Etop][context._clamp]
1519 new_exp = min(max(self._exp, Etiny), exp_max)
1520 if new_exp != self._exp:
1521 context._raise_error(Clamped)
1522 return Decimal((self._sign, (0,), new_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001523 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001524 return Decimal(self)
1525
1526 # exp_min is the smallest allowable exponent of the result,
1527 # equal to max(self.adjusted()-context.prec+1, Etiny)
1528 exp_min = len(self._int) + self._exp - context.prec
1529 if exp_min > Etop:
1530 # overflow: exp_min > Etop iff self.adjusted() > Emax
1531 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001532 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001533 return context._raise_error(Overflow, 'above Emax', self._sign)
1534 self_is_subnormal = exp_min < Etiny
1535 if self_is_subnormal:
1536 context._raise_error(Subnormal)
1537 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001538
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001539 # round if self has too many digits
1540 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001541 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001542 ans = self._rescale(exp_min, context.rounding)
1543 if ans != self:
1544 context._raise_error(Inexact)
1545 if self_is_subnormal:
1546 context._raise_error(Underflow)
1547 if not ans:
1548 # raise Clamped on underflow to 0
1549 context._raise_error(Clamped)
1550 elif len(ans._int) == context.prec+1:
1551 # we get here only if rescaling rounds the
1552 # cofficient up to exactly 10**context.prec
1553 if ans._exp < Etop:
1554 ans = Decimal((ans._sign, ans._int[:-1], ans._exp+1))
1555 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)
1564 self_padded = self._int + (0,)*(self._exp - Etop)
1565 return Decimal((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)
1575 # the rounded result will have exponent self._exp + len(self._int) - prec;
1576
1577 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001578 """Also known as round-towards-0, truncate."""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001579 newexp = self._exp + len(self._int) - prec
1580 return Decimal((self._sign, self._int[:prec] or (0,), newexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001581
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001582 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001583 """Rounds away from 0."""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001584 newexp = self._exp + len(self._int) - prec
1585 tmp = Decimal((self._sign, self._int[:prec] or (0,), newexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001586 for digit in self._int[prec:]:
1587 if digit != 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001588 return tmp._increment()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001589 return tmp
1590
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001591 def _round_half_up(self, prec):
1592 """Rounds 5 up (away from 0)"""
1593 if self._int[prec] >= 5:
1594 return self._round_up(prec)
1595 else:
1596 return self._round_down(prec)
1597
1598 def _round_half_down(self, prec):
1599 """Round 5 down"""
1600 if self._int[prec] == 5:
1601 for digit in self._int[prec+1:]:
1602 if digit != 0:
1603 break
1604 else:
1605 return self._round_down(prec)
1606 return self._round_half_up(prec)
1607
1608 def _round_half_even(self, prec):
1609 """Round 5 to even, rest to nearest."""
1610 if prec and self._int[prec-1] & 1:
1611 return self._round_half_up(prec)
1612 else:
1613 return self._round_half_down(prec)
1614
1615 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001616 """Rounds up (not away from 0 if negative.)"""
1617 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001618 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001619 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001620 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001621
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001622 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001623 """Rounds down (not towards 0 if negative)"""
1624 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001625 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001626 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001627 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001628
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001629 def _round_05up(self, prec):
1630 """Round down unless digit prec-1 is 0 or 5."""
1631 if prec == 0 or self._int[prec-1] in (0, 5):
1632 return self._round_up(prec)
1633 else:
1634 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001635
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001636 def fma(self, other, third, context=None):
1637 """Fused multiply-add.
1638
1639 Returns self*other+third with no rounding of the intermediate
1640 product self*other.
1641
1642 self and other are multiplied together, with no rounding of
1643 the result. The third operand is then added to the result,
1644 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001645 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001646
1647 other = _convert_other(other, raiseit=True)
1648 third = _convert_other(third, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001649
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001650 if context is None:
1651 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001652
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001653 # do self*other in fresh context with no traps and no rounding
1654 mul_context = Context(traps=[], flags=[],
1655 _rounding_decision=NEVER_ROUND)
1656 product = self.__mul__(other, mul_context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001657
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001658 if mul_context.flags[InvalidOperation]:
1659 # reraise in current context
1660 return context._raise_error(InvalidOperation,
1661 'invalid multiplication in fma',
1662 1, product)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001663
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001664 ans = product.__add__(third, context)
1665 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001666
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001667 def _power_modulo(self, other, modulo, context=None):
1668 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001669
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001670 # if can't convert other and modulo to Decimal, raise
1671 # TypeError; there's no point returning NotImplemented (no
1672 # equivalent of __rpow__ for three argument pow)
1673 other = _convert_other(other, raiseit=True)
1674 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001675
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001676 if context is None:
1677 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001678
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001679 # deal with NaNs: if there are any sNaNs then first one wins,
1680 # (i.e. behaviour for NaNs is identical to that of fma)
1681 self_is_nan = self._isnan()
1682 other_is_nan = other._isnan()
1683 modulo_is_nan = modulo._isnan()
1684 if self_is_nan or other_is_nan or modulo_is_nan:
1685 if self_is_nan == 2:
1686 return context._raise_error(InvalidOperation, 'sNaN',
1687 1, self)
1688 if other_is_nan == 2:
1689 return context._raise_error(InvalidOperation, 'sNaN',
1690 1, other)
1691 if modulo_is_nan == 2:
1692 return context._raise_error(InvalidOperation, 'sNaN',
1693 1, modulo)
1694 if self_is_nan:
1695 return self._fix_nan(context)
1696 if other_is_nan:
1697 return other._fix_nan(context)
1698 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001699
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001700 # check inputs: we apply same restrictions as Python's pow()
1701 if not (self._isinteger() and
1702 other._isinteger() and
1703 modulo._isinteger()):
1704 return context._raise_error(InvalidOperation,
1705 'pow() 3rd argument not allowed '
1706 'unless all arguments are integers')
1707 if other < 0:
1708 return context._raise_error(InvalidOperation,
1709 'pow() 2nd argument cannot be '
1710 'negative when 3rd argument specified')
1711 if not modulo:
1712 return context._raise_error(InvalidOperation,
1713 'pow() 3rd argument cannot be 0')
1714
1715 # additional restriction for decimal: the modulus must be less
1716 # than 10**prec in absolute value
1717 if modulo.adjusted() >= context.prec:
1718 return context._raise_error(InvalidOperation,
1719 'insufficient precision: pow() 3rd '
1720 'argument must not have more than '
1721 'precision digits')
1722
1723 # define 0**0 == NaN, for consistency with two-argument pow
1724 # (even though it hurts!)
1725 if not other and not self:
1726 return context._raise_error(InvalidOperation,
1727 'at least one of pow() 1st argument '
1728 'and 2nd argument must be nonzero ;'
1729 '0**0 is not defined')
1730
1731 # compute sign of result
1732 if other._iseven():
1733 sign = 0
1734 else:
1735 sign = self._sign
1736
1737 # convert modulo to a Python integer, and self and other to
1738 # Decimal integers (i.e. force their exponents to be >= 0)
1739 modulo = abs(int(modulo))
1740 base = _WorkRep(self.to_integral_value())
1741 exponent = _WorkRep(other.to_integral_value())
1742
1743 # compute result using integer pow()
1744 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1745 for i in range(exponent.exp):
1746 base = pow(base, 10, modulo)
1747 base = pow(base, exponent.int, modulo)
1748
1749 return Decimal((sign, list(map(int, str(base))), 0))
1750
1751 def _power_exact(self, other, p):
1752 """Attempt to compute self**other exactly.
1753
1754 Given Decimals self and other and an integer p, attempt to
1755 compute an exact result for the power self**other, with p
1756 digits of precision. Return None if self**other is not
1757 exactly representable in p digits.
1758
1759 Assumes that elimination of special cases has already been
1760 performed: self and other must both be nonspecial; self must
1761 be positive and not numerically equal to 1; other must be
1762 nonzero. For efficiency, other._exp should not be too large,
1763 so that 10**abs(other._exp) is a feasible calculation."""
1764
1765 # In the comments below, we write x for the value of self and
1766 # y for the value of other. Write x = xc*10**xe and y =
1767 # yc*10**ye.
1768
1769 # The main purpose of this method is to identify the *failure*
1770 # of x**y to be exactly representable with as little effort as
1771 # possible. So we look for cheap and easy tests that
1772 # eliminate the possibility of x**y being exact. Only if all
1773 # these tests are passed do we go on to actually compute x**y.
1774
1775 # Here's the main idea. First normalize both x and y. We
1776 # express y as a rational m/n, with m and n relatively prime
1777 # and n>0. Then for x**y to be exactly representable (at
1778 # *any* precision), xc must be the nth power of a positive
1779 # integer and xe must be divisible by n. If m is negative
1780 # then additionally xc must be a power of either 2 or 5, hence
1781 # a power of 2**n or 5**n.
1782 #
1783 # There's a limit to how small |y| can be: if y=m/n as above
1784 # then:
1785 #
1786 # (1) if xc != 1 then for the result to be representable we
1787 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1788 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1789 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1790 # representable.
1791 #
1792 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1793 # |y| < 1/|xe| then the result is not representable.
1794 #
1795 # Note that since x is not equal to 1, at least one of (1) and
1796 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1797 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1798 #
1799 # There's also a limit to how large y can be, at least if it's
1800 # positive: the normalized result will have coefficient xc**y,
1801 # so if it's representable then xc**y < 10**p, and y <
1802 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1803 # not exactly representable.
1804
1805 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1806 # so |y| < 1/xe and the result is not representable.
1807 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1808 # < 1/nbits(xc).
1809
1810 x = _WorkRep(self)
1811 xc, xe = x.int, x.exp
1812 while xc % 10 == 0:
1813 xc //= 10
1814 xe += 1
1815
1816 y = _WorkRep(other)
1817 yc, ye = y.int, y.exp
1818 while yc % 10 == 0:
1819 yc //= 10
1820 ye += 1
1821
1822 # case where xc == 1: result is 10**(xe*y), with xe*y
1823 # required to be an integer
1824 if xc == 1:
1825 if ye >= 0:
1826 exponent = xe*yc*10**ye
1827 else:
1828 exponent, remainder = divmod(xe*yc, 10**-ye)
1829 if remainder:
1830 return None
1831 if y.sign == 1:
1832 exponent = -exponent
1833 # if other is a nonnegative integer, use ideal exponent
1834 if other._isinteger() and other._sign == 0:
1835 ideal_exponent = self._exp*int(other)
1836 zeros = min(exponent-ideal_exponent, p-1)
1837 else:
1838 zeros = 0
1839 return Decimal((0, (1,) + (0,)*zeros, exponent-zeros))
1840
1841 # case where y is negative: xc must be either a power
1842 # of 2 or a power of 5.
1843 if y.sign == 1:
1844 last_digit = xc % 10
1845 if last_digit in (2,4,6,8):
1846 # quick test for power of 2
1847 if xc & -xc != xc:
1848 return None
1849 # now xc is a power of 2; e is its exponent
1850 e = _nbits(xc)-1
1851 # find e*y and xe*y; both must be integers
1852 if ye >= 0:
1853 y_as_int = yc*10**ye
1854 e = e*y_as_int
1855 xe = xe*y_as_int
1856 else:
1857 ten_pow = 10**-ye
1858 e, remainder = divmod(e*yc, ten_pow)
1859 if remainder:
1860 return None
1861 xe, remainder = divmod(xe*yc, ten_pow)
1862 if remainder:
1863 return None
1864
1865 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1866 return None
1867 xc = 5**e
1868
1869 elif last_digit == 5:
1870 # e >= log_5(xc) if xc is a power of 5; we have
1871 # equality all the way up to xc=5**2658
1872 e = _nbits(xc)*28//65
1873 xc, remainder = divmod(5**e, xc)
1874 if remainder:
1875 return None
1876 while xc % 5 == 0:
1877 xc //= 5
1878 e -= 1
1879 if ye >= 0:
1880 y_as_integer = yc*10**ye
1881 e = e*y_as_integer
1882 xe = xe*y_as_integer
1883 else:
1884 ten_pow = 10**-ye
1885 e, remainder = divmod(e*yc, ten_pow)
1886 if remainder:
1887 return None
1888 xe, remainder = divmod(xe*yc, ten_pow)
1889 if remainder:
1890 return None
1891 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1892 return None
1893 xc = 2**e
1894 else:
1895 return None
1896
1897 if xc >= 10**p:
1898 return None
1899 xe = -e-xe
1900 return Decimal((0, list(map(int, str(xc))), xe))
1901
1902 # now y is positive; find m and n such that y = m/n
1903 if ye >= 0:
1904 m, n = yc*10**ye, 1
1905 else:
1906 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1907 return None
1908 xc_bits = _nbits(xc)
1909 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1910 return None
1911 m, n = yc, 10**(-ye)
1912 while m % 2 == n % 2 == 0:
1913 m //= 2
1914 n //= 2
1915 while m % 5 == n % 5 == 0:
1916 m //= 5
1917 n //= 5
1918
1919 # compute nth root of xc*10**xe
1920 if n > 1:
1921 # if 1 < xc < 2**n then xc isn't an nth power
1922 if xc != 1 and xc_bits <= n:
1923 return None
1924
1925 xe, rem = divmod(xe, n)
1926 if rem != 0:
1927 return None
1928
1929 # compute nth root of xc using Newton's method
1930 a = 1 << -(-_nbits(xc)//n) # initial estimate
1931 while True:
1932 q, r = divmod(xc, a**(n-1))
1933 if a <= q:
1934 break
1935 else:
1936 a = (a*(n-1) + q)//n
1937 if not (a == q and r == 0):
1938 return None
1939 xc = a
1940
1941 # now xc*10**xe is the nth root of the original xc*10**xe
1942 # compute mth power of xc*10**xe
1943
1944 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1945 # 10**p and the result is not representable.
1946 if xc > 1 and m > p*100//_log10_lb(xc):
1947 return None
1948 xc = xc**m
1949 xe *= m
1950 if xc > 10**p:
1951 return None
1952
1953 # by this point the result *is* exactly representable
1954 # adjust the exponent to get as close as possible to the ideal
1955 # exponent, if necessary
1956 str_xc = str(xc)
1957 if other._isinteger() and other._sign == 0:
1958 ideal_exponent = self._exp*int(other)
1959 zeros = min(xe-ideal_exponent, p-len(str_xc))
1960 else:
1961 zeros = 0
1962 return Decimal((0, list(map(int, str_xc))+[0,]*zeros, xe-zeros))
1963
1964 def __pow__(self, other, modulo=None, context=None):
1965 """Return self ** other [ % modulo].
1966
1967 With two arguments, compute self**other.
1968
1969 With three arguments, compute (self**other) % modulo. For the
1970 three argument form, the following restrictions on the
1971 arguments hold:
1972
1973 - all three arguments must be integral
1974 - other must be nonnegative
1975 - either self or other (or both) must be nonzero
1976 - modulo must be nonzero and must have at most p digits,
1977 where p is the context precision.
1978
1979 If any of these restrictions is violated the InvalidOperation
1980 flag is raised.
1981
1982 The result of pow(self, other, modulo) is identical to the
1983 result that would be obtained by computing (self**other) %
1984 modulo with unbounded precision, but is computed more
1985 efficiently. It is always exact.
1986 """
1987
1988 if modulo is not None:
1989 return self._power_modulo(other, modulo, context)
1990
1991 other = _convert_other(other)
1992 if other is NotImplemented:
1993 return other
1994
1995 if context is None:
1996 context = getcontext()
1997
1998 # either argument is a NaN => result is NaN
1999 ans = self._check_nans(other, context)
2000 if ans:
2001 return ans
2002
2003 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2004 if not other:
2005 if not self:
2006 return context._raise_error(InvalidOperation, '0 ** 0')
2007 else:
2008 return Dec_p1
2009
2010 # result has sign 1 iff self._sign is 1 and other is an odd integer
2011 result_sign = 0
2012 if self._sign == 1:
2013 if other._isinteger():
2014 if not other._iseven():
2015 result_sign = 1
2016 else:
2017 # -ve**noninteger = NaN
2018 # (-0)**noninteger = 0**noninteger
2019 if self:
2020 return context._raise_error(InvalidOperation,
2021 'x ** y with x negative and y not an integer')
2022 # negate self, without doing any unwanted rounding
2023 self = Decimal((0, self._int, self._exp))
2024
2025 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2026 if not self:
2027 if other._sign == 0:
2028 return Decimal((result_sign, (0,), 0))
2029 else:
2030 return Infsign[result_sign]
2031
2032 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002033 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002034 if other._sign == 0:
2035 return Infsign[result_sign]
2036 else:
2037 return Decimal((result_sign, (0,), 0))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002038
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002039 # 1**other = 1, but the choice of exponent and the flags
2040 # depend on the exponent of self, and on whether other is a
2041 # positive integer, a negative integer, or neither
2042 if self == Dec_p1:
2043 if other._isinteger():
2044 # exp = max(self._exp*max(int(other), 0),
2045 # 1-context.prec) but evaluating int(other) directly
2046 # is dangerous until we know other is small (other
2047 # could be 1e999999999)
2048 if other._sign == 1:
2049 multiplier = 0
2050 elif other > context.prec:
2051 multiplier = context.prec
2052 else:
2053 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002054
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002055 exp = self._exp * multiplier
2056 if exp < 1-context.prec:
2057 exp = 1-context.prec
2058 context._raise_error(Rounded)
2059 else:
2060 context._raise_error(Inexact)
2061 context._raise_error(Rounded)
2062 exp = 1-context.prec
2063
2064 return Decimal((result_sign, (1,)+(0,)*-exp, exp))
2065
2066 # compute adjusted exponent of self
2067 self_adj = self.adjusted()
2068
2069 # self ** infinity is infinity if self > 1, 0 if self < 1
2070 # self ** -infinity is infinity if self < 1, 0 if self > 1
2071 if other._isinfinity():
2072 if (other._sign == 0) == (self_adj < 0):
2073 return Decimal((result_sign, (0,), 0))
2074 else:
2075 return Infsign[result_sign]
2076
2077 # from here on, the result always goes through the call
2078 # to _fix at the end of this function.
2079 ans = None
2080
2081 # crude test to catch cases of extreme overflow/underflow. If
2082 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2083 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2084 # self**other >= 10**(Emax+1), so overflow occurs. The test
2085 # for underflow is similar.
2086 bound = self._log10_exp_bound() + other.adjusted()
2087 if (self_adj >= 0) == (other._sign == 0):
2088 # self > 1 and other +ve, or self < 1 and other -ve
2089 # possibility of overflow
2090 if bound >= len(str(context.Emax)):
2091 ans = Decimal((result_sign, (1,), context.Emax+1))
2092 else:
2093 # self > 1 and other -ve, or self < 1 and other +ve
2094 # possibility of underflow to 0
2095 Etiny = context.Etiny()
2096 if bound >= len(str(-Etiny)):
2097 ans = Decimal((result_sign, (1,), Etiny-1))
2098
2099 # try for an exact result with precision +1
2100 if ans is None:
2101 ans = self._power_exact(other, context.prec + 1)
2102 if ans is not None and result_sign == 1:
2103 ans = Decimal((1, ans._int, ans._exp))
2104
2105 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2106 if ans is None:
2107 p = context.prec
2108 x = _WorkRep(self)
2109 xc, xe = x.int, x.exp
2110 y = _WorkRep(other)
2111 yc, ye = y.int, y.exp
2112 if y.sign == 1:
2113 yc = -yc
2114
2115 # compute correctly rounded result: start with precision +3,
2116 # then increase precision until result is unambiguously roundable
2117 extra = 3
2118 while True:
2119 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2120 if coeff % (5*10**(len(str(coeff))-p-1)):
2121 break
2122 extra += 3
2123
2124 ans = Decimal((result_sign, list(map(int, str(coeff))), exp))
2125
2126 # the specification says that for non-integer other we need to
2127 # raise Inexact, even when the result is actually exact. In
2128 # the same way, we need to raise Underflow here if the result
2129 # is subnormal. (The call to _fix will take care of raising
2130 # Rounded and Subnormal, as usual.)
2131 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002132 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002133 # pad with zeros up to length context.prec+1 if necessary
2134 if len(ans._int) <= context.prec:
2135 expdiff = context.prec+1 - len(ans._int)
2136 ans = Decimal((ans._sign, ans._int+(0,)*expdiff, ans._exp-expdiff))
2137 if ans.adjusted() < context.Emin:
2138 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002139
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002140 # unlike exp, ln and log10, the power function respects the
2141 # rounding mode; no need to use ROUND_HALF_EVEN here
2142 ans = ans._fix(context)
2143 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002144
2145 def __rpow__(self, other, context=None):
2146 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002147 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002148 if other is NotImplemented:
2149 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002150 return other.__pow__(self, context=context)
2151
2152 def normalize(self, context=None):
2153 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002154
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002155 if context is None:
2156 context = getcontext()
2157
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002158 if self._is_special:
2159 ans = self._check_nans(context=context)
2160 if ans:
2161 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002162
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002163 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002164 if dup._isinfinity():
2165 return dup
2166
2167 if not dup:
2168 return Decimal( (dup._sign, (0,), 0) )
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002169 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002170 end = len(dup._int)
2171 exp = dup._exp
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002172 while dup._int[end-1] == 0 and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002173 exp += 1
2174 end -= 1
2175 return Decimal( (dup._sign, dup._int[:end], exp) )
2176
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002177 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002178 """Quantize self so its exponent is the same as that of exp.
2179
2180 Similar to self._rescale(exp._exp) but with error checking.
2181 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002182 exp = _convert_other(exp, raiseit=True)
2183
2184 if context is None:
2185 context = getcontext()
2186 if rounding is None:
2187 rounding = context.rounding
2188
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002189 if self._is_special or exp._is_special:
2190 ans = self._check_nans(exp, context)
2191 if ans:
2192 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002193
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002194 if exp._isinfinity() or self._isinfinity():
2195 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002196 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002197 return context._raise_error(InvalidOperation,
2198 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002199
2200 # if we're not watching exponents, do a simple rescale
2201 if not watchexp:
2202 ans = self._rescale(exp._exp, rounding)
2203 # raise Inexact and Rounded where appropriate
2204 if ans._exp > self._exp:
2205 context._raise_error(Rounded)
2206 if ans != self:
2207 context._raise_error(Inexact)
2208 return ans
2209
2210 # exp._exp should be between Etiny and Emax
2211 if not (context.Etiny() <= exp._exp <= context.Emax):
2212 return context._raise_error(InvalidOperation,
2213 'target exponent out of bounds in quantize')
2214
2215 if not self:
2216 ans = Decimal((self._sign, (0,), exp._exp))
2217 return ans._fix(context)
2218
2219 self_adjusted = self.adjusted()
2220 if self_adjusted > context.Emax:
2221 return context._raise_error(InvalidOperation,
2222 'exponent of quantize result too large for current context')
2223 if self_adjusted - exp._exp + 1 > context.prec:
2224 return context._raise_error(InvalidOperation,
2225 'quantize result has too many digits for current context')
2226
2227 ans = self._rescale(exp._exp, rounding)
2228 if ans.adjusted() > context.Emax:
2229 return context._raise_error(InvalidOperation,
2230 'exponent of quantize result too large for current context')
2231 if len(ans._int) > context.prec:
2232 return context._raise_error(InvalidOperation,
2233 'quantize result has too many digits for current context')
2234
2235 # raise appropriate flags
2236 if ans._exp > self._exp:
2237 context._raise_error(Rounded)
2238 if ans != self:
2239 context._raise_error(Inexact)
2240 if ans and ans.adjusted() < context.Emin:
2241 context._raise_error(Subnormal)
2242
2243 # call to fix takes care of any necessary folddown
2244 ans = ans._fix(context)
2245 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002246
2247 def same_quantum(self, other):
2248 """Test whether self and other have the same exponent.
2249
2250 same as self._exp == other._exp, except NaN == sNaN
2251 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002252 if self._is_special or other._is_special:
2253 if self._isnan() or other._isnan():
2254 return self._isnan() and other._isnan() and True
2255 if self._isinfinity() or other._isinfinity():
2256 return self._isinfinity() and other._isinfinity() and True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002257 return self._exp == other._exp
2258
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002259 def _rescale(self, exp, rounding):
2260 """Rescale self so that the exponent is exp, either by padding with zeros
2261 or by truncating digits, using the given rounding mode.
2262
2263 Specials are returned without change. This operation is
2264 quiet: it raises no flags, and uses no information from the
2265 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002266
2267 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002268 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002269 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002270 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002271 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002272 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002273 return Decimal((self._sign, (0,), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002274
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002275 if self._exp >= exp:
2276 # pad answer with zeros if necessary
2277 return Decimal((self._sign, self._int + (0,)*(self._exp - exp), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002278
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002279 # too many digits; round and lose data. If self.adjusted() <
2280 # exp-1, replace self by 10**(exp-1) before rounding
2281 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002282 if digits < 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002283 self = Decimal((self._sign, (1,), exp-1))
2284 digits = 0
2285 this_function = getattr(self, self._pick_rounding_function[rounding])
2286 return this_function(digits)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002287
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002288 def to_integral_exact(self, rounding=None, context=None):
2289 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002290
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002291 If no rounding mode is specified, take the rounding mode from
2292 the context. This method raises the Rounded and Inexact flags
2293 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002294
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002295 See also: to_integral_value, which does exactly the same as
2296 this method except that it doesn't raise Inexact or Rounded.
2297 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002298 if self._is_special:
2299 ans = self._check_nans(context=context)
2300 if ans:
2301 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002302 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002303 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002304 return Decimal(self)
2305 if not self:
2306 return Decimal((self._sign, (0,), 0))
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002307 if context is None:
2308 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002309 if rounding is None:
2310 rounding = context.rounding
2311 context._raise_error(Rounded)
2312 ans = self._rescale(0, rounding)
2313 if ans != self:
2314 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002315 return ans
2316
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002317 def to_integral_value(self, rounding=None, context=None):
2318 """Rounds to the nearest integer, without raising inexact, rounded."""
2319 if context is None:
2320 context = getcontext()
2321 if rounding is None:
2322 rounding = context.rounding
2323 if self._is_special:
2324 ans = self._check_nans(context=context)
2325 if ans:
2326 return ans
2327 return Decimal(self)
2328 if self._exp >= 0:
2329 return Decimal(self)
2330 else:
2331 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002332
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002333 # the method name changed, but we provide also the old one, for compatibility
2334 to_integral = to_integral_value
2335
2336 def sqrt(self, context=None):
2337 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002338 if self._is_special:
2339 ans = self._check_nans(context=context)
2340 if ans:
2341 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002342
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002343 if self._isinfinity() and self._sign == 0:
2344 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002345
2346 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002347 # exponent = self._exp // 2. sqrt(-0) = -0
2348 ans = Decimal((self._sign, (0,), self._exp // 2))
2349 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002350
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002351 if context is None:
2352 context = getcontext()
2353
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002354 if self._sign == 1:
2355 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2356
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002357 # At this point self represents a positive number. Let p be
2358 # the desired precision and express self in the form c*100**e
2359 # with c a positive real number and e an integer, c and e
2360 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2361 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2362 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2363 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2364 # the closest integer to sqrt(c) with the even integer chosen
2365 # in the case of a tie.
2366 #
2367 # To ensure correct rounding in all cases, we use the
2368 # following trick: we compute the square root to an extra
2369 # place (precision p+1 instead of precision p), rounding down.
2370 # Then, if the result is inexact and its last digit is 0 or 5,
2371 # we increase the last digit to 1 or 6 respectively; if it's
2372 # exact we leave the last digit alone. Now the final round to
2373 # p places (or fewer in the case of underflow) will round
2374 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002375
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002376 # use an extra digit of precision
2377 prec = context.prec+1
2378
2379 # write argument in the form c*100**e where e = self._exp//2
2380 # is the 'ideal' exponent, to be used if the square root is
2381 # exactly representable. l is the number of 'digits' of c in
2382 # base 100, so that 100**(l-1) <= c < 100**l.
2383 op = _WorkRep(self)
2384 e = op.exp >> 1
2385 if op.exp & 1:
2386 c = op.int * 10
2387 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002388 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002389 c = op.int
2390 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002391
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002392 # rescale so that c has exactly prec base 100 'digits'
2393 shift = prec-l
2394 if shift >= 0:
2395 c *= 100**shift
2396 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002397 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002398 c, remainder = divmod(c, 100**-shift)
2399 exact = not remainder
2400 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002401
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002402 # find n = floor(sqrt(c)) using Newton's method
2403 n = 10**prec
2404 while True:
2405 q = c//n
2406 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002407 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002408 else:
2409 n = n + q >> 1
2410 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002411
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002412 if exact:
2413 # result is exact; rescale to use ideal exponent e
2414 if shift >= 0:
2415 # assert n % 10**shift == 0
2416 n //= 10**shift
2417 else:
2418 n *= 10**-shift
2419 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002420 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002421 # result is not exact; fix last digit as described above
2422 if n % 5 == 0:
2423 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002424
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002425 ans = Decimal((0, list(map(int, str(n))), e))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002426
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002427 # round, and fit to current context
2428 context = context._shallow_copy()
2429 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002430 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002431 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002432
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002433 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002434
2435 def max(self, other, context=None):
2436 """Returns the larger value.
2437
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002438 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002439 NaN (and signals if one is sNaN). Also rounds.
2440 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002441 other = _convert_other(other, raiseit=True)
2442
2443 if context is None:
2444 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002445
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002446 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002447 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002448 # number is always returned
2449 sn = self._isnan()
2450 on = other._isnan()
2451 if sn or on:
2452 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002453 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002454 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002455 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002456 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002457
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002458 c = self.__cmp__(other)
2459 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002460 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002461 # then an ordering is applied:
2462 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002463 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002464 # positive sign and min returns the operand with the negative sign
2465 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002466 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002467 # the result. This is exactly the ordering used in compare_total.
2468 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002469
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002470 if c == -1:
2471 ans = other
2472 else:
2473 ans = self
2474
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002475 if context._rounding_decision == ALWAYS_ROUND:
2476 return ans._fix(context)
2477 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002478
2479 def min(self, other, context=None):
2480 """Returns the smaller value.
2481
Guido van Rossumd8faa362007-04-27 19:54:29 +00002482 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002483 NaN (and signals if one is sNaN). Also rounds.
2484 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002485 other = _convert_other(other, raiseit=True)
2486
2487 if context is None:
2488 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002489
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002490 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002491 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002492 # number is always returned
2493 sn = self._isnan()
2494 on = other._isnan()
2495 if sn or on:
2496 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002497 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002498 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002499 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002500 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002501
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002502 c = self.__cmp__(other)
2503 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002504 c = self.compare_total(other)
2505
2506 if c == -1:
2507 ans = self
2508 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002509 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002510
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002511 if context._rounding_decision == ALWAYS_ROUND:
2512 return ans._fix(context)
2513 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002514
2515 def _isinteger(self):
2516 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002517 if self._is_special:
2518 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002519 if self._exp >= 0:
2520 return True
2521 rest = self._int[self._exp:]
2522 return rest == (0,)*len(rest)
2523
2524 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002525 """Returns True if self is even. Assumes self is an integer."""
2526 if not self or self._exp > 0:
2527 return True
Raymond Hettinger61992ef2004-08-06 23:42:16 +00002528 return self._int[-1+self._exp] & 1 == 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002529
2530 def adjusted(self):
2531 """Return the adjusted exponent of self"""
2532 try:
2533 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002534 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002535 except TypeError:
2536 return 0
2537
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002538 def canonical(self, context=None):
2539 """Returns the same Decimal object.
2540
2541 As we do not have different encodings for the same number, the
2542 received object already is in its canonical form.
2543 """
2544 return self
2545
2546 def compare_signal(self, other, context=None):
2547 """Compares self to the other operand numerically.
2548
2549 It's pretty much like compare(), but all NaNs signal, with signaling
2550 NaNs taking precedence over quiet NaNs.
2551 """
2552 if context is None:
2553 context = getcontext()
2554
2555 self_is_nan = self._isnan()
2556 other_is_nan = other._isnan()
2557 if self_is_nan == 2:
2558 return context._raise_error(InvalidOperation, 'sNaN',
2559 1, self)
2560 if other_is_nan == 2:
2561 return context._raise_error(InvalidOperation, 'sNaN',
2562 1, other)
2563 if self_is_nan:
2564 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2565 1, self)
2566 if other_is_nan:
2567 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2568 1, other)
2569 return self.compare(other, context=context)
2570
2571 def compare_total(self, other):
2572 """Compares self to other using the abstract representations.
2573
2574 This is not like the standard compare, which use their numerical
2575 value. Note that a total ordering is defined for all possible abstract
2576 representations.
2577 """
2578 # if one is negative and the other is positive, it's easy
2579 if self._sign and not other._sign:
2580 return Dec_n1
2581 if not self._sign and other._sign:
2582 return Dec_p1
2583 sign = self._sign
2584
2585 # let's handle both NaN types
2586 self_nan = self._isnan()
2587 other_nan = other._isnan()
2588 if self_nan or other_nan:
2589 if self_nan == other_nan:
2590 if self._int < other._int:
2591 if sign:
2592 return Dec_p1
2593 else:
2594 return Dec_n1
2595 if self._int > other._int:
2596 if sign:
2597 return Dec_n1
2598 else:
2599 return Dec_p1
2600 return Dec_0
2601
2602 if sign:
2603 if self_nan == 1:
2604 return Dec_n1
2605 if other_nan == 1:
2606 return Dec_p1
2607 if self_nan == 2:
2608 return Dec_n1
2609 if other_nan == 2:
2610 return Dec_p1
2611 else:
2612 if self_nan == 1:
2613 return Dec_p1
2614 if other_nan == 1:
2615 return Dec_n1
2616 if self_nan == 2:
2617 return Dec_p1
2618 if other_nan == 2:
2619 return Dec_n1
2620
2621 if self < other:
2622 return Dec_n1
2623 if self > other:
2624 return Dec_p1
2625
2626 if self._exp < other._exp:
2627 if sign:
2628 return Dec_p1
2629 else:
2630 return Dec_n1
2631 if self._exp > other._exp:
2632 if sign:
2633 return Dec_n1
2634 else:
2635 return Dec_p1
2636 return Dec_0
2637
2638
2639 def compare_total_mag(self, other):
2640 """Compares self to other using abstract repr., ignoring sign.
2641
2642 Like compare_total, but with operand's sign ignored and assumed to be 0.
2643 """
2644 s = self.copy_abs()
2645 o = other.copy_abs()
2646 return s.compare_total(o)
2647
2648 def copy_abs(self):
2649 """Returns a copy with the sign set to 0. """
2650 return Decimal((0, self._int, self._exp))
2651
2652 def copy_negate(self):
2653 """Returns a copy with the sign inverted."""
2654 if self._sign:
2655 return Decimal((0, self._int, self._exp))
2656 else:
2657 return Decimal((1, self._int, self._exp))
2658
2659 def copy_sign(self, other):
2660 """Returns self with the sign of other."""
2661 return Decimal((other._sign, self._int, self._exp))
2662
2663 def exp(self, context=None):
2664 """Returns e ** self."""
2665
2666 if context is None:
2667 context = getcontext()
2668
2669 # exp(NaN) = NaN
2670 ans = self._check_nans(context=context)
2671 if ans:
2672 return ans
2673
2674 # exp(-Infinity) = 0
2675 if self._isinfinity() == -1:
2676 return Dec_0
2677
2678 # exp(0) = 1
2679 if not self:
2680 return Dec_p1
2681
2682 # exp(Infinity) = Infinity
2683 if self._isinfinity() == 1:
2684 return Decimal(self)
2685
2686 # the result is now guaranteed to be inexact (the true
2687 # mathematical result is transcendental). There's no need to
2688 # raise Rounded and Inexact here---they'll always be raised as
2689 # a result of the call to _fix.
2690 p = context.prec
2691 adj = self.adjusted()
2692
2693 # we only need to do any computation for quite a small range
2694 # of adjusted exponents---for example, -29 <= adj <= 10 for
2695 # the default context. For smaller exponent the result is
2696 # indistinguishable from 1 at the given precision, while for
2697 # larger exponent the result either overflows or underflows.
2698 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2699 # overflow
2700 ans = Decimal((0, (1,), context.Emax+1))
2701 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2702 # underflow to 0
2703 ans = Decimal((0, (1,), context.Etiny()-1))
2704 elif self._sign == 0 and adj < -p:
2705 # p+1 digits; final round will raise correct flags
2706 ans = Decimal((0, (1,) + (0,)*(p-1) + (1,), -p))
2707 elif self._sign == 1 and adj < -p-1:
2708 # p+1 digits; final round will raise correct flags
2709 ans = Decimal((0, (9,)*(p+1), -p-1))
2710 # general case
2711 else:
2712 op = _WorkRep(self)
2713 c, e = op.int, op.exp
2714 if op.sign == 1:
2715 c = -c
2716
2717 # compute correctly rounded result: increase precision by
2718 # 3 digits at a time until we get an unambiguously
2719 # roundable result
2720 extra = 3
2721 while True:
2722 coeff, exp = _dexp(c, e, p+extra)
2723 if coeff % (5*10**(len(str(coeff))-p-1)):
2724 break
2725 extra += 3
2726
2727 ans = Decimal((0, list(map(int, str(coeff))), exp))
2728
2729 # at this stage, ans should round correctly with *any*
2730 # rounding mode, not just with ROUND_HALF_EVEN
2731 context = context._shallow_copy()
2732 rounding = context._set_rounding(ROUND_HALF_EVEN)
2733 ans = ans._fix(context)
2734 context.rounding = rounding
2735
2736 return ans
2737
2738 def is_canonical(self):
2739 """Returns 1 if self is canonical; otherwise returns 0."""
2740 return Dec_p1
2741
2742 def is_finite(self):
2743 """Returns 1 if self is finite, otherwise returns 0.
2744
2745 For it to be finite, it must be neither infinite nor a NaN.
2746 """
2747 if self._is_special:
2748 return Dec_0
2749 else:
2750 return Dec_p1
2751
2752 def is_infinite(self):
2753 """Returns 1 if self is an Infinite, otherwise returns 0."""
2754 if self._isinfinity():
2755 return Dec_p1
2756 else:
2757 return Dec_0
2758
2759 def is_nan(self):
2760 """Returns 1 if self is qNaN or sNaN, otherwise returns 0."""
2761 if self._isnan():
2762 return Dec_p1
2763 else:
2764 return Dec_0
2765
2766 def is_normal(self, context=None):
2767 """Returns 1 if self is a normal number, otherwise returns 0."""
2768 if self._is_special:
2769 return Dec_0
2770 if not self:
2771 return Dec_0
2772 if context is None:
2773 context = getcontext()
2774 if context.Emin <= self.adjusted() <= context.Emax:
2775 return Dec_p1
2776 else:
2777 return Dec_0
2778
2779 def is_qnan(self):
2780 """Returns 1 if self is a quiet NaN, otherwise returns 0."""
2781 if self._isnan() == 1:
2782 return Dec_p1
2783 else:
2784 return Dec_0
2785
2786 def is_signed(self):
2787 """Returns 1 if self is negative, otherwise returns 0."""
2788 return Decimal(self._sign)
2789
2790 def is_snan(self):
2791 """Returns 1 if self is a signaling NaN, otherwise returns 0."""
2792 if self._isnan() == 2:
2793 return Dec_p1
2794 else:
2795 return Dec_0
2796
2797 def is_subnormal(self, context=None):
2798 """Returns 1 if self is subnormal, otherwise returns 0."""
2799 if self._is_special:
2800 return Dec_0
2801 if not self:
2802 return Dec_0
2803 if context is None:
2804 context = getcontext()
2805
2806 r = self._exp + len(self._int)
2807 if r <= context.Emin:
2808 return Dec_p1
2809 return Dec_0
2810
2811 def is_zero(self):
2812 """Returns 1 if self is a zero, otherwise returns 0."""
2813 if self:
2814 return Dec_0
2815 else:
2816 return Dec_p1
2817
2818 def _ln_exp_bound(self):
2819 """Compute a lower bound for the adjusted exponent of self.ln().
2820 In other words, compute r such that self.ln() >= 10**r. Assumes
2821 that self is finite and positive and that self != 1.
2822 """
2823
2824 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2825 adj = self._exp + len(self._int) - 1
2826 if adj >= 1:
2827 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2828 return len(str(adj*23//10)) - 1
2829 if adj <= -2:
2830 # argument <= 0.1
2831 return len(str((-1-adj)*23//10)) - 1
2832 op = _WorkRep(self)
2833 c, e = op.int, op.exp
2834 if adj == 0:
2835 # 1 < self < 10
2836 num = str(c-10**-e)
2837 den = str(c)
2838 return len(num) - len(den) - (num < den)
2839 # adj == -1, 0.1 <= self < 1
2840 return e + len(str(10**-e - c)) - 1
2841
2842
2843 def ln(self, context=None):
2844 """Returns the natural (base e) logarithm of self."""
2845
2846 if context is None:
2847 context = getcontext()
2848
2849 # ln(NaN) = NaN
2850 ans = self._check_nans(context=context)
2851 if ans:
2852 return ans
2853
2854 # ln(0.0) == -Infinity
2855 if not self:
2856 return negInf
2857
2858 # ln(Infinity) = Infinity
2859 if self._isinfinity() == 1:
2860 return Inf
2861
2862 # ln(1.0) == 0.0
2863 if self == Dec_p1:
2864 return Dec_0
2865
2866 # ln(negative) raises InvalidOperation
2867 if self._sign == 1:
2868 return context._raise_error(InvalidOperation,
2869 'ln of a negative value')
2870
2871 # result is irrational, so necessarily inexact
2872 op = _WorkRep(self)
2873 c, e = op.int, op.exp
2874 p = context.prec
2875
2876 # correctly rounded result: repeatedly increase precision by 3
2877 # until we get an unambiguously roundable result
2878 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2879 while True:
2880 coeff = _dlog(c, e, places)
2881 # assert len(str(abs(coeff)))-p >= 1
2882 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2883 break
2884 places += 3
2885 ans = Decimal((int(coeff<0), list(map(int, str(abs(coeff)))), -places))
2886
2887 context = context._shallow_copy()
2888 rounding = context._set_rounding(ROUND_HALF_EVEN)
2889 ans = ans._fix(context)
2890 context.rounding = rounding
2891 return ans
2892
2893 def _log10_exp_bound(self):
2894 """Compute a lower bound for the adjusted exponent of self.log10().
2895 In other words, find r such that self.log10() >= 10**r.
2896 Assumes that self is finite and positive and that self != 1.
2897 """
2898
2899 # For x >= 10 or x < 0.1 we only need a bound on the integer
2900 # part of log10(self), and this comes directly from the
2901 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2902 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2903 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2904
2905 adj = self._exp + len(self._int) - 1
2906 if adj >= 1:
2907 # self >= 10
2908 return len(str(adj))-1
2909 if adj <= -2:
2910 # self < 0.1
2911 return len(str(-1-adj))-1
2912 op = _WorkRep(self)
2913 c, e = op.int, op.exp
2914 if adj == 0:
2915 # 1 < self < 10
2916 num = str(c-10**-e)
2917 den = str(231*c)
2918 return len(num) - len(den) - (num < den) + 2
2919 # adj == -1, 0.1 <= self < 1
2920 num = str(10**-e-c)
2921 return len(num) + e - (num < "231") - 1
2922
2923 def log10(self, context=None):
2924 """Returns the base 10 logarithm of self."""
2925
2926 if context is None:
2927 context = getcontext()
2928
2929 # log10(NaN) = NaN
2930 ans = self._check_nans(context=context)
2931 if ans:
2932 return ans
2933
2934 # log10(0.0) == -Infinity
2935 if not self:
2936 return negInf
2937
2938 # log10(Infinity) = Infinity
2939 if self._isinfinity() == 1:
2940 return Inf
2941
2942 # log10(negative or -Infinity) raises InvalidOperation
2943 if self._sign == 1:
2944 return context._raise_error(InvalidOperation,
2945 'log10 of a negative value')
2946
2947 # log10(10**n) = n
2948 if self._int[0] == 1 and self._int[1:] == (0,)*(len(self._int) - 1):
2949 # answer may need rounding
2950 ans = Decimal(self._exp + len(self._int) - 1)
2951 else:
2952 # result is irrational, so necessarily inexact
2953 op = _WorkRep(self)
2954 c, e = op.int, op.exp
2955 p = context.prec
2956
2957 # correctly rounded result: repeatedly increase precision
2958 # until result is unambiguously roundable
2959 places = p-self._log10_exp_bound()+2
2960 while True:
2961 coeff = _dlog10(c, e, places)
2962 # assert len(str(abs(coeff)))-p >= 1
2963 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2964 break
2965 places += 3
2966 ans = Decimal((int(coeff<0), list(map(int, str(abs(coeff)))),
2967 -places))
2968
2969 context = context._shallow_copy()
2970 rounding = context._set_rounding(ROUND_HALF_EVEN)
2971 ans = ans._fix(context)
2972 context.rounding = rounding
2973 return ans
2974
2975 def logb(self, context=None):
2976 """ Returns the exponent of the magnitude of self's MSD.
2977
2978 The result is the integer which is the exponent of the magnitude
2979 of the most significant digit of self (as though it were truncated
2980 to a single digit while maintaining the value of that digit and
2981 without limiting the resulting exponent).
2982 """
2983 # logb(NaN) = NaN
2984 ans = self._check_nans(context=context)
2985 if ans:
2986 return ans
2987
2988 if context is None:
2989 context = getcontext()
2990
2991 # logb(+/-Inf) = +Inf
2992 if self._isinfinity():
2993 return Inf
2994
2995 # logb(0) = -Inf, DivisionByZero
2996 if not self:
2997 return context._raise_error(DivisionByZero, 'logb(0)', 1)
2998
2999 # otherwise, simply return the adjusted exponent of self, as a
3000 # Decimal. Note that no attempt is made to fit the result
3001 # into the current context.
3002 return Decimal(self.adjusted())
3003
3004 def _islogical(self):
3005 """Return True if self is a logical operand.
3006
3007 For being logical, it must be a finite numbers with a sign of 0,
3008 an exponent of 0, and a coefficient whose digits must all be
3009 either 0 or 1.
3010 """
3011 if self._sign != 0 or self._exp != 0:
3012 return False
3013 for dig in self._int:
3014 if dig not in (0, 1):
3015 return False
3016 return True
3017
3018 def _fill_logical(self, context, opa, opb):
3019 dif = context.prec - len(opa)
3020 if dif > 0:
3021 opa = (0,)*dif + opa
3022 elif dif < 0:
3023 opa = opa[-context.prec:]
3024 dif = context.prec - len(opb)
3025 if dif > 0:
3026 opb = (0,)*dif + opb
3027 elif dif < 0:
3028 opb = opb[-context.prec:]
3029 return opa, opb
3030
3031 def logical_and(self, other, context=None):
3032 """Applies an 'and' operation between self and other's digits."""
3033 if context is None:
3034 context = getcontext()
3035 if not self._islogical() or not other._islogical():
3036 return context._raise_error(InvalidOperation)
3037
3038 # fill to context.prec
3039 (opa, opb) = self._fill_logical(context, self._int, other._int)
3040
3041 # make the operation, and clean starting zeroes
3042 result = [a&b for a,b in zip(opa,opb)]
3043 for i,d in enumerate(result):
3044 if d == 1:
3045 break
3046 result = tuple(result[i:])
3047
3048 # if empty, we must have at least a zero
3049 if not result:
3050 result = (0,)
3051 return Decimal((0, result, 0))
3052
3053 def logical_invert(self, context=None):
3054 """Invert all its digits."""
3055 if context is None:
3056 context = getcontext()
3057 return self.logical_xor(Decimal((0,(1,)*context.prec,0)), context)
3058
3059 def logical_or(self, other, context=None):
3060 """Applies an 'or' operation between self and other's digits."""
3061 if context is None:
3062 context = getcontext()
3063 if not self._islogical() or not other._islogical():
3064 return context._raise_error(InvalidOperation)
3065
3066 # fill to context.prec
3067 (opa, opb) = self._fill_logical(context, self._int, other._int)
3068
3069 # make the operation, and clean starting zeroes
3070 result = [a|b for a,b in zip(opa,opb)]
3071 for i,d in enumerate(result):
3072 if d == 1:
3073 break
3074 result = tuple(result[i:])
3075
3076 # if empty, we must have at least a zero
3077 if not result:
3078 result = (0,)
3079 return Decimal((0, result, 0))
3080
3081 def logical_xor(self, other, context=None):
3082 """Applies an 'xor' operation between self and other's digits."""
3083 if context is None:
3084 context = getcontext()
3085 if not self._islogical() or not other._islogical():
3086 return context._raise_error(InvalidOperation)
3087
3088 # fill to context.prec
3089 (opa, opb) = self._fill_logical(context, self._int, other._int)
3090
3091 # make the operation, and clean starting zeroes
3092 result = [a^b for a,b in zip(opa,opb)]
3093 for i,d in enumerate(result):
3094 if d == 1:
3095 break
3096 result = tuple(result[i:])
3097
3098 # if empty, we must have at least a zero
3099 if not result:
3100 result = (0,)
3101 return Decimal((0, result, 0))
3102
3103 def max_mag(self, other, context=None):
3104 """Compares the values numerically with their sign ignored."""
3105 other = _convert_other(other, raiseit=True)
3106
3107 if context is None:
3108 context = getcontext()
3109
3110 if self._is_special or other._is_special:
3111 # If one operand is a quiet NaN and the other is number, then the
3112 # number is always returned
3113 sn = self._isnan()
3114 on = other._isnan()
3115 if sn or on:
3116 if on == 1 and sn != 2:
3117 return self._fix_nan(context)
3118 if sn == 1 and on != 2:
3119 return other._fix_nan(context)
3120 return self._check_nans(other, context)
3121
3122 c = self.copy_abs().__cmp__(other.copy_abs())
3123 if c == 0:
3124 c = self.compare_total(other)
3125
3126 if c == -1:
3127 ans = other
3128 else:
3129 ans = self
3130
3131 if context._rounding_decision == ALWAYS_ROUND:
3132 return ans._fix(context)
3133 return ans
3134
3135 def min_mag(self, other, context=None):
3136 """Compares the values numerically with their sign ignored."""
3137 other = _convert_other(other, raiseit=True)
3138
3139 if context is None:
3140 context = getcontext()
3141
3142 if self._is_special or other._is_special:
3143 # If one operand is a quiet NaN and the other is number, then the
3144 # number is always returned
3145 sn = self._isnan()
3146 on = other._isnan()
3147 if sn or on:
3148 if on == 1 and sn != 2:
3149 return self._fix_nan(context)
3150 if sn == 1 and on != 2:
3151 return other._fix_nan(context)
3152 return self._check_nans(other, context)
3153
3154 c = self.copy_abs().__cmp__(other.copy_abs())
3155 if c == 0:
3156 c = self.compare_total(other)
3157
3158 if c == -1:
3159 ans = self
3160 else:
3161 ans = other
3162
3163 if context._rounding_decision == ALWAYS_ROUND:
3164 return ans._fix(context)
3165 return ans
3166
3167 def next_minus(self, context=None):
3168 """Returns the largest representable number smaller than itself."""
3169 if context is None:
3170 context = getcontext()
3171
3172 ans = self._check_nans(context=context)
3173 if ans:
3174 return ans
3175
3176 if self._isinfinity() == -1:
3177 return negInf
3178 if self._isinfinity() == 1:
3179 return Decimal((0, (9,)*context.prec, context.Etop()))
3180
3181 context = context.copy()
3182 context._set_rounding(ROUND_FLOOR)
3183 context._ignore_all_flags()
3184 new_self = self._fix(context)
3185 if new_self != self:
3186 return new_self
3187 return self.__sub__(Decimal((0, (1,), context.Etiny()-1)), context)
3188
3189 def next_plus(self, context=None):
3190 """Returns the smallest representable number larger than itself."""
3191 if context is None:
3192 context = getcontext()
3193
3194 ans = self._check_nans(context=context)
3195 if ans:
3196 return ans
3197
3198 if self._isinfinity() == 1:
3199 return Inf
3200 if self._isinfinity() == -1:
3201 return Decimal((1, (9,)*context.prec, context.Etop()))
3202
3203 context = context.copy()
3204 context._set_rounding(ROUND_CEILING)
3205 context._ignore_all_flags()
3206 new_self = self._fix(context)
3207 if new_self != self:
3208 return new_self
3209 return self.__add__(Decimal((0, (1,), context.Etiny()-1)), context)
3210
3211 def next_toward(self, other, context=None):
3212 """Returns the number closest to self, in the direction towards other.
3213
3214 The result is the closest representable number to self
3215 (excluding self) that is in the direction towards other,
3216 unless both have the same value. If the two operands are
3217 numerically equal, then the result is a copy of self with the
3218 sign set to be the same as the sign of other.
3219 """
3220 other = _convert_other(other, raiseit=True)
3221
3222 if context is None:
3223 context = getcontext()
3224
3225 ans = self._check_nans(other, context)
3226 if ans:
3227 return ans
3228
3229 comparison = self.__cmp__(other)
3230 if comparison == 0:
3231 return Decimal((other._sign, self._int, self._exp))
3232
3233 if comparison == -1:
3234 ans = self.next_plus(context)
3235 else: # comparison == 1
3236 ans = self.next_minus(context)
3237
3238 # decide which flags to raise using value of ans
3239 if ans._isinfinity():
3240 context._raise_error(Overflow,
3241 'Infinite result from next_toward',
3242 ans._sign)
3243 context._raise_error(Rounded)
3244 context._raise_error(Inexact)
3245 elif ans.adjusted() < context.Emin:
3246 context._raise_error(Underflow)
3247 context._raise_error(Subnormal)
3248 context._raise_error(Rounded)
3249 context._raise_error(Inexact)
3250 # if precision == 1 then we don't raise Clamped for a
3251 # result 0E-Etiny.
3252 if not ans:
3253 context._raise_error(Clamped)
3254
3255 return ans
3256
3257 def number_class(self, context=None):
3258 """Returns an indication of the class of self.
3259
3260 The class is one of the following strings:
3261 -sNaN
3262 -NaN
3263 -Infinity
3264 -Normal
3265 -Subnormal
3266 -Zero
3267 +Zero
3268 +Subnormal
3269 +Normal
3270 +Infinity
3271 """
3272 if self.is_snan():
3273 return "sNaN"
3274 if self.is_qnan():
3275 return "NaN"
3276 inf = self._isinfinity()
3277 if inf == 1:
3278 return "+Infinity"
3279 if inf == -1:
3280 return "-Infinity"
3281 if self.is_zero():
3282 if self._sign:
3283 return "-Zero"
3284 else:
3285 return "+Zero"
3286 if context is None:
3287 context = getcontext()
3288 if self.is_subnormal(context=context):
3289 if self._sign:
3290 return "-Subnormal"
3291 else:
3292 return "+Subnormal"
3293 # just a normal, regular, boring number, :)
3294 if self._sign:
3295 return "-Normal"
3296 else:
3297 return "+Normal"
3298
3299 def radix(self):
3300 """Just returns 10, as this is Decimal, :)"""
3301 return Decimal(10)
3302
3303 def rotate(self, other, context=None):
3304 """Returns a rotated copy of self, value-of-other times."""
3305 if context is None:
3306 context = getcontext()
3307
3308 ans = self._check_nans(other, context)
3309 if ans:
3310 return ans
3311
3312 if other._exp != 0:
3313 return context._raise_error(InvalidOperation)
3314 if not (-context.prec <= int(other) <= context.prec):
3315 return context._raise_error(InvalidOperation)
3316
3317 if self._isinfinity():
3318 return Decimal(self)
3319
3320 # get values, pad if necessary
3321 torot = int(other)
3322 rotdig = self._int
3323 topad = context.prec - len(rotdig)
3324 if topad:
3325 rotdig = ((0,)*topad) + rotdig
3326
3327 # let's rotate!
3328 rotated = rotdig[torot:] + rotdig[:torot]
3329
3330 # clean starting zeroes
3331 for i,d in enumerate(rotated):
3332 if d != 0:
3333 break
3334 rotated = rotated[i:]
3335
3336 return Decimal((self._sign, rotated, self._exp))
3337
3338
3339 def scaleb (self, other, context=None):
3340 """Returns self operand after adding the second value to its exp."""
3341 if context is None:
3342 context = getcontext()
3343
3344 ans = self._check_nans(other, context)
3345 if ans:
3346 return ans
3347
3348 if other._exp != 0:
3349 return context._raise_error(InvalidOperation)
3350 liminf = -2 * (context.Emax + context.prec)
3351 limsup = 2 * (context.Emax + context.prec)
3352 if not (liminf <= int(other) <= limsup):
3353 return context._raise_error(InvalidOperation)
3354
3355 if self._isinfinity():
3356 return Decimal(self)
3357
3358 d = Decimal((self._sign, self._int, self._exp + int(other)))
3359 d = d._fix(context)
3360 return d
3361
3362 def shift(self, other, context=None):
3363 """Returns a shifted copy of self, value-of-other times."""
3364 if context is None:
3365 context = getcontext()
3366
3367 ans = self._check_nans(other, context)
3368 if ans:
3369 return ans
3370
3371 if other._exp != 0:
3372 return context._raise_error(InvalidOperation)
3373 if not (-context.prec <= int(other) <= context.prec):
3374 return context._raise_error(InvalidOperation)
3375
3376 if self._isinfinity():
3377 return Decimal(self)
3378
3379 # get values, pad if necessary
3380 torot = int(other)
3381 if not torot:
3382 return Decimal(self)
3383 rotdig = self._int
3384 topad = context.prec - len(rotdig)
3385 if topad:
3386 rotdig = ((0,)*topad) + rotdig
3387
3388 # let's shift!
3389 if torot < 0:
3390 rotated = rotdig[:torot]
3391 else:
3392 rotated = (rotdig + ((0,) * torot))
3393 rotated = rotated[-context.prec:]
3394
3395 # clean starting zeroes
3396 if rotated:
3397 for i,d in enumerate(rotated):
3398 if d != 0:
3399 break
3400 rotated = rotated[i:]
3401 else:
3402 rotated = (0,)
3403
3404 return Decimal((self._sign, rotated, self._exp))
3405
3406
Guido van Rossumd8faa362007-04-27 19:54:29 +00003407 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003408 def __reduce__(self):
3409 return (self.__class__, (str(self),))
3410
3411 def __copy__(self):
3412 if type(self) == Decimal:
3413 return self # I'm immutable; therefore I am my own clone
3414 return self.__class__(str(self))
3415
3416 def __deepcopy__(self, memo):
3417 if type(self) == Decimal:
3418 return self # My components are also immutable
3419 return self.__class__(str(self))
3420
Guido van Rossumd8faa362007-04-27 19:54:29 +00003421##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003422
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003423
3424# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003425rounding_functions = [name for name in Decimal.__dict__.keys()
3426 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003427for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003428 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003429 globalname = name[1:].upper()
3430 val = globals()[globalname]
3431 Decimal._pick_rounding_function[val] = name
3432
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003433del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003434
Thomas Wouters89f507f2006-12-13 04:49:30 +00003435class _ContextManager(object):
3436 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003437
Thomas Wouters89f507f2006-12-13 04:49:30 +00003438 Sets a copy of the supplied context in __enter__() and restores
3439 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003440 """
3441 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003442 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003443 def __enter__(self):
3444 self.saved_context = getcontext()
3445 setcontext(self.new_context)
3446 return self.new_context
3447 def __exit__(self, t, v, tb):
3448 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003449
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003450class Context(object):
3451 """Contains the context for a Decimal instance.
3452
3453 Contains:
3454 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003455 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003456 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003457 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003458 raised when it is caused. Otherwise, a value is
3459 substituted in.
3460 flags - When an exception is caused, flags[exception] is incremented.
3461 (Whether or not the trap_enabler is set)
3462 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003463 Emin - Minimum exponent
3464 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003465 capitals - If 1, 1*10^1 is printed as 1E+1.
3466 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003467 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003468 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003469
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003470 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003471 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003472 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003473 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003474 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003475 _ignored_flags=None):
3476 if flags is None:
3477 flags = []
3478 if _ignored_flags is None:
3479 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003480 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003481 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003482 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003483 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003484 for name, val in locals().items():
3485 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003486 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003487 else:
3488 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003489 del self.self
3490
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003491 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003492 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003493 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003494 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3495 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3496 % vars(self))
3497 names = [f.__name__ for f, v in self.flags.items() if v]
3498 s.append('flags=[' + ', '.join(names) + ']')
3499 names = [t.__name__ for t, v in self.traps.items() if v]
3500 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003501 return ', '.join(s) + ')'
3502
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003503 def clear_flags(self):
3504 """Reset all flags to zero"""
3505 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003506 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003507
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003508 def _shallow_copy(self):
3509 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003510 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003511 self._rounding_decision, self.Emin, self.Emax,
3512 self.capitals, self._clamp, self._ignored_flags)
3513 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003514
3515 def copy(self):
3516 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003517 nc = Context(self.prec, self.rounding, self.traps.copy(),
3518 self.flags.copy(), self._rounding_decision, self.Emin,
3519 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003520 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003521 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003522
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003523 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003524 """Handles an error
3525
3526 If the flag is in _ignored_flags, returns the default response.
3527 Otherwise, it increments the flag, then, if the corresponding
3528 trap_enabler is set, it reaises the exception. Otherwise, it returns
3529 the default value after incrementing the flag.
3530 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003531 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003532 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003533 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003534 return error().handle(self, *args)
3535
3536 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003537 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003538 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003539 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003540
3541 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003542 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003543 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003544
3545 def _ignore_all_flags(self):
3546 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003547 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003548
3549 def _ignore_flags(self, *flags):
3550 """Ignore the flags, if they are raised"""
3551 # Do not mutate-- This way, copies of a context leave the original
3552 # alone.
3553 self._ignored_flags = (self._ignored_flags + list(flags))
3554 return list(flags)
3555
3556 def _regard_flags(self, *flags):
3557 """Stop ignoring the flags, if they are raised"""
3558 if flags and isinstance(flags[0], (tuple,list)):
3559 flags = flags[0]
3560 for flag in flags:
3561 self._ignored_flags.remove(flag)
3562
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003563 def __hash__(self):
3564 """A Context cannot be hashed."""
3565 # We inherit object.__hash__, so we must deny this explicitly
Guido van Rossumd8faa362007-04-27 19:54:29 +00003566 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003567
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003568 def Etiny(self):
3569 """Returns Etiny (= Emin - prec + 1)"""
3570 return int(self.Emin - self.prec + 1)
3571
3572 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003573 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003574 return int(self.Emax - self.prec + 1)
3575
3576 def _set_rounding_decision(self, type):
3577 """Sets the rounding decision.
3578
3579 Sets the rounding decision, and returns the current (previous)
3580 rounding decision. Often used like:
3581
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003582 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003583 # That so you don't change the calling context
3584 # if an error occurs in the middle (say DivisionImpossible is raised).
3585
3586 rounding = context._set_rounding_decision(NEVER_ROUND)
3587 instance = instance / Decimal(2)
3588 context._set_rounding_decision(rounding)
3589
3590 This will make it not round for that operation.
3591 """
3592
3593 rounding = self._rounding_decision
3594 self._rounding_decision = type
3595 return rounding
3596
3597 def _set_rounding(self, type):
3598 """Sets the rounding type.
3599
3600 Sets the rounding type, and returns the current (previous)
3601 rounding type. Often used like:
3602
3603 context = context.copy()
3604 # so you don't change the calling context
3605 # if an error occurs in the middle.
3606 rounding = context._set_rounding(ROUND_UP)
3607 val = self.__sub__(other, context=context)
3608 context._set_rounding(rounding)
3609
3610 This will make it round up for that operation.
3611 """
3612 rounding = self.rounding
3613 self.rounding= type
3614 return rounding
3615
Raymond Hettingerfed52962004-07-14 15:41:57 +00003616 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003617 """Creates a new Decimal instance but using self as context."""
3618 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003619 if d._isnan() and len(d._int) > self.prec - self._clamp:
3620 return self._raise_error(ConversionSyntax,
3621 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003622 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003623
Guido van Rossumd8faa362007-04-27 19:54:29 +00003624 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003625 def abs(self, a):
3626 """Returns the absolute value of the operand.
3627
3628 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003629 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003630 the plus operation on the operand.
3631
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003632 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003633 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003634 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003635 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003636 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003637 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003638 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003639 Decimal("101.5")
3640 """
3641 return a.__abs__(context=self)
3642
3643 def add(self, a, b):
3644 """Return the sum of the two operands.
3645
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003646 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003647 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003648 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003649 Decimal("1.02E+4")
3650 """
3651 return a.__add__(b, context=self)
3652
3653 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003654 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003655
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003656 def canonical(self, a):
3657 """Returns the same Decimal object.
3658
3659 As we do not have different encodings for the same number, the
3660 received object already is in its canonical form.
3661
3662 >>> ExtendedContext.canonical(Decimal('2.50'))
3663 Decimal("2.50")
3664 """
3665 return a.canonical(context=self)
3666
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003667 def compare(self, a, b):
3668 """Compares values numerically.
3669
3670 If the signs of the operands differ, a value representing each operand
3671 ('-1' if the operand is less than zero, '0' if the operand is zero or
3672 negative zero, or '1' if the operand is greater than zero) is used in
3673 place of that operand for the comparison instead of the actual
3674 operand.
3675
3676 The comparison is then effected by subtracting the second operand from
3677 the first and then returning a value according to the result of the
3678 subtraction: '-1' if the result is less than zero, '0' if the result is
3679 zero or negative zero, or '1' if the result is greater than zero.
3680
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003681 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003682 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003683 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003684 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003685 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003686 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003687 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003688 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003689 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003690 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003691 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003692 Decimal("-1")
3693 """
3694 return a.compare(b, context=self)
3695
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003696 def compare_signal(self, a, b):
3697 """Compares the values of the two operands numerically.
3698
3699 It's pretty much like compare(), but all NaNs signal, with signaling
3700 NaNs taking precedence over quiet NaNs.
3701
3702 >>> c = ExtendedContext
3703 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3704 Decimal("-1")
3705 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3706 Decimal("0")
3707 >>> c.flags[InvalidOperation] = 0
3708 >>> print(c.flags[InvalidOperation])
3709 0
3710 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3711 Decimal("NaN")
3712 >>> print(c.flags[InvalidOperation])
3713 1
3714 >>> c.flags[InvalidOperation] = 0
3715 >>> print(c.flags[InvalidOperation])
3716 0
3717 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3718 Decimal("NaN")
3719 >>> print(c.flags[InvalidOperation])
3720 1
3721 """
3722 return a.compare_signal(b, context=self)
3723
3724 def compare_total(self, a, b):
3725 """Compares two operands using their abstract representation.
3726
3727 This is not like the standard compare, which use their numerical
3728 value. Note that a total ordering is defined for all possible abstract
3729 representations.
3730
3731 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3732 Decimal("-1")
3733 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3734 Decimal("-1")
3735 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3736 Decimal("-1")
3737 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3738 Decimal("0")
3739 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3740 Decimal("1")
3741 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3742 Decimal("-1")
3743 """
3744 return a.compare_total(b)
3745
3746 def compare_total_mag(self, a, b):
3747 """Compares two operands using their abstract representation ignoring sign.
3748
3749 Like compare_total, but with operand's sign ignored and assumed to be 0.
3750 """
3751 return a.compare_total_mag(b)
3752
3753 def copy_abs(self, a):
3754 """Returns a copy of the operand with the sign set to 0.
3755
3756 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3757 Decimal("2.1")
3758 >>> ExtendedContext.copy_abs(Decimal('-100'))
3759 Decimal("100")
3760 """
3761 return a.copy_abs()
3762
3763 def copy_decimal(self, a):
3764 """Returns a copy of the decimal objet.
3765
3766 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3767 Decimal("2.1")
3768 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3769 Decimal("-1.00")
3770 """
3771 return Decimal(a)
3772
3773 def copy_negate(self, a):
3774 """Returns a copy of the operand with the sign inverted.
3775
3776 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3777 Decimal("-101.5")
3778 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3779 Decimal("101.5")
3780 """
3781 return a.copy_negate()
3782
3783 def copy_sign(self, a, b):
3784 """Copies the second operand's sign to the first one.
3785
3786 In detail, it returns a copy of the first operand with the sign
3787 equal to the sign of the second operand.
3788
3789 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3790 Decimal("1.50")
3791 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3792 Decimal("1.50")
3793 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3794 Decimal("-1.50")
3795 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3796 Decimal("-1.50")
3797 """
3798 return a.copy_sign(b)
3799
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003800 def divide(self, a, b):
3801 """Decimal division in a specified context.
3802
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003803 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003804 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003805 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003806 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003807 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003808 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003809 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003810 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003811 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003812 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003813 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003814 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003815 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003816 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003817 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003818 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003819 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003820 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003821 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003822 Decimal("1.20E+6")
3823 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003824 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003825
3826 def divide_int(self, a, b):
3827 """Divides two numbers and returns the integer part of the result.
3828
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003829 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003830 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003831 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003832 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003833 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003834 Decimal("3")
3835 """
3836 return a.__floordiv__(b, context=self)
3837
3838 def divmod(self, a, b):
3839 return a.__divmod__(b, context=self)
3840
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003841 def exp(self, a):
3842 """Returns e ** a.
3843
3844 >>> c = ExtendedContext.copy()
3845 >>> c.Emin = -999
3846 >>> c.Emax = 999
3847 >>> c.exp(Decimal('-Infinity'))
3848 Decimal("0")
3849 >>> c.exp(Decimal('-1'))
3850 Decimal("0.367879441")
3851 >>> c.exp(Decimal('0'))
3852 Decimal("1")
3853 >>> c.exp(Decimal('1'))
3854 Decimal("2.71828183")
3855 >>> c.exp(Decimal('0.693147181'))
3856 Decimal("2.00000000")
3857 >>> c.exp(Decimal('+Infinity'))
3858 Decimal("Infinity")
3859 """
3860 return a.exp(context=self)
3861
3862 def fma(self, a, b, c):
3863 """Returns a multiplied by b, plus c.
3864
3865 The first two operands are multiplied together, using multiply,
3866 the third operand is then added to the result of that
3867 multiplication, using add, all with only one final rounding.
3868
3869 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3870 Decimal("22")
3871 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3872 Decimal("-8")
3873 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3874 Decimal("1.38435736E+12")
3875 """
3876 return a.fma(b, c, context=self)
3877
3878 def is_canonical(self, a):
3879 """Returns 1 if the operand is canonical; otherwise returns 0.
3880
3881 >>> ExtendedContext.is_canonical(Decimal('2.50'))
3882 Decimal("1")
3883 """
3884 return Dec_p1
3885
3886 def is_finite(self, a):
3887 """Returns 1 if the operand is finite, otherwise returns 0.
3888
3889 For it to be finite, it must be neither infinite nor a NaN.
3890
3891 >>> ExtendedContext.is_finite(Decimal('2.50'))
3892 Decimal("1")
3893 >>> ExtendedContext.is_finite(Decimal('-0.3'))
3894 Decimal("1")
3895 >>> ExtendedContext.is_finite(Decimal('0'))
3896 Decimal("1")
3897 >>> ExtendedContext.is_finite(Decimal('Inf'))
3898 Decimal("0")
3899 >>> ExtendedContext.is_finite(Decimal('NaN'))
3900 Decimal("0")
3901 """
3902 return a.is_finite()
3903
3904 def is_infinite(self, a):
3905 """Returns 1 if the operand is an Infinite, otherwise returns 0.
3906
3907 >>> ExtendedContext.is_infinite(Decimal('2.50'))
3908 Decimal("0")
3909 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
3910 Decimal("1")
3911 >>> ExtendedContext.is_infinite(Decimal('NaN'))
3912 Decimal("0")
3913 """
3914 return a.is_infinite()
3915
3916 def is_nan(self, a):
3917 """Returns 1 if the operand is qNaN or sNaN, otherwise returns 0.
3918
3919 >>> ExtendedContext.is_nan(Decimal('2.50'))
3920 Decimal("0")
3921 >>> ExtendedContext.is_nan(Decimal('NaN'))
3922 Decimal("1")
3923 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
3924 Decimal("1")
3925 """
3926 return a.is_nan()
3927
3928 def is_normal(self, a):
3929 """Returns 1 if the operand is a normal number, otherwise returns 0.
3930
3931 >>> c = ExtendedContext.copy()
3932 >>> c.Emin = -999
3933 >>> c.Emax = 999
3934 >>> c.is_normal(Decimal('2.50'))
3935 Decimal("1")
3936 >>> c.is_normal(Decimal('0.1E-999'))
3937 Decimal("0")
3938 >>> c.is_normal(Decimal('0.00'))
3939 Decimal("0")
3940 >>> c.is_normal(Decimal('-Inf'))
3941 Decimal("0")
3942 >>> c.is_normal(Decimal('NaN'))
3943 Decimal("0")
3944 """
3945 return a.is_normal(context=self)
3946
3947 def is_qnan(self, a):
3948 """Returns 1 if the operand is a quiet NaN, otherwise returns 0.
3949
3950 >>> ExtendedContext.is_qnan(Decimal('2.50'))
3951 Decimal("0")
3952 >>> ExtendedContext.is_qnan(Decimal('NaN'))
3953 Decimal("1")
3954 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
3955 Decimal("0")
3956 """
3957 return a.is_qnan()
3958
3959 def is_signed(self, a):
3960 """Returns 1 if the operand is negative, otherwise returns 0.
3961
3962 >>> ExtendedContext.is_signed(Decimal('2.50'))
3963 Decimal("0")
3964 >>> ExtendedContext.is_signed(Decimal('-12'))
3965 Decimal("1")
3966 >>> ExtendedContext.is_signed(Decimal('-0'))
3967 Decimal("1")
3968 """
3969 return a.is_signed()
3970
3971 def is_snan(self, a):
3972 """Returns 1 if the operand is a signaling NaN, otherwise returns 0.
3973
3974 >>> ExtendedContext.is_snan(Decimal('2.50'))
3975 Decimal("0")
3976 >>> ExtendedContext.is_snan(Decimal('NaN'))
3977 Decimal("0")
3978 >>> ExtendedContext.is_snan(Decimal('sNaN'))
3979 Decimal("1")
3980 """
3981 return a.is_snan()
3982
3983 def is_subnormal(self, a):
3984 """Returns 1 if the operand is subnormal, otherwise returns 0.
3985
3986 >>> c = ExtendedContext.copy()
3987 >>> c.Emin = -999
3988 >>> c.Emax = 999
3989 >>> c.is_subnormal(Decimal('2.50'))
3990 Decimal("0")
3991 >>> c.is_subnormal(Decimal('0.1E-999'))
3992 Decimal("1")
3993 >>> c.is_subnormal(Decimal('0.00'))
3994 Decimal("0")
3995 >>> c.is_subnormal(Decimal('-Inf'))
3996 Decimal("0")
3997 >>> c.is_subnormal(Decimal('NaN'))
3998 Decimal("0")
3999 """
4000 return a.is_subnormal(context=self)
4001
4002 def is_zero(self, a):
4003 """Returns 1 if the operand is a zero, otherwise returns 0.
4004
4005 >>> ExtendedContext.is_zero(Decimal('0'))
4006 Decimal("1")
4007 >>> ExtendedContext.is_zero(Decimal('2.50'))
4008 Decimal("0")
4009 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
4010 Decimal("1")
4011 """
4012 return a.is_zero()
4013
4014 def ln(self, a):
4015 """Returns the natural (base e) logarithm of the operand.
4016
4017 >>> c = ExtendedContext.copy()
4018 >>> c.Emin = -999
4019 >>> c.Emax = 999
4020 >>> c.ln(Decimal('0'))
4021 Decimal("-Infinity")
4022 >>> c.ln(Decimal('1.000'))
4023 Decimal("0")
4024 >>> c.ln(Decimal('2.71828183'))
4025 Decimal("1.00000000")
4026 >>> c.ln(Decimal('10'))
4027 Decimal("2.30258509")
4028 >>> c.ln(Decimal('+Infinity'))
4029 Decimal("Infinity")
4030 """
4031 return a.ln(context=self)
4032
4033 def log10(self, a):
4034 """Returns the base 10 logarithm of the operand.
4035
4036 >>> c = ExtendedContext.copy()
4037 >>> c.Emin = -999
4038 >>> c.Emax = 999
4039 >>> c.log10(Decimal('0'))
4040 Decimal("-Infinity")
4041 >>> c.log10(Decimal('0.001'))
4042 Decimal("-3")
4043 >>> c.log10(Decimal('1.000'))
4044 Decimal("0")
4045 >>> c.log10(Decimal('2'))
4046 Decimal("0.301029996")
4047 >>> c.log10(Decimal('10'))
4048 Decimal("1")
4049 >>> c.log10(Decimal('70'))
4050 Decimal("1.84509804")
4051 >>> c.log10(Decimal('+Infinity'))
4052 Decimal("Infinity")
4053 """
4054 return a.log10(context=self)
4055
4056 def logb(self, a):
4057 """ Returns the exponent of the magnitude of the operand's MSD.
4058
4059 The result is the integer which is the exponent of the magnitude
4060 of the most significant digit of the operand (as though the
4061 operand were truncated to a single digit while maintaining the
4062 value of that digit and without limiting the resulting exponent).
4063
4064 >>> ExtendedContext.logb(Decimal('250'))
4065 Decimal("2")
4066 >>> ExtendedContext.logb(Decimal('2.50'))
4067 Decimal("0")
4068 >>> ExtendedContext.logb(Decimal('0.03'))
4069 Decimal("-2")
4070 >>> ExtendedContext.logb(Decimal('0'))
4071 Decimal("-Infinity")
4072 """
4073 return a.logb(context=self)
4074
4075 def logical_and(self, a, b):
4076 """Applies the logical operation 'and' between each operand's digits.
4077
4078 The operands must be both logical numbers.
4079
4080 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4081 Decimal("0")
4082 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4083 Decimal("0")
4084 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4085 Decimal("0")
4086 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4087 Decimal("1")
4088 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4089 Decimal("1000")
4090 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4091 Decimal("10")
4092 """
4093 return a.logical_and(b, context=self)
4094
4095 def logical_invert(self, a):
4096 """Invert all the digits in the operand.
4097
4098 The operand must be a logical number.
4099
4100 >>> ExtendedContext.logical_invert(Decimal('0'))
4101 Decimal("111111111")
4102 >>> ExtendedContext.logical_invert(Decimal('1'))
4103 Decimal("111111110")
4104 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4105 Decimal("0")
4106 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4107 Decimal("10101010")
4108 """
4109 return a.logical_invert(context=self)
4110
4111 def logical_or(self, a, b):
4112 """Applies the logical operation 'or' between each operand's digits.
4113
4114 The operands must be both logical numbers.
4115
4116 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4117 Decimal("0")
4118 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4119 Decimal("1")
4120 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4121 Decimal("1")
4122 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4123 Decimal("1")
4124 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4125 Decimal("1110")
4126 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4127 Decimal("1110")
4128 """
4129 return a.logical_or(b, context=self)
4130
4131 def logical_xor(self, a, b):
4132 """Applies the logical operation 'xor' between each operand's digits.
4133
4134 The operands must be both logical numbers.
4135
4136 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4137 Decimal("0")
4138 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4139 Decimal("1")
4140 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4141 Decimal("1")
4142 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4143 Decimal("0")
4144 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4145 Decimal("110")
4146 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4147 Decimal("1101")
4148 """
4149 return a.logical_xor(b, context=self)
4150
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004151 def max(self, a,b):
4152 """max compares two values numerically and returns the maximum.
4153
4154 If either operand is a NaN then the general rules apply.
4155 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004156 operation. If they are numerically equal then the left-hand operand
4157 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004158 infinity) of the two operands is chosen as the result.
4159
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004160 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004161 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004162 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004163 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004164 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004165 Decimal("1")
4166 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4167 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004168 """
4169 return a.max(b, context=self)
4170
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004171 def max_mag(self, a, b):
4172 """Compares the values numerically with their sign ignored."""
4173 return a.max_mag(b, context=self)
4174
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004175 def min(self, a,b):
4176 """min compares two values numerically and returns the minimum.
4177
4178 If either operand is a NaN then the general rules apply.
4179 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004180 operation. If they are numerically equal then the left-hand operand
4181 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004182 infinity) of the two operands is chosen as the result.
4183
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004184 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004185 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004186 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004187 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004188 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004189 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004190 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4191 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004192 """
4193 return a.min(b, context=self)
4194
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004195 def min_mag(self, a, b):
4196 """Compares the values numerically with their sign ignored."""
4197 return a.min_mag(b, context=self)
4198
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004199 def minus(self, a):
4200 """Minus corresponds to unary prefix minus in Python.
4201
4202 The operation is evaluated using the same rules as subtract; the
4203 operation minus(a) is calculated as subtract('0', a) where the '0'
4204 has the same exponent as the operand.
4205
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004206 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004207 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004208 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004209 Decimal("1.3")
4210 """
4211 return a.__neg__(context=self)
4212
4213 def multiply(self, a, b):
4214 """multiply multiplies two operands.
4215
4216 If either operand is a special value then the general rules apply.
4217 Otherwise, the operands are multiplied together ('long multiplication'),
4218 resulting in a number which may be as long as the sum of the lengths
4219 of the two operands.
4220
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004221 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004222 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004223 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004224 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004225 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004226 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004227 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004228 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004229 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004230 Decimal("4.28135971E+11")
4231 """
4232 return a.__mul__(b, context=self)
4233
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004234 def next_minus(self, a):
4235 """Returns the largest representable number smaller than a.
4236
4237 >>> c = ExtendedContext.copy()
4238 >>> c.Emin = -999
4239 >>> c.Emax = 999
4240 >>> ExtendedContext.next_minus(Decimal('1'))
4241 Decimal("0.999999999")
4242 >>> c.next_minus(Decimal('1E-1007'))
4243 Decimal("0E-1007")
4244 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4245 Decimal("-1.00000004")
4246 >>> c.next_minus(Decimal('Infinity'))
4247 Decimal("9.99999999E+999")
4248 """
4249 return a.next_minus(context=self)
4250
4251 def next_plus(self, a):
4252 """Returns the smallest representable number larger than a.
4253
4254 >>> c = ExtendedContext.copy()
4255 >>> c.Emin = -999
4256 >>> c.Emax = 999
4257 >>> ExtendedContext.next_plus(Decimal('1'))
4258 Decimal("1.00000001")
4259 >>> c.next_plus(Decimal('-1E-1007'))
4260 Decimal("-0E-1007")
4261 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4262 Decimal("-1.00000002")
4263 >>> c.next_plus(Decimal('-Infinity'))
4264 Decimal("-9.99999999E+999")
4265 """
4266 return a.next_plus(context=self)
4267
4268 def next_toward(self, a, b):
4269 """Returns the number closest to a, in direction towards b.
4270
4271 The result is the closest representable number from the first
4272 operand (but not the first operand) that is in the direction
4273 towards the second operand, unless the operands have the same
4274 value.
4275
4276 >>> c = ExtendedContext.copy()
4277 >>> c.Emin = -999
4278 >>> c.Emax = 999
4279 >>> c.next_toward(Decimal('1'), Decimal('2'))
4280 Decimal("1.00000001")
4281 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4282 Decimal("-0E-1007")
4283 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4284 Decimal("-1.00000002")
4285 >>> c.next_toward(Decimal('1'), Decimal('0'))
4286 Decimal("0.999999999")
4287 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4288 Decimal("0E-1007")
4289 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4290 Decimal("-1.00000004")
4291 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4292 Decimal("-0.00")
4293 """
4294 return a.next_toward(b, context=self)
4295
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004296 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004297 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004298
4299 Essentially a plus operation with all trailing zeros removed from the
4300 result.
4301
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004302 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004303 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004304 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004305 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004306 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004307 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004308 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004309 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004310 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004311 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004312 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004313 Decimal("0")
4314 """
4315 return a.normalize(context=self)
4316
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004317 def number_class(self, a):
4318 """Returns an indication of the class of the operand.
4319
4320 The class is one of the following strings:
4321 -sNaN
4322 -NaN
4323 -Infinity
4324 -Normal
4325 -Subnormal
4326 -Zero
4327 +Zero
4328 +Subnormal
4329 +Normal
4330 +Infinity
4331
4332 >>> c = Context(ExtendedContext)
4333 >>> c.Emin = -999
4334 >>> c.Emax = 999
4335 >>> c.number_class(Decimal('Infinity'))
4336 '+Infinity'
4337 >>> c.number_class(Decimal('1E-10'))
4338 '+Normal'
4339 >>> c.number_class(Decimal('2.50'))
4340 '+Normal'
4341 >>> c.number_class(Decimal('0.1E-999'))
4342 '+Subnormal'
4343 >>> c.number_class(Decimal('0'))
4344 '+Zero'
4345 >>> c.number_class(Decimal('-0'))
4346 '-Zero'
4347 >>> c.number_class(Decimal('-0.1E-999'))
4348 '-Subnormal'
4349 >>> c.number_class(Decimal('-1E-10'))
4350 '-Normal'
4351 >>> c.number_class(Decimal('-2.50'))
4352 '-Normal'
4353 >>> c.number_class(Decimal('-Infinity'))
4354 '-Infinity'
4355 >>> c.number_class(Decimal('NaN'))
4356 'NaN'
4357 >>> c.number_class(Decimal('-NaN'))
4358 'NaN'
4359 >>> c.number_class(Decimal('sNaN'))
4360 'sNaN'
4361 """
4362 return a.number_class(context=self)
4363
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004364 def plus(self, a):
4365 """Plus corresponds to unary prefix plus in Python.
4366
4367 The operation is evaluated using the same rules as add; the
4368 operation plus(a) is calculated as add('0', a) where the '0'
4369 has the same exponent as the operand.
4370
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004371 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004372 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004373 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004374 Decimal("-1.3")
4375 """
4376 return a.__pos__(context=self)
4377
4378 def power(self, a, b, modulo=None):
4379 """Raises a to the power of b, to modulo if given.
4380
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004381 With two arguments, compute a**b. If a is negative then b
4382 must be integral. The result will be inexact unless b is
4383 integral and the result is finite and can be expressed exactly
4384 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004385
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004386 With three arguments, compute (a**b) % modulo. For the
4387 three argument form, the following restrictions on the
4388 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004389
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004390 - all three arguments must be integral
4391 - b must be nonnegative
4392 - at least one of a or b must be nonzero
4393 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004394
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004395 The result of pow(a, b, modulo) is identical to the result
4396 that would be obtained by computing (a**b) % modulo with
4397 unbounded precision, but is computed more efficiently. It is
4398 always exact.
4399
4400 >>> c = ExtendedContext.copy()
4401 >>> c.Emin = -999
4402 >>> c.Emax = 999
4403 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004404 Decimal("8")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004405 >>> c.power(Decimal('-2'), Decimal('3'))
4406 Decimal("-8")
4407 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004408 Decimal("0.125")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004409 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004410 Decimal("69.7575744")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004411 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4412 Decimal("2.00000000")
4413 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004414 Decimal("0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004415 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004416 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004417 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004418 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004419 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004420 Decimal("-0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004421 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004422 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004423 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004424 Decimal("-Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004425 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004426 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004427 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004428 Decimal("NaN")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004429
4430 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4431 Decimal("11")
4432 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4433 Decimal("-11")
4434 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4435 Decimal("1")
4436 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4437 Decimal("11")
4438 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4439 Decimal("11729830")
4440 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4441 Decimal("-0")
4442 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4443 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004444 """
4445 return a.__pow__(b, modulo, context=self)
4446
4447 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004448 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004449
4450 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004451 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004452 exponent is being increased), multiplied by a positive power of ten (if
4453 the exponent is being decreased), or is unchanged (if the exponent is
4454 already equal to that of the right-hand operand).
4455
4456 Unlike other operations, if the length of the coefficient after the
4457 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004458 operation condition is raised. This guarantees that, unless there is
4459 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004460 equal to that of the right-hand operand.
4461
4462 Also unlike other operations, quantize will never raise Underflow, even
4463 if the result is subnormal and inexact.
4464
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004465 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004466 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004467 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004468 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004469 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004470 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004471 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004472 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004473 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004474 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004475 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004476 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004477 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004478 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004479 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004480 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004481 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004482 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004483 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004484 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004485 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004486 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004487 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004488 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004489 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004490 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004491 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004492 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004493 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004494 Decimal("2E+2")
4495 """
4496 return a.quantize(b, context=self)
4497
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004498 def radix(self):
4499 """Just returns 10, as this is Decimal, :)
4500
4501 >>> ExtendedContext.radix()
4502 Decimal("10")
4503 """
4504 return Decimal(10)
4505
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004506 def remainder(self, a, b):
4507 """Returns the remainder from integer division.
4508
4509 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004510 calculating integer division as described for divide-integer, rounded
4511 to precision digits if necessary. The sign of the result, if
4512 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004513
4514 This operation will fail under the same conditions as integer division
4515 (that is, if integer division on the same two operands would fail, the
4516 remainder cannot be calculated).
4517
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004518 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004519 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004520 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004521 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004522 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004523 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004524 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004525 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004526 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004527 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004528 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004529 Decimal("1.0")
4530 """
4531 return a.__mod__(b, context=self)
4532
4533 def remainder_near(self, a, b):
4534 """Returns to be "a - b * n", where n is the integer nearest the exact
4535 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004536 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004537 sign of a.
4538
4539 This operation will fail under the same conditions as integer division
4540 (that is, if integer division on the same two operands would fail, the
4541 remainder cannot be calculated).
4542
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004543 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004544 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004545 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004546 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004547 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004548 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004549 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004550 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004551 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004552 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004553 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004554 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004555 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004556 Decimal("-0.3")
4557 """
4558 return a.remainder_near(b, context=self)
4559
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004560 def rotate(self, a, b):
4561 """Returns a rotated copy of a, b times.
4562
4563 The coefficient of the result is a rotated copy of the digits in
4564 the coefficient of the first operand. The number of places of
4565 rotation is taken from the absolute value of the second operand,
4566 with the rotation being to the left if the second operand is
4567 positive or to the right otherwise.
4568
4569 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4570 Decimal("400000003")
4571 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4572 Decimal("12")
4573 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4574 Decimal("891234567")
4575 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4576 Decimal("123456789")
4577 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4578 Decimal("345678912")
4579 """
4580 return a.rotate(b, context=self)
4581
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004582 def same_quantum(self, a, b):
4583 """Returns True if the two operands have the same exponent.
4584
4585 The result is never affected by either the sign or the coefficient of
4586 either operand.
4587
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004588 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004589 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004590 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004591 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004592 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004593 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004594 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004595 True
4596 """
4597 return a.same_quantum(b)
4598
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004599 def scaleb (self, a, b):
4600 """Returns the first operand after adding the second value its exp.
4601
4602 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4603 Decimal("0.0750")
4604 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4605 Decimal("7.50")
4606 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4607 Decimal("7.50E+3")
4608 """
4609 return a.scaleb (b, context=self)
4610
4611 def shift(self, a, b):
4612 """Returns a shifted copy of a, b times.
4613
4614 The coefficient of the result is a shifted copy of the digits
4615 in the coefficient of the first operand. The number of places
4616 to shift is taken from the absolute value of the second operand,
4617 with the shift being to the left if the second operand is
4618 positive or to the right otherwise. Digits shifted into the
4619 coefficient are zeros.
4620
4621 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4622 Decimal("400000000")
4623 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4624 Decimal("0")
4625 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4626 Decimal("1234567")
4627 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4628 Decimal("123456789")
4629 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4630 Decimal("345678900")
4631 """
4632 return a.shift(b, context=self)
4633
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004634 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004635 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004636
4637 If the result must be inexact, it is rounded using the round-half-even
4638 algorithm.
4639
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004640 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004641 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004642 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004643 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004644 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004645 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004646 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004647 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004648 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004649 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004650 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004651 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004652 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004653 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004654 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004655 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004656 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004657 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004658 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004659 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004660 """
4661 return a.sqrt(context=self)
4662
4663 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004664 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004665
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004666 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004667 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004668 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004669 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004670 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004671 Decimal("-0.77")
4672 """
4673 return a.__sub__(b, context=self)
4674
4675 def to_eng_string(self, a):
4676 """Converts a number to a string, using scientific notation.
4677
4678 The operation is not affected by the context.
4679 """
4680 return a.to_eng_string(context=self)
4681
4682 def to_sci_string(self, a):
4683 """Converts a number to a string, using scientific notation.
4684
4685 The operation is not affected by the context.
4686 """
4687 return a.__str__(context=self)
4688
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004689 def to_integral_exact(self, a):
4690 """Rounds to an integer.
4691
4692 When the operand has a negative exponent, the result is the same
4693 as using the quantize() operation using the given operand as the
4694 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4695 of the operand as the precision setting; Inexact and Rounded flags
4696 are allowed in this operation. The rounding mode is taken from the
4697 context.
4698
4699 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4700 Decimal("2")
4701 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4702 Decimal("100")
4703 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4704 Decimal("100")
4705 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4706 Decimal("102")
4707 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4708 Decimal("-102")
4709 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4710 Decimal("1.0E+6")
4711 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4712 Decimal("7.89E+77")
4713 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4714 Decimal("-Infinity")
4715 """
4716 return a.to_integral_exact(context=self)
4717
4718 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004719 """Rounds to an integer.
4720
4721 When the operand has a negative exponent, the result is the same
4722 as using the quantize() operation using the given operand as the
4723 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4724 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004725 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004726
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004727 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004728 Decimal("2")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004729 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004730 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004731 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004732 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004733 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004734 Decimal("102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004735 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004736 Decimal("-102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004737 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004738 Decimal("1.0E+6")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004739 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004740 Decimal("7.89E+77")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004741 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004742 Decimal("-Infinity")
4743 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004744 return a.to_integral_value(context=self)
4745
4746 # the method name changed, but we provide also the old one, for compatibility
4747 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004748
4749class _WorkRep(object):
4750 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004751 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004752 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004753 # exp: None, int, or string
4754
4755 def __init__(self, value=None):
4756 if value is None:
4757 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004758 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004759 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004760 elif isinstance(value, Decimal):
4761 self.sign = value._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004762 cum = 0
Raymond Hettinger17931de2004-10-27 06:21:46 +00004763 for digit in value._int:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004764 cum = cum * 10 + digit
4765 self.int = cum
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004766 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004767 else:
4768 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004769 self.sign = value[0]
4770 self.int = value[1]
4771 self.exp = value[2]
4772
4773 def __repr__(self):
4774 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4775
4776 __str__ = __repr__
4777
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004778
4779
4780def _normalize(op1, op2, shouldround = 0, prec = 0):
4781 """Normalizes op1, op2 to have the same exp and length of coefficient.
4782
4783 Done during addition.
4784 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004785 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004786 tmp = op2
4787 other = op1
4788 else:
4789 tmp = op1
4790 other = op2
4791
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004792 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4793 # Then adding 10**exp to tmp has the same effect (after rounding)
4794 # as adding any positive quantity smaller than 10**exp; similarly
4795 # for subtraction. So if other is smaller than 10**exp we replace
4796 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4797 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004798 tmp_len = len(str(tmp.int))
4799 other_len = len(str(other.int))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004800 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4801 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004802 other.int = 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004803 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004804
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004805 tmp.int *= 10 ** (tmp.exp - other.exp)
4806 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004807 return op1, op2
4808
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004809##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004810
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004811# This function from Tim Peters was taken from here:
4812# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4813# The correction being in the function definition is for speed, and
4814# the whole function is not resolved with math.log because of avoiding
4815# the use of floats.
4816def _nbits(n, correction = {
4817 '0': 4, '1': 3, '2': 2, '3': 2,
4818 '4': 1, '5': 1, '6': 1, '7': 1,
4819 '8': 0, '9': 0, 'a': 0, 'b': 0,
4820 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4821 """Number of bits in binary representation of the positive integer n,
4822 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004823 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004824 if n < 0:
4825 raise ValueError("The argument to _nbits should be nonnegative.")
4826 hex_n = "%x" % n
4827 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004828
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004829def _sqrt_nearest(n, a):
4830 """Closest integer to the square root of the positive integer n. a is
4831 an initial approximation to the square root. Any positive integer
4832 will do for a, but the closer a is to the square root of n the
4833 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004834
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004835 """
4836 if n <= 0 or a <= 0:
4837 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4838
4839 b=0
4840 while a != b:
4841 b, a = a, a--n//a>>1
4842 return a
4843
4844def _rshift_nearest(x, shift):
4845 """Given an integer x and a nonnegative integer shift, return closest
4846 integer to x / 2**shift; use round-to-even in case of a tie.
4847
4848 """
4849 b, q = 1 << shift, x >> shift
4850 return q + (2*(x & (b-1)) + (q&1) > b)
4851
4852def _div_nearest(a, b):
4853 """Closest integer to a/b, a and b positive integers; rounds to even
4854 in the case of a tie.
4855
4856 """
4857 q, r = divmod(a, b)
4858 return q + (2*r + (q&1) > b)
4859
4860def _ilog(x, M, L = 8):
4861 """Integer approximation to M*log(x/M), with absolute error boundable
4862 in terms only of x/M.
4863
4864 Given positive integers x and M, return an integer approximation to
4865 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4866 between the approximation and the exact result is at most 22. For
4867 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4868 both cases these are upper bounds on the error; it will usually be
4869 much smaller."""
4870
4871 # The basic algorithm is the following: let log1p be the function
4872 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4873 # the reduction
4874 #
4875 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4876 #
4877 # repeatedly until the argument to log1p is small (< 2**-L in
4878 # absolute value). For small y we can use the Taylor series
4879 # expansion
4880 #
4881 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4882 #
4883 # truncating at T such that y**T is small enough. The whole
4884 # computation is carried out in a form of fixed-point arithmetic,
4885 # with a real number z being represented by an integer
4886 # approximation to z*M. To avoid loss of precision, the y below
4887 # is actually an integer approximation to 2**R*y*M, where R is the
4888 # number of reductions performed so far.
4889
4890 y = x-M
4891 # argument reduction; R = number of reductions performed
4892 R = 0
4893 while (R <= L and abs(y) << L-R >= M or
4894 R > L and abs(y) >> R-L >= M):
4895 y = _div_nearest((M*y) << 1,
4896 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4897 R += 1
4898
4899 # Taylor series with T terms
4900 T = -int(-10*len(str(M))//(3*L))
4901 yshift = _rshift_nearest(y, R)
4902 w = _div_nearest(M, T)
4903 for k in range(T-1, 0, -1):
4904 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4905
4906 return _div_nearest(w*y, M)
4907
4908def _dlog10(c, e, p):
4909 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4910 approximation to 10**p * log10(c*10**e), with an absolute error of
4911 at most 1. Assumes that c*10**e is not exactly 1."""
4912
4913 # increase precision by 2; compensate for this by dividing
4914 # final result by 100
4915 p += 2
4916
4917 # write c*10**e as d*10**f with either:
4918 # f >= 0 and 1 <= d <= 10, or
4919 # f <= 0 and 0.1 <= d <= 1.
4920 # Thus for c*10**e close to 1, f = 0
4921 l = len(str(c))
4922 f = e+l - (e+l >= 1)
4923
4924 if p > 0:
4925 M = 10**p
4926 k = e+p-f
4927 if k >= 0:
4928 c *= 10**k
4929 else:
4930 c = _div_nearest(c, 10**-k)
4931
4932 log_d = _ilog(c, M) # error < 5 + 22 = 27
4933 log_10 = _ilog(10*M, M) # error < 15
4934 log_d = _div_nearest(log_d*M, log_10)
4935 log_tenpower = f*M # exact
4936 else:
4937 log_d = 0 # error < 2.31
4938 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4939
4940 return _div_nearest(log_tenpower+log_d, 100)
4941
4942def _dlog(c, e, p):
4943 """Given integers c, e and p with c > 0, compute an integer
4944 approximation to 10**p * log(c*10**e), with an absolute error of
4945 at most 1. Assumes that c*10**e is not exactly 1."""
4946
4947 # Increase precision by 2. The precision increase is compensated
4948 # for at the end with a division by 100.
4949 p += 2
4950
4951 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4952 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4953 # as 10**p * log(d) + 10**p*f * log(10).
4954 l = len(str(c))
4955 f = e+l - (e+l >= 1)
4956
4957 # compute approximation to 10**p*log(d), with error < 27
4958 if p > 0:
4959 k = e+p-f
4960 if k >= 0:
4961 c *= 10**k
4962 else:
4963 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4964
4965 # _ilog magnifies existing error in c by a factor of at most 10
4966 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4967 else:
4968 # p <= 0: just approximate the whole thing by 0; error < 2.31
4969 log_d = 0
4970
4971 # compute approximation to 10**p*f*log(10), with error < 17
4972 if f:
4973 sign_f = [-1, 1][f > 0]
4974 if p >= 0:
4975 M = 10**p * abs(f)
4976 else:
4977 M = _div_nearest(abs(f), 10**-p) # M = 10**p*|f|, error <= 0.5
4978
4979 if M:
4980 f_log_ten = sign_f*_ilog(10*M, M) # M*log(10), error <= 1.2 + 15 < 17
4981 else:
4982 f_log_ten = 0
4983 else:
4984 f_log_ten = 0
4985
4986 # error in sum < 17+27 = 44; error after division < 0.44 + 0.5 < 1
4987 return _div_nearest(f_log_ten + log_d, 100)
4988
4989def _iexp(x, M, L=8):
4990 """Given integers x and M, M > 0, such that x/M is small in absolute
4991 value, compute an integer approximation to M*exp(x/M). For 0 <=
4992 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4993 is usually much smaller)."""
4994
4995 # Algorithm: to compute exp(z) for a real number z, first divide z
4996 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4997 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4998 # series
4999 #
5000 # expm1(x) = x + x**2/2! + x**3/3! + ...
5001 #
5002 # Now use the identity
5003 #
5004 # expm1(2x) = expm1(x)*(expm1(x)+2)
5005 #
5006 # R times to compute the sequence expm1(z/2**R),
5007 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5008
5009 # Find R such that x/2**R/M <= 2**-L
5010 R = _nbits((x<<L)//M)
5011
5012 # Taylor series. (2**L)**T > M
5013 T = -int(-10*len(str(M))//(3*L))
5014 y = _div_nearest(x, T)
5015 Mshift = M<<R
5016 for i in range(T-1, 0, -1):
5017 y = _div_nearest(x*(Mshift + y), Mshift * i)
5018
5019 # Expansion
5020 for k in range(R-1, -1, -1):
5021 Mshift = M<<(k+2)
5022 y = _div_nearest(y*(y+Mshift), Mshift)
5023
5024 return M+y
5025
5026def _dexp(c, e, p):
5027 """Compute an approximation to exp(c*10**e), with p decimal places of
5028 precision.
5029
5030 Returns d, f such that:
5031
5032 10**(p-1) <= d <= 10**p, and
5033 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5034
5035 In other words, d*10**f is an approximation to exp(c*10**e) with p
5036 digits of precision, and with an error in d of at most 1. This is
5037 almost, but not quite, the same as the error being < 1ulp: when d
5038 = 10**(p-1) the error could be up to 10 ulp."""
5039
5040 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5041 p += 2
5042
5043 # compute log10 with extra precision = adjusted exponent of c*10**e
5044 extra = max(0, e + len(str(c)) - 1)
5045 q = p + extra
5046 log10 = _dlog(10, 0, q) # error <= 1
5047
5048 # compute quotient c*10**e/(log10/10**q) = c*10**(e+q)/log10,
5049 # rounding down
5050 shift = e+q
5051 if shift >= 0:
5052 cshift = c*10**shift
5053 else:
5054 cshift = c//10**-shift
5055 quot, rem = divmod(cshift, log10)
5056
5057 # reduce remainder back to original precision
5058 rem = _div_nearest(rem, 10**extra)
5059
5060 # error in result of _iexp < 120; error after division < 0.62
5061 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5062
5063def _dpower(xc, xe, yc, ye, p):
5064 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5065 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5066
5067 10**(p-1) <= c <= 10**p, and
5068 (c-1)*10**e < x**y < (c+1)*10**e
5069
5070 in other words, c*10**e is an approximation to x**y with p digits
5071 of precision, and with an error in c of at most 1. (This is
5072 almost, but not quite, the same as the error being < 1ulp: when c
5073 == 10**(p-1) we can only guarantee error < 10ulp.)
5074
5075 We assume that: x is positive and not equal to 1, and y is nonzero.
5076 """
5077
5078 # Find b such that 10**(b-1) <= |y| <= 10**b
5079 b = len(str(abs(yc))) + ye
5080
5081 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5082 lxc = _dlog(xc, xe, p+b+1)
5083
5084 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5085 shift = ye-b
5086 if shift >= 0:
5087 pc = lxc*yc*10**shift
5088 else:
5089 pc = _div_nearest(lxc*yc, 10**-shift)
5090
5091 if pc == 0:
5092 # we prefer a result that isn't exactly 1; this makes it
5093 # easier to compute a correctly rounded result in __pow__
5094 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5095 coeff, exp = 10**(p-1)+1, 1-p
5096 else:
5097 coeff, exp = 10**p-1, -p
5098 else:
5099 coeff, exp = _dexp(pc, -(p+1), p+1)
5100 coeff = _div_nearest(coeff, 10)
5101 exp += 1
5102
5103 return coeff, exp
5104
5105def _log10_lb(c, correction = {
5106 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5107 '6': 23, '7': 16, '8': 10, '9': 5}):
5108 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5109 if c <= 0:
5110 raise ValueError("The argument to _log10_lb should be nonnegative.")
5111 str_c = str(c)
5112 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005113
Guido van Rossumd8faa362007-04-27 19:54:29 +00005114##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005115
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005116def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005117 """Convert other to Decimal.
5118
5119 Verifies that it's ok to use in an implicit construction.
5120 """
5121 if isinstance(other, Decimal):
5122 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005123 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005124 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005125 if raiseit:
5126 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005127 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005128
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005129_infinity_map = {
5130 'inf' : 1,
5131 'infinity' : 1,
5132 '+inf' : 1,
5133 '+infinity' : 1,
5134 '-inf' : -1,
5135 '-infinity' : -1
5136}
5137
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005138def _isinfinity(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005139 """Determines whether a string or float is infinity.
5140
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005141 +1 for negative infinity; 0 for finite ; +1 for positive infinity
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005142 """
5143 num = str(num).lower()
5144 return _infinity_map.get(num, 0)
5145
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005146def _isnan(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005147 """Determines whether a string or float is NaN
5148
5149 (1, sign, diagnostic info as string) => NaN
5150 (2, sign, diagnostic info as string) => sNaN
5151 0 => not a NaN
5152 """
5153 num = str(num).lower()
5154 if not num:
5155 return 0
5156
Guido van Rossumd8faa362007-04-27 19:54:29 +00005157 # Get the sign, get rid of trailing [+-]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005158 sign = 0
5159 if num[0] == '+':
5160 num = num[1:]
Guido van Rossumd8faa362007-04-27 19:54:29 +00005161 elif num[0] == '-': # elif avoids '+-nan'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005162 num = num[1:]
5163 sign = 1
5164
5165 if num.startswith('nan'):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005166 if len(num) > 3 and not num[3:].isdigit(): # diagnostic info
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005167 return 0
5168 return (1, sign, num[3:].lstrip('0'))
5169 if num.startswith('snan'):
5170 if len(num) > 4 and not num[4:].isdigit():
5171 return 0
5172 return (2, sign, num[4:].lstrip('0'))
5173 return 0
5174
5175
Guido van Rossumd8faa362007-04-27 19:54:29 +00005176##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005177
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005178# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005179# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005180
5181DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005182 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005183 traps=[DivisionByZero, Overflow, InvalidOperation],
5184 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005185 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005186 Emax=999999999,
5187 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005188 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005189)
5190
5191# Pre-made alternate contexts offered by the specification
5192# Don't change these; the user should be able to select these
5193# contexts and be able to reproduce results from other implementations
5194# of the spec.
5195
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005196BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005197 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005198 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5199 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005200)
5201
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005202ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005203 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005204 traps=[],
5205 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005206)
5207
5208
Guido van Rossumd8faa362007-04-27 19:54:29 +00005209##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005210
Guido van Rossumd8faa362007-04-27 19:54:29 +00005211# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005212Inf = Decimal('Inf')
5213negInf = Decimal('-Inf')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005214NaN = Decimal('NaN')
5215Dec_0 = Decimal(0)
5216Dec_p1 = Decimal(1)
5217Dec_n1 = Decimal(-1)
5218Dec_p2 = Decimal(2)
5219Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005220
Guido van Rossumd8faa362007-04-27 19:54:29 +00005221# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005222Infsign = (Inf, negInf)
5223
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005224
Guido van Rossumd8faa362007-04-27 19:54:29 +00005225##### crud for parsing strings #############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005226import re
5227
5228# There's an optional sign at the start, and an optional exponent
5229# at the end. The exponent has an optional sign and at least one
5230# digit. In between, must have either at least one digit followed
5231# by an optional fraction, or a decimal point followed by at least
5232# one digit. Yuck.
5233
5234_parser = re.compile(r"""
5235# \s*
5236 (?P<sign>[-+])?
5237 (
5238 (?P<int>\d+) (\. (?P<frac>\d*))?
5239 |
5240 \. (?P<onlyfrac>\d+)
5241 )
5242 ([eE](?P<exp>[-+]? \d+))?
5243# \s*
5244 $
Guido van Rossumd8faa362007-04-27 19:54:29 +00005245""", re.VERBOSE).match # Uncomment the \s* to allow leading or trailing spaces.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005246
5247del re
5248
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005249def _string2exact(s):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005250 """Return sign, n, p s.t.
5251
5252 Float string value == -1**sign * n * 10**p exactly
5253 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005254 m = _parser(s)
5255 if m is None:
5256 raise ValueError("invalid literal for Decimal: %r" % s)
5257
5258 if m.group('sign') == "-":
5259 sign = 1
5260 else:
5261 sign = 0
5262
5263 exp = m.group('exp')
5264 if exp is None:
5265 exp = 0
5266 else:
5267 exp = int(exp)
5268
5269 intpart = m.group('int')
5270 if intpart is None:
5271 intpart = ""
5272 fracpart = m.group('onlyfrac')
5273 else:
5274 fracpart = m.group('frac')
5275 if fracpart is None:
5276 fracpart = ""
5277
5278 exp -= len(fracpart)
5279
5280 mantissa = intpart + fracpart
Guido van Rossumc1f779c2007-07-03 08:25:58 +00005281 tmp = list(map(int, mantissa))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005282 backup = tmp
5283 while tmp and tmp[0] == 0:
5284 del tmp[0]
5285
5286 # It's a zero
5287 if not tmp:
5288 if backup:
5289 return (sign, tuple(backup), exp)
5290 return (sign, (0,), exp)
5291 mantissa = tuple(tmp)
5292
5293 return (sign, mantissa, exp)
5294
5295
5296if __name__ == '__main__':
5297 import doctest, sys
5298 doctest.testmod(sys.modules[__name__])