blob: faf9bf71d90783d45c2967adb55564ecca388102 [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 Rossum8ce8a782007-11-01 19:42:39 +0000565 raise ValueError('Invalid tuple size in creation of Decimal '
566 'from list or tuple. The list or tuple '
567 'should have exactly three elements.')
568 # process sign. The isinstance test rejects floats
569 if not (isinstance(value[0], int) and value[0] in (0,1)):
570 raise ValueError("Invalid sign. The first value in the tuple "
571 "should be an integer; either 0 for a "
572 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000573 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000574 if value[2] == 'F':
575 # infinity: value[1] is ignored
576 self._int = (0,)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000577 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000578 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000579 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000580 # process and validate the digits in value[1]
581 digits = []
582 for digit in value[1]:
583 if isinstance(digit, int) and 0 <= digit <= 9:
584 # skip leading zeros
585 if digits or digit != 0:
586 digits.append(digit)
587 else:
588 raise ValueError("The second value in the tuple must "
589 "be composed of integers in the range "
590 "0 through 9.")
591 if value[2] in ('n', 'N'):
592 # NaN: digits form the diagnostic
593 self._int = tuple(digits)
594 self._exp = value[2]
595 self._is_special = True
596 elif isinstance(value[2], int):
597 # finite number: digits give the coefficient
598 self._int = tuple(digits or [0])
599 self._exp = value[2]
600 self._is_special = False
601 else:
602 raise ValueError("The third value in the tuple must "
603 "be an integer, or one of the "
604 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000605 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000606
Raymond Hettingerbf440692004-07-10 14:14:37 +0000607 if isinstance(value, float):
608 raise TypeError("Cannot convert float to Decimal. " +
609 "First convert the float to a string")
610
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000611 # Other argument types may require the context during interpretation
612 if context is None:
613 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000614
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000615 # From a string
616 # REs insist on real strings, so we can too.
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000617 if isinstance(value, str):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000618 if _isinfinity(value):
619 self._exp = 'F'
620 self._int = (0,)
621 self._is_special = True
622 if _isinfinity(value) == 1:
623 self._sign = 0
624 else:
625 self._sign = 1
626 return self
627 if _isnan(value):
628 sig, sign, diag = _isnan(value)
629 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000630 if sig == 1:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000631 self._exp = 'n' # qNaN
632 else: # sig == 2
633 self._exp = 'N' # sNaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000634 self._sign = sign
Guido van Rossumd8faa362007-04-27 19:54:29 +0000635 self._int = tuple(map(int, diag)) # Diagnostic info
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000636 return self
637 try:
638 self._sign, self._int, self._exp = _string2exact(value)
639 except ValueError:
640 self._is_special = True
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000641 return context._raise_error(ConversionSyntax,
642 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000643 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000644
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000645 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000646
647 def _isnan(self):
648 """Returns whether the number is not actually one.
649
650 0 if a number
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000651 1 if NaN (it could be a normal quiet NaN or a phantom one)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000652 2 if sNaN
653 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000654 if self._is_special:
655 exp = self._exp
656 if exp == 'n':
657 return 1
658 elif exp == 'N':
659 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000660 return 0
661
662 def _isinfinity(self):
663 """Returns whether the number is infinite
664
665 0 if finite or not a number
666 1 if +INF
667 -1 if -INF
668 """
669 if self._exp == 'F':
670 if self._sign:
671 return -1
672 return 1
673 return 0
674
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000675 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000676 """Returns whether the number is not actually one.
677
678 if self, other are sNaN, signal
679 if self, other are NaN return nan
680 return 0
681
682 Done before operations.
683 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000684
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000685 self_is_nan = self._isnan()
686 if other is None:
687 other_is_nan = False
688 else:
689 other_is_nan = other._isnan()
690
691 if self_is_nan or other_is_nan:
692 if context is None:
693 context = getcontext()
694
695 if self_is_nan == 2:
696 return context._raise_error(InvalidOperation, 'sNaN',
697 1, self)
698 if other_is_nan == 2:
699 return context._raise_error(InvalidOperation, 'sNaN',
700 1, other)
701 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000702 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000703
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000704 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000705 return 0
706
Jack Diederich4dafcc42006-11-28 19:15:13 +0000707 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000708 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000709
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000710 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000711 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000712 return self._is_special or self._int[0] != 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000713
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000714 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000715 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000716 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000717 # Never return NotImplemented
718 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000719
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000720 if self._is_special or other._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000721 # check for nans, without raising on a signaling nan
722 if self._isnan() or other._isnan():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000723 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000724
725 # INF = INF
726 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000727
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000728 # check for zeros; note that cmp(0, -0) should return 0
729 if not self:
730 if not other:
731 return 0
732 else:
733 return -((-1)**other._sign)
734 if not other:
735 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000736
Guido van Rossumd8faa362007-04-27 19:54:29 +0000737 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000738 if other._sign < self._sign:
739 return -1
740 if self._sign < other._sign:
741 return 1
742
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000743 self_adjusted = self.adjusted()
744 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000745 if self_adjusted == other_adjusted:
746 self_padded = self._int + (0,)*(self._exp - other._exp)
747 other_padded = other._int + (0,)*(other._exp - self._exp)
748 return cmp(self_padded, other_padded) * (-1)**self._sign
749 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000750 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000751 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000752 return -((-1)**self._sign)
753
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000754 def __eq__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000755 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000756 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000757 return self.__cmp__(other) == 0
758
759 def __ne__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000760 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000761 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000762 return self.__cmp__(other) != 0
763
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000764 def __lt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000765 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000766 return NotImplemented
767 return self.__cmp__(other) < 0
768
769 def __le__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000770 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000771 return NotImplemented
772 return self.__cmp__(other) <= 0
773
774 def __gt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000775 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000776 return NotImplemented
777 return self.__cmp__(other) > 0
778
779 def __ge__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000780 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000781 return NotImplemented
782 return self.__cmp__(other) >= 0
783
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000784 def compare(self, other, context=None):
785 """Compares one to another.
786
787 -1 => a < b
788 0 => a = b
789 1 => a > b
790 NaN => one is NaN
791 Like __cmp__, but returns Decimal instances.
792 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000793 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000794
Guido van Rossumd8faa362007-04-27 19:54:29 +0000795 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000796 if (self._is_special or other and other._is_special):
797 ans = self._check_nans(other, context)
798 if ans:
799 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000800
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000801 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000802
803 def __hash__(self):
804 """x.__hash__() <==> hash(x)"""
805 # Decimal integers must hash the same as the ints
806 # Non-integer decimals are normalized and hashed as strings
Thomas Wouters477c8d52006-05-27 19:21:47 +0000807 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000808 if self._is_special:
809 if self._isnan():
810 raise TypeError('Cannot hash a NaN value.')
811 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000812 if not self:
813 return 0
814 if self._isinteger():
815 op = _WorkRep(self.to_integral_value())
816 # to make computation feasible for Decimals with large
817 # exponent, we use the fact that hash(n) == hash(m) for
818 # any two nonzero integers n and m such that (i) n and m
819 # have the same sign, and (ii) n is congruent to m modulo
820 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
821 # hash((-1)**s*c*pow(10, e, 2**64-1).
822 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000823 return hash(str(self.normalize()))
824
825 def as_tuple(self):
826 """Represents the number as a triple tuple.
827
828 To show the internals exactly as they are.
829 """
830 return (self._sign, self._int, self._exp)
831
832 def __repr__(self):
833 """Represents the number as an instance of Decimal."""
834 # Invariant: eval(repr(d)) == d
835 return 'Decimal("%s")' % str(self)
836
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000837 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000838 """Return string representation of the number in scientific notation.
839
840 Captures all of the information in the underlying representation.
841 """
842
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000843 if self._is_special:
844 if self._isnan():
845 minus = '-'*self._sign
846 if self._int == (0,):
847 info = ''
848 else:
849 info = ''.join(map(str, self._int))
850 if self._isnan() == 2:
851 return minus + 'sNaN' + info
852 return minus + 'NaN' + info
853 if self._isinfinity():
854 minus = '-'*self._sign
855 return minus + 'Infinity'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000856
857 if context is None:
858 context = getcontext()
859
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000860 tmp = list(map(str, self._int))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000861 numdigits = len(self._int)
862 leftdigits = self._exp + numdigits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000863 if eng and not self: # self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
864 if self._exp < 0 and self._exp >= -6: # short, no need for e/E
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000865 s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
866 return s
Guido van Rossumd8faa362007-04-27 19:54:29 +0000867 # exp is closest mult. of 3 >= self._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000868 exp = ((self._exp - 1)// 3 + 1) * 3
869 if exp != self._exp:
870 s = '0.'+'0'*(exp - self._exp)
871 else:
872 s = '0'
873 if exp != 0:
874 if context.capitals:
875 s += 'E'
876 else:
877 s += 'e'
878 if exp > 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000879 s += '+' # 0.0e+3, not 0.0e3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000880 s += str(exp)
881 s = '-'*self._sign + s
882 return s
883 if eng:
884 dotplace = (leftdigits-1)%3+1
885 adjexp = leftdigits -1 - (leftdigits-1)%3
886 else:
887 adjexp = leftdigits-1
888 dotplace = 1
889 if self._exp == 0:
890 pass
891 elif self._exp < 0 and adjexp >= 0:
892 tmp.insert(leftdigits, '.')
893 elif self._exp < 0 and adjexp >= -6:
894 tmp[0:0] = ['0'] * int(-leftdigits)
895 tmp.insert(0, '0.')
896 else:
897 if numdigits > dotplace:
898 tmp.insert(dotplace, '.')
899 elif numdigits < dotplace:
900 tmp.extend(['0']*(dotplace-numdigits))
901 if adjexp:
902 if not context.capitals:
903 tmp.append('e')
904 else:
905 tmp.append('E')
906 if adjexp > 0:
907 tmp.append('+')
908 tmp.append(str(adjexp))
909 if eng:
910 while tmp[0:1] == ['0']:
911 tmp[0:1] = []
912 if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
913 tmp[0:0] = ['0']
914 if self._sign:
915 tmp.insert(0, '-')
916
917 return ''.join(tmp)
918
919 def to_eng_string(self, context=None):
920 """Convert to engineering-type string.
921
922 Engineering notation has an exponent which is a multiple of 3, so there
923 are up to 3 digits left of the decimal place.
924
925 Same rules for when in exponential and when as a value as in __str__.
926 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000927 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000928
929 def __neg__(self, context=None):
930 """Returns a copy with the sign switched.
931
932 Rounds, if it has reason.
933 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000934 if self._is_special:
935 ans = self._check_nans(context=context)
936 if ans:
937 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000938
939 if not self:
940 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000941 ans = self.copy_sign(Dec_0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000942 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000943 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000944
945 if context is None:
946 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000947 if context._rounding_decision == ALWAYS_ROUND:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000948 return ans._fix(context)
949 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000950
951 def __pos__(self, context=None):
952 """Returns a copy, unless it is a sNaN.
953
954 Rounds the number (if more then precision digits)
955 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000956 if self._is_special:
957 ans = self._check_nans(context=context)
958 if ans:
959 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000960
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000961 if not self:
962 # + (-0) = 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000963 ans = self.copy_sign(Dec_0)
964 else:
965 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000966
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000967 if context is None:
968 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000969 if context._rounding_decision == ALWAYS_ROUND:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000970 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971 return ans
972
973 def __abs__(self, round=1, context=None):
974 """Returns the absolute value of self.
975
976 If the second argument is 0, do not round.
977 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000978 if self._is_special:
979 ans = self._check_nans(context=context)
980 if ans:
981 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000982
983 if not round:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000984 if context is None:
985 context = getcontext()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000986 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000987 context._set_rounding_decision(NEVER_ROUND)
988
989 if self._sign:
990 ans = self.__neg__(context=context)
991 else:
992 ans = self.__pos__(context=context)
993
994 return ans
995
996 def __add__(self, other, context=None):
997 """Returns self + other.
998
999 -INF + INF (or the reverse) cause InvalidOperation errors.
1000 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001001 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001002 if other is NotImplemented:
1003 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001004
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001005 if context is None:
1006 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001007
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001008 if self._is_special or other._is_special:
1009 ans = self._check_nans(other, context)
1010 if ans:
1011 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001012
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001013 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001014 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001015 if self._sign != other._sign and other._isinfinity():
1016 return context._raise_error(InvalidOperation, '-INF + INF')
1017 return Decimal(self)
1018 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001019 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001020
1021 shouldround = context._rounding_decision == ALWAYS_ROUND
1022
1023 exp = min(self._exp, other._exp)
1024 negativezero = 0
1025 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001026 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001027 negativezero = 1
1028
1029 if not self and not other:
1030 sign = min(self._sign, other._sign)
1031 if negativezero:
1032 sign = 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001033 ans = Decimal( (sign, (0,), exp))
1034 if shouldround:
1035 ans = ans._fix(context)
1036 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001037 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001038 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001039 ans = other._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001040 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001041 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001042 return ans
1043 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001044 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001045 ans = self._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001046 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001047 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001048 return ans
1049
1050 op1 = _WorkRep(self)
1051 op2 = _WorkRep(other)
1052 op1, op2 = _normalize(op1, op2, shouldround, context.prec)
1053
1054 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001056 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001057 if op1.int == op2.int:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001058 ans = Decimal((negativezero, (0,), exp))
1059 if shouldround:
1060 ans = ans._fix(context)
1061 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001062 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001063 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001064 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001065 if op1.sign == 1:
1066 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001067 op1.sign, op2.sign = op2.sign, op1.sign
1068 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001069 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001070 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001071 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001072 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001073 op1.sign, op2.sign = (0, 0)
1074 else:
1075 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001076 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001077
Raymond Hettinger17931de2004-10-27 06:21:46 +00001078 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001079 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001080 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001081 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001082
1083 result.exp = op1.exp
1084 ans = Decimal(result)
1085 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001086 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001087 return ans
1088
1089 __radd__ = __add__
1090
1091 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001092 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001093 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001094 if other is NotImplemented:
1095 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001096
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001097 if self._is_special or other._is_special:
1098 ans = self._check_nans(other, context=context)
1099 if ans:
1100 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001101
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001102 # self - other is computed as self + other.copy_negate()
1103 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001104
1105 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001106 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001107 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001108 if other is NotImplemented:
1109 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001110
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001111 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001112
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001113 def _increment(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001114 """Special case of add, adding 1eExponent
1115
1116 Since it is common, (rounding, for example) this adds
1117 (sign)*one E self._exp to the number more efficiently than add.
1118
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001119 Assumes that self is nonspecial.
1120
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001121 For example:
1122 Decimal('5.624e10')._increment() == Decimal('5.625e10')
1123 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001124 L = list(self._int)
1125 L[-1] += 1
1126 spot = len(L)-1
1127 while L[spot] == 10:
1128 L[spot] = 0
1129 if spot == 0:
1130 L[0:0] = [1]
1131 break
1132 L[spot-1] += 1
1133 spot -= 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001134 return Decimal((self._sign, L, self._exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001135
1136 def __mul__(self, other, context=None):
1137 """Return self * other.
1138
1139 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1140 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001141 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001142 if other is NotImplemented:
1143 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001144
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001145 if context is None:
1146 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001147
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001148 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001149
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001150 if self._is_special or other._is_special:
1151 ans = self._check_nans(other, context)
1152 if ans:
1153 return ans
1154
1155 if self._isinfinity():
1156 if not other:
1157 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1158 return Infsign[resultsign]
1159
1160 if other._isinfinity():
1161 if not self:
1162 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1163 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001164
1165 resultexp = self._exp + other._exp
1166 shouldround = context._rounding_decision == ALWAYS_ROUND
1167
1168 # Special case for multiplying by zero
1169 if not self or not other:
1170 ans = Decimal((resultsign, (0,), resultexp))
1171 if shouldround:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001172 # Fixing in case the exponent is out of bounds
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001173 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001174 return ans
1175
1176 # Special case for multiplying by power of 10
1177 if self._int == (1,):
1178 ans = Decimal((resultsign, other._int, resultexp))
1179 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001180 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001181 return ans
1182 if other._int == (1,):
1183 ans = Decimal((resultsign, self._int, resultexp))
1184 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001185 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001186 return ans
1187
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001188 op1 = _WorkRep(self)
1189 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001190
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001191 ans = Decimal((resultsign,
1192 tuple(map(int, str(op1.int * op2.int))),
1193 resultexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001194 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001195 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001196
1197 return ans
1198 __rmul__ = __mul__
1199
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001200 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001201 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001202 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001203 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001204 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001205
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001206 if context is None:
1207 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001208
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001209 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001210
1211 if self._is_special or other._is_special:
1212 ans = self._check_nans(other, context)
1213 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001214 return ans
1215
1216 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001217 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001218
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001219 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001220 return Infsign[sign]
1221
1222 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001223 context._raise_error(Clamped, 'Division by infinity')
1224 return Decimal((sign, (0,), context.Etiny()))
1225
1226 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001227 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001228 if not self:
1229 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001230 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001231
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001232 if not self:
1233 exp = self._exp - other._exp
1234 coeff = 0
1235 else:
1236 # OK, so neither = 0, INF or NaN
1237 shift = len(other._int) - len(self._int) + context.prec + 1
1238 exp = self._exp - other._exp - shift
1239 op1 = _WorkRep(self)
1240 op2 = _WorkRep(other)
1241 if shift >= 0:
1242 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1243 else:
1244 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1245 if remainder:
1246 # result is not exact; adjust to ensure correct rounding
1247 if coeff % 5 == 0:
1248 coeff += 1
1249 else:
1250 # result is exact; get as close to ideal exponent as possible
1251 ideal_exp = self._exp - other._exp
1252 while exp < ideal_exp and coeff % 10 == 0:
1253 coeff //= 10
1254 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001255
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001256 ans = Decimal((sign, list(map(int, str(coeff))), exp))
1257 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001258
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001259 def _divide(self, other, context):
1260 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001261
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001262 Assumes that neither self nor other is a NaN, that self is not
1263 infinite and that other is nonzero.
1264 """
1265 sign = self._sign ^ other._sign
1266 if other._isinfinity():
1267 ideal_exp = self._exp
1268 else:
1269 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001270
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001271 expdiff = self.adjusted() - other.adjusted()
1272 if not self or other._isinfinity() or expdiff <= -2:
1273 return (Decimal((sign, (0,), 0)),
1274 self._rescale(ideal_exp, context.rounding))
1275 if expdiff <= context.prec:
1276 op1 = _WorkRep(self)
1277 op2 = _WorkRep(other)
1278 if op1.exp >= op2.exp:
1279 op1.int *= 10**(op1.exp - op2.exp)
1280 else:
1281 op2.int *= 10**(op2.exp - op1.exp)
1282 q, r = divmod(op1.int, op2.int)
1283 if q < 10**context.prec:
1284 return (Decimal((sign, list(map(int, str(q))), 0)),
1285 Decimal((self._sign, list(map(int, str(r))),
1286 ideal_exp)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001287
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001288 # Here the quotient is too large to be representable
1289 ans = context._raise_error(DivisionImpossible,
1290 'quotient too large in //, % or divmod')
1291 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001292
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001293 def __rtruediv__(self, other, context=None):
1294 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001295 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001296 if other is NotImplemented:
1297 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001298 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001299
1300 def __divmod__(self, other, context=None):
1301 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001302 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001303 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001304 other = _convert_other(other)
1305 if other is NotImplemented:
1306 return other
1307
1308 if context is None:
1309 context = getcontext()
1310
1311 ans = self._check_nans(other, context)
1312 if ans:
1313 return (ans, ans)
1314
1315 sign = self._sign ^ other._sign
1316 if self._isinfinity():
1317 if other._isinfinity():
1318 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1319 return ans, ans
1320 else:
1321 return (Infsign[sign],
1322 context._raise_error(InvalidOperation, 'INF % x'))
1323
1324 if not other:
1325 if not self:
1326 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1327 return ans, ans
1328 else:
1329 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1330 context._raise_error(InvalidOperation, 'x % 0'))
1331
1332 quotient, remainder = self._divide(other, context)
1333 if context._rounding_decision == ALWAYS_ROUND:
1334 remainder = remainder._fix(context)
1335 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001336
1337 def __rdivmod__(self, other, context=None):
1338 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001339 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001340 if other is NotImplemented:
1341 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001342 return other.__divmod__(self, context=context)
1343
1344 def __mod__(self, other, context=None):
1345 """
1346 self % other
1347 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001348 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001349 if other is NotImplemented:
1350 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001351
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001352 if context is None:
1353 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001354
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001355 ans = self._check_nans(other, context)
1356 if ans:
1357 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001358
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001359 if self._isinfinity():
1360 return context._raise_error(InvalidOperation, 'INF % x')
1361 elif not other:
1362 if self:
1363 return context._raise_error(InvalidOperation, 'x % 0')
1364 else:
1365 return context._raise_error(DivisionUndefined, '0 % 0')
1366
1367 remainder = self._divide(other, context)[1]
1368 if context._rounding_decision == ALWAYS_ROUND:
1369 remainder = remainder._fix(context)
1370 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001371
1372 def __rmod__(self, other, context=None):
1373 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001374 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001375 if other is NotImplemented:
1376 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001377 return other.__mod__(self, context=context)
1378
1379 def remainder_near(self, other, context=None):
1380 """
1381 Remainder nearest to 0- abs(remainder-near) <= other/2
1382 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001383 if context is None:
1384 context = getcontext()
1385
1386 other = _convert_other(other, raiseit=True)
1387
1388 ans = self._check_nans(other, context)
1389 if ans:
1390 return ans
1391
1392 # self == +/-infinity -> InvalidOperation
1393 if self._isinfinity():
1394 return context._raise_error(InvalidOperation,
1395 'remainder_near(infinity, x)')
1396
1397 # other == 0 -> either InvalidOperation or DivisionUndefined
1398 if not other:
1399 if self:
1400 return context._raise_error(InvalidOperation,
1401 'remainder_near(x, 0)')
1402 else:
1403 return context._raise_error(DivisionUndefined,
1404 'remainder_near(0, 0)')
1405
1406 # other = +/-infinity -> remainder = self
1407 if other._isinfinity():
1408 ans = Decimal(self)
1409 return ans._fix(context)
1410
1411 # self = 0 -> remainder = self, with ideal exponent
1412 ideal_exponent = min(self._exp, other._exp)
1413 if not self:
1414 ans = Decimal((self._sign, (0,), ideal_exponent))
1415 return ans._fix(context)
1416
1417 # catch most cases of large or small quotient
1418 expdiff = self.adjusted() - other.adjusted()
1419 if expdiff >= context.prec + 1:
1420 # expdiff >= prec+1 => abs(self/other) > 10**prec
1421 return context._raise_error(DivisionImpossible)
1422 if expdiff <= -2:
1423 # expdiff <= -2 => abs(self/other) < 0.1
1424 ans = self._rescale(ideal_exponent, context.rounding)
1425 return ans._fix(context)
1426
1427 # adjust both arguments to have the same exponent, then divide
1428 op1 = _WorkRep(self)
1429 op2 = _WorkRep(other)
1430 if op1.exp >= op2.exp:
1431 op1.int *= 10**(op1.exp - op2.exp)
1432 else:
1433 op2.int *= 10**(op2.exp - op1.exp)
1434 q, r = divmod(op1.int, op2.int)
1435 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1436 # 10**ideal_exponent. Apply correction to ensure that
1437 # abs(remainder) <= abs(other)/2
1438 if 2*r + (q&1) > op2.int:
1439 r -= op2.int
1440 q += 1
1441
1442 if q >= 10**context.prec:
1443 return context._raise_error(DivisionImpossible)
1444
1445 # result has same sign as self unless r is negative
1446 sign = self._sign
1447 if r < 0:
1448 sign = 1-sign
1449 r = -r
1450
1451 ans = Decimal((sign, list(map(int, str(r))), ideal_exponent))
1452 return ans._fix(context)
1453
1454 def __floordiv__(self, other, context=None):
1455 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001456 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001457 if other is NotImplemented:
1458 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001459
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001460 if context is None:
1461 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001462
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001463 ans = self._check_nans(other, context)
1464 if ans:
1465 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001466
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001467 if self._isinfinity():
1468 if other._isinfinity():
1469 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001470 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001471 return Infsign[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001472
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001473 if not other:
1474 if self:
1475 return context._raise_error(DivisionByZero, 'x // 0',
1476 self._sign ^ other._sign)
1477 else:
1478 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001479
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001480 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001481
1482 def __rfloordiv__(self, other, context=None):
1483 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001484 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001485 if other is NotImplemented:
1486 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001487 return other.__floordiv__(self, context=context)
1488
1489 def __float__(self):
1490 """Float representation."""
1491 return float(str(self))
1492
1493 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001494 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001495 if self._is_special:
1496 if self._isnan():
1497 context = getcontext()
1498 return context._raise_error(InvalidContext)
1499 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001500 raise OverflowError("Cannot convert infinity to int")
1501 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001502 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001503 return s*int(''.join(map(str, self._int)))*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001504 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001505 return s*int(''.join(map(str, self._int))[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001506
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001507 def _fix_nan(self, context):
1508 """Decapitate the payload of a NaN to fit the context"""
1509 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001510
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001511 # maximum length of payload is precision if _clamp=0,
1512 # precision-1 if _clamp=1.
1513 max_payload_len = context.prec - context._clamp
1514 if len(payload) > max_payload_len:
1515 pos = len(payload)-max_payload_len
1516 while pos < len(payload) and payload[pos] == 0:
1517 pos += 1
1518 payload = payload[pos:]
1519 return Decimal((self._sign, payload, self._exp))
1520 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001521
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001522 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001523 """Round if it is necessary to keep self within prec precision.
1524
1525 Rounds and fixes the exponent. Does not raise on a sNaN.
1526
1527 Arguments:
1528 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001529 context - context used.
1530 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001531
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001532 if context is None:
1533 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001534
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001535 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001536 if self._isnan():
1537 # decapitate payload if necessary
1538 return self._fix_nan(context)
1539 else:
1540 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001541 return Decimal(self)
1542
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001543 # if self is zero then exponent should be between Etiny and
1544 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1545 Etiny = context.Etiny()
1546 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001547 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001548 exp_max = [context.Emax, Etop][context._clamp]
1549 new_exp = min(max(self._exp, Etiny), exp_max)
1550 if new_exp != self._exp:
1551 context._raise_error(Clamped)
1552 return Decimal((self._sign, (0,), new_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001553 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001554 return Decimal(self)
1555
1556 # exp_min is the smallest allowable exponent of the result,
1557 # equal to max(self.adjusted()-context.prec+1, Etiny)
1558 exp_min = len(self._int) + self._exp - context.prec
1559 if exp_min > Etop:
1560 # overflow: exp_min > Etop iff self.adjusted() > Emax
1561 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001562 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001563 return context._raise_error(Overflow, 'above Emax', self._sign)
1564 self_is_subnormal = exp_min < Etiny
1565 if self_is_subnormal:
1566 context._raise_error(Subnormal)
1567 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001568
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001569 # round if self has too many digits
1570 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001571 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001572 ans = self._rescale(exp_min, context.rounding)
1573 if ans != self:
1574 context._raise_error(Inexact)
1575 if self_is_subnormal:
1576 context._raise_error(Underflow)
1577 if not ans:
1578 # raise Clamped on underflow to 0
1579 context._raise_error(Clamped)
1580 elif len(ans._int) == context.prec+1:
1581 # we get here only if rescaling rounds the
1582 # cofficient up to exactly 10**context.prec
1583 if ans._exp < Etop:
1584 ans = Decimal((ans._sign, ans._int[:-1], ans._exp+1))
1585 else:
1586 # Inexact and Rounded have already been raised
1587 ans = context._raise_error(Overflow, 'above Emax',
1588 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001589 return ans
1590
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001591 # fold down if _clamp == 1 and self has too few digits
1592 if context._clamp == 1 and self._exp > Etop:
1593 context._raise_error(Clamped)
1594 self_padded = self._int + (0,)*(self._exp - Etop)
1595 return Decimal((self._sign, self_padded, Etop))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001596
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001597 # here self was representable to begin with; return unchanged
1598 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001599
1600 _pick_rounding_function = {}
1601
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001602 # for each of the rounding functions below:
1603 # self is a finite, nonzero Decimal
1604 # prec is an integer satisfying 0 <= prec < len(self._int)
1605 # the rounded result will have exponent self._exp + len(self._int) - prec;
1606
1607 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001608 """Also known as round-towards-0, truncate."""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001609 newexp = self._exp + len(self._int) - prec
1610 return Decimal((self._sign, self._int[:prec] or (0,), newexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001611
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001612 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001613 """Rounds away from 0."""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001614 newexp = self._exp + len(self._int) - prec
1615 tmp = Decimal((self._sign, self._int[:prec] or (0,), newexp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001616 for digit in self._int[prec:]:
1617 if digit != 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001618 return tmp._increment()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001619 return tmp
1620
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001621 def _round_half_up(self, prec):
1622 """Rounds 5 up (away from 0)"""
1623 if self._int[prec] >= 5:
1624 return self._round_up(prec)
1625 else:
1626 return self._round_down(prec)
1627
1628 def _round_half_down(self, prec):
1629 """Round 5 down"""
1630 if self._int[prec] == 5:
1631 for digit in self._int[prec+1:]:
1632 if digit != 0:
1633 break
1634 else:
1635 return self._round_down(prec)
1636 return self._round_half_up(prec)
1637
1638 def _round_half_even(self, prec):
1639 """Round 5 to even, rest to nearest."""
1640 if prec and self._int[prec-1] & 1:
1641 return self._round_half_up(prec)
1642 else:
1643 return self._round_half_down(prec)
1644
1645 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001646 """Rounds up (not away from 0 if negative.)"""
1647 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001648 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001649 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001650 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001651
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001652 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001653 """Rounds down (not towards 0 if negative)"""
1654 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001655 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001656 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001657 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001658
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001659 def _round_05up(self, prec):
1660 """Round down unless digit prec-1 is 0 or 5."""
1661 if prec == 0 or self._int[prec-1] in (0, 5):
1662 return self._round_up(prec)
1663 else:
1664 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001665
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001666 def fma(self, other, third, context=None):
1667 """Fused multiply-add.
1668
1669 Returns self*other+third with no rounding of the intermediate
1670 product self*other.
1671
1672 self and other are multiplied together, with no rounding of
1673 the result. The third operand is then added to the result,
1674 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001675 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001676
1677 other = _convert_other(other, raiseit=True)
1678 third = _convert_other(third, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001679
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001680 if context is None:
1681 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001682
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001683 # do self*other in fresh context with no traps and no rounding
1684 mul_context = Context(traps=[], flags=[],
1685 _rounding_decision=NEVER_ROUND)
1686 product = self.__mul__(other, mul_context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001687
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001688 if mul_context.flags[InvalidOperation]:
1689 # reraise in current context
1690 return context._raise_error(InvalidOperation,
1691 'invalid multiplication in fma',
1692 1, product)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001693
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001694 ans = product.__add__(third, context)
1695 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001696
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001697 def _power_modulo(self, other, modulo, context=None):
1698 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001699
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001700 # if can't convert other and modulo to Decimal, raise
1701 # TypeError; there's no point returning NotImplemented (no
1702 # equivalent of __rpow__ for three argument pow)
1703 other = _convert_other(other, raiseit=True)
1704 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001705
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001706 if context is None:
1707 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001708
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001709 # deal with NaNs: if there are any sNaNs then first one wins,
1710 # (i.e. behaviour for NaNs is identical to that of fma)
1711 self_is_nan = self._isnan()
1712 other_is_nan = other._isnan()
1713 modulo_is_nan = modulo._isnan()
1714 if self_is_nan or other_is_nan or modulo_is_nan:
1715 if self_is_nan == 2:
1716 return context._raise_error(InvalidOperation, 'sNaN',
1717 1, self)
1718 if other_is_nan == 2:
1719 return context._raise_error(InvalidOperation, 'sNaN',
1720 1, other)
1721 if modulo_is_nan == 2:
1722 return context._raise_error(InvalidOperation, 'sNaN',
1723 1, modulo)
1724 if self_is_nan:
1725 return self._fix_nan(context)
1726 if other_is_nan:
1727 return other._fix_nan(context)
1728 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001729
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001730 # check inputs: we apply same restrictions as Python's pow()
1731 if not (self._isinteger() and
1732 other._isinteger() and
1733 modulo._isinteger()):
1734 return context._raise_error(InvalidOperation,
1735 'pow() 3rd argument not allowed '
1736 'unless all arguments are integers')
1737 if other < 0:
1738 return context._raise_error(InvalidOperation,
1739 'pow() 2nd argument cannot be '
1740 'negative when 3rd argument specified')
1741 if not modulo:
1742 return context._raise_error(InvalidOperation,
1743 'pow() 3rd argument cannot be 0')
1744
1745 # additional restriction for decimal: the modulus must be less
1746 # than 10**prec in absolute value
1747 if modulo.adjusted() >= context.prec:
1748 return context._raise_error(InvalidOperation,
1749 'insufficient precision: pow() 3rd '
1750 'argument must not have more than '
1751 'precision digits')
1752
1753 # define 0**0 == NaN, for consistency with two-argument pow
1754 # (even though it hurts!)
1755 if not other and not self:
1756 return context._raise_error(InvalidOperation,
1757 'at least one of pow() 1st argument '
1758 'and 2nd argument must be nonzero ;'
1759 '0**0 is not defined')
1760
1761 # compute sign of result
1762 if other._iseven():
1763 sign = 0
1764 else:
1765 sign = self._sign
1766
1767 # convert modulo to a Python integer, and self and other to
1768 # Decimal integers (i.e. force their exponents to be >= 0)
1769 modulo = abs(int(modulo))
1770 base = _WorkRep(self.to_integral_value())
1771 exponent = _WorkRep(other.to_integral_value())
1772
1773 # compute result using integer pow()
1774 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1775 for i in range(exponent.exp):
1776 base = pow(base, 10, modulo)
1777 base = pow(base, exponent.int, modulo)
1778
1779 return Decimal((sign, list(map(int, str(base))), 0))
1780
1781 def _power_exact(self, other, p):
1782 """Attempt to compute self**other exactly.
1783
1784 Given Decimals self and other and an integer p, attempt to
1785 compute an exact result for the power self**other, with p
1786 digits of precision. Return None if self**other is not
1787 exactly representable in p digits.
1788
1789 Assumes that elimination of special cases has already been
1790 performed: self and other must both be nonspecial; self must
1791 be positive and not numerically equal to 1; other must be
1792 nonzero. For efficiency, other._exp should not be too large,
1793 so that 10**abs(other._exp) is a feasible calculation."""
1794
1795 # In the comments below, we write x for the value of self and
1796 # y for the value of other. Write x = xc*10**xe and y =
1797 # yc*10**ye.
1798
1799 # The main purpose of this method is to identify the *failure*
1800 # of x**y to be exactly representable with as little effort as
1801 # possible. So we look for cheap and easy tests that
1802 # eliminate the possibility of x**y being exact. Only if all
1803 # these tests are passed do we go on to actually compute x**y.
1804
1805 # Here's the main idea. First normalize both x and y. We
1806 # express y as a rational m/n, with m and n relatively prime
1807 # and n>0. Then for x**y to be exactly representable (at
1808 # *any* precision), xc must be the nth power of a positive
1809 # integer and xe must be divisible by n. If m is negative
1810 # then additionally xc must be a power of either 2 or 5, hence
1811 # a power of 2**n or 5**n.
1812 #
1813 # There's a limit to how small |y| can be: if y=m/n as above
1814 # then:
1815 #
1816 # (1) if xc != 1 then for the result to be representable we
1817 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1818 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1819 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1820 # representable.
1821 #
1822 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1823 # |y| < 1/|xe| then the result is not representable.
1824 #
1825 # Note that since x is not equal to 1, at least one of (1) and
1826 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1827 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1828 #
1829 # There's also a limit to how large y can be, at least if it's
1830 # positive: the normalized result will have coefficient xc**y,
1831 # so if it's representable then xc**y < 10**p, and y <
1832 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1833 # not exactly representable.
1834
1835 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1836 # so |y| < 1/xe and the result is not representable.
1837 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1838 # < 1/nbits(xc).
1839
1840 x = _WorkRep(self)
1841 xc, xe = x.int, x.exp
1842 while xc % 10 == 0:
1843 xc //= 10
1844 xe += 1
1845
1846 y = _WorkRep(other)
1847 yc, ye = y.int, y.exp
1848 while yc % 10 == 0:
1849 yc //= 10
1850 ye += 1
1851
1852 # case where xc == 1: result is 10**(xe*y), with xe*y
1853 # required to be an integer
1854 if xc == 1:
1855 if ye >= 0:
1856 exponent = xe*yc*10**ye
1857 else:
1858 exponent, remainder = divmod(xe*yc, 10**-ye)
1859 if remainder:
1860 return None
1861 if y.sign == 1:
1862 exponent = -exponent
1863 # if other is a nonnegative integer, use ideal exponent
1864 if other._isinteger() and other._sign == 0:
1865 ideal_exponent = self._exp*int(other)
1866 zeros = min(exponent-ideal_exponent, p-1)
1867 else:
1868 zeros = 0
1869 return Decimal((0, (1,) + (0,)*zeros, exponent-zeros))
1870
1871 # case where y is negative: xc must be either a power
1872 # of 2 or a power of 5.
1873 if y.sign == 1:
1874 last_digit = xc % 10
1875 if last_digit in (2,4,6,8):
1876 # quick test for power of 2
1877 if xc & -xc != xc:
1878 return None
1879 # now xc is a power of 2; e is its exponent
1880 e = _nbits(xc)-1
1881 # find e*y and xe*y; both must be integers
1882 if ye >= 0:
1883 y_as_int = yc*10**ye
1884 e = e*y_as_int
1885 xe = xe*y_as_int
1886 else:
1887 ten_pow = 10**-ye
1888 e, remainder = divmod(e*yc, ten_pow)
1889 if remainder:
1890 return None
1891 xe, remainder = divmod(xe*yc, ten_pow)
1892 if remainder:
1893 return None
1894
1895 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1896 return None
1897 xc = 5**e
1898
1899 elif last_digit == 5:
1900 # e >= log_5(xc) if xc is a power of 5; we have
1901 # equality all the way up to xc=5**2658
1902 e = _nbits(xc)*28//65
1903 xc, remainder = divmod(5**e, xc)
1904 if remainder:
1905 return None
1906 while xc % 5 == 0:
1907 xc //= 5
1908 e -= 1
1909 if ye >= 0:
1910 y_as_integer = yc*10**ye
1911 e = e*y_as_integer
1912 xe = xe*y_as_integer
1913 else:
1914 ten_pow = 10**-ye
1915 e, remainder = divmod(e*yc, ten_pow)
1916 if remainder:
1917 return None
1918 xe, remainder = divmod(xe*yc, ten_pow)
1919 if remainder:
1920 return None
1921 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1922 return None
1923 xc = 2**e
1924 else:
1925 return None
1926
1927 if xc >= 10**p:
1928 return None
1929 xe = -e-xe
1930 return Decimal((0, list(map(int, str(xc))), xe))
1931
1932 # now y is positive; find m and n such that y = m/n
1933 if ye >= 0:
1934 m, n = yc*10**ye, 1
1935 else:
1936 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1937 return None
1938 xc_bits = _nbits(xc)
1939 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1940 return None
1941 m, n = yc, 10**(-ye)
1942 while m % 2 == n % 2 == 0:
1943 m //= 2
1944 n //= 2
1945 while m % 5 == n % 5 == 0:
1946 m //= 5
1947 n //= 5
1948
1949 # compute nth root of xc*10**xe
1950 if n > 1:
1951 # if 1 < xc < 2**n then xc isn't an nth power
1952 if xc != 1 and xc_bits <= n:
1953 return None
1954
1955 xe, rem = divmod(xe, n)
1956 if rem != 0:
1957 return None
1958
1959 # compute nth root of xc using Newton's method
1960 a = 1 << -(-_nbits(xc)//n) # initial estimate
1961 while True:
1962 q, r = divmod(xc, a**(n-1))
1963 if a <= q:
1964 break
1965 else:
1966 a = (a*(n-1) + q)//n
1967 if not (a == q and r == 0):
1968 return None
1969 xc = a
1970
1971 # now xc*10**xe is the nth root of the original xc*10**xe
1972 # compute mth power of xc*10**xe
1973
1974 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1975 # 10**p and the result is not representable.
1976 if xc > 1 and m > p*100//_log10_lb(xc):
1977 return None
1978 xc = xc**m
1979 xe *= m
1980 if xc > 10**p:
1981 return None
1982
1983 # by this point the result *is* exactly representable
1984 # adjust the exponent to get as close as possible to the ideal
1985 # exponent, if necessary
1986 str_xc = str(xc)
1987 if other._isinteger() and other._sign == 0:
1988 ideal_exponent = self._exp*int(other)
1989 zeros = min(xe-ideal_exponent, p-len(str_xc))
1990 else:
1991 zeros = 0
1992 return Decimal((0, list(map(int, str_xc))+[0,]*zeros, xe-zeros))
1993
1994 def __pow__(self, other, modulo=None, context=None):
1995 """Return self ** other [ % modulo].
1996
1997 With two arguments, compute self**other.
1998
1999 With three arguments, compute (self**other) % modulo. For the
2000 three argument form, the following restrictions on the
2001 arguments hold:
2002
2003 - all three arguments must be integral
2004 - other must be nonnegative
2005 - either self or other (or both) must be nonzero
2006 - modulo must be nonzero and must have at most p digits,
2007 where p is the context precision.
2008
2009 If any of these restrictions is violated the InvalidOperation
2010 flag is raised.
2011
2012 The result of pow(self, other, modulo) is identical to the
2013 result that would be obtained by computing (self**other) %
2014 modulo with unbounded precision, but is computed more
2015 efficiently. It is always exact.
2016 """
2017
2018 if modulo is not None:
2019 return self._power_modulo(other, modulo, context)
2020
2021 other = _convert_other(other)
2022 if other is NotImplemented:
2023 return other
2024
2025 if context is None:
2026 context = getcontext()
2027
2028 # either argument is a NaN => result is NaN
2029 ans = self._check_nans(other, context)
2030 if ans:
2031 return ans
2032
2033 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2034 if not other:
2035 if not self:
2036 return context._raise_error(InvalidOperation, '0 ** 0')
2037 else:
2038 return Dec_p1
2039
2040 # result has sign 1 iff self._sign is 1 and other is an odd integer
2041 result_sign = 0
2042 if self._sign == 1:
2043 if other._isinteger():
2044 if not other._iseven():
2045 result_sign = 1
2046 else:
2047 # -ve**noninteger = NaN
2048 # (-0)**noninteger = 0**noninteger
2049 if self:
2050 return context._raise_error(InvalidOperation,
2051 'x ** y with x negative and y not an integer')
2052 # negate self, without doing any unwanted rounding
2053 self = Decimal((0, self._int, self._exp))
2054
2055 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2056 if not self:
2057 if other._sign == 0:
2058 return Decimal((result_sign, (0,), 0))
2059 else:
2060 return Infsign[result_sign]
2061
2062 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002063 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002064 if other._sign == 0:
2065 return Infsign[result_sign]
2066 else:
2067 return Decimal((result_sign, (0,), 0))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002068
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002069 # 1**other = 1, but the choice of exponent and the flags
2070 # depend on the exponent of self, and on whether other is a
2071 # positive integer, a negative integer, or neither
2072 if self == Dec_p1:
2073 if other._isinteger():
2074 # exp = max(self._exp*max(int(other), 0),
2075 # 1-context.prec) but evaluating int(other) directly
2076 # is dangerous until we know other is small (other
2077 # could be 1e999999999)
2078 if other._sign == 1:
2079 multiplier = 0
2080 elif other > context.prec:
2081 multiplier = context.prec
2082 else:
2083 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002084
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002085 exp = self._exp * multiplier
2086 if exp < 1-context.prec:
2087 exp = 1-context.prec
2088 context._raise_error(Rounded)
2089 else:
2090 context._raise_error(Inexact)
2091 context._raise_error(Rounded)
2092 exp = 1-context.prec
2093
2094 return Decimal((result_sign, (1,)+(0,)*-exp, exp))
2095
2096 # compute adjusted exponent of self
2097 self_adj = self.adjusted()
2098
2099 # self ** infinity is infinity if self > 1, 0 if self < 1
2100 # self ** -infinity is infinity if self < 1, 0 if self > 1
2101 if other._isinfinity():
2102 if (other._sign == 0) == (self_adj < 0):
2103 return Decimal((result_sign, (0,), 0))
2104 else:
2105 return Infsign[result_sign]
2106
2107 # from here on, the result always goes through the call
2108 # to _fix at the end of this function.
2109 ans = None
2110
2111 # crude test to catch cases of extreme overflow/underflow. If
2112 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2113 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2114 # self**other >= 10**(Emax+1), so overflow occurs. The test
2115 # for underflow is similar.
2116 bound = self._log10_exp_bound() + other.adjusted()
2117 if (self_adj >= 0) == (other._sign == 0):
2118 # self > 1 and other +ve, or self < 1 and other -ve
2119 # possibility of overflow
2120 if bound >= len(str(context.Emax)):
2121 ans = Decimal((result_sign, (1,), context.Emax+1))
2122 else:
2123 # self > 1 and other -ve, or self < 1 and other +ve
2124 # possibility of underflow to 0
2125 Etiny = context.Etiny()
2126 if bound >= len(str(-Etiny)):
2127 ans = Decimal((result_sign, (1,), Etiny-1))
2128
2129 # try for an exact result with precision +1
2130 if ans is None:
2131 ans = self._power_exact(other, context.prec + 1)
2132 if ans is not None and result_sign == 1:
2133 ans = Decimal((1, ans._int, ans._exp))
2134
2135 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2136 if ans is None:
2137 p = context.prec
2138 x = _WorkRep(self)
2139 xc, xe = x.int, x.exp
2140 y = _WorkRep(other)
2141 yc, ye = y.int, y.exp
2142 if y.sign == 1:
2143 yc = -yc
2144
2145 # compute correctly rounded result: start with precision +3,
2146 # then increase precision until result is unambiguously roundable
2147 extra = 3
2148 while True:
2149 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2150 if coeff % (5*10**(len(str(coeff))-p-1)):
2151 break
2152 extra += 3
2153
2154 ans = Decimal((result_sign, list(map(int, str(coeff))), exp))
2155
2156 # the specification says that for non-integer other we need to
2157 # raise Inexact, even when the result is actually exact. In
2158 # the same way, we need to raise Underflow here if the result
2159 # is subnormal. (The call to _fix will take care of raising
2160 # Rounded and Subnormal, as usual.)
2161 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002162 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002163 # pad with zeros up to length context.prec+1 if necessary
2164 if len(ans._int) <= context.prec:
2165 expdiff = context.prec+1 - len(ans._int)
2166 ans = Decimal((ans._sign, ans._int+(0,)*expdiff, ans._exp-expdiff))
2167 if ans.adjusted() < context.Emin:
2168 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002169
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002170 # unlike exp, ln and log10, the power function respects the
2171 # rounding mode; no need to use ROUND_HALF_EVEN here
2172 ans = ans._fix(context)
2173 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002174
2175 def __rpow__(self, other, context=None):
2176 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002177 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002178 if other is NotImplemented:
2179 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002180 return other.__pow__(self, context=context)
2181
2182 def normalize(self, context=None):
2183 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002184
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002185 if context is None:
2186 context = getcontext()
2187
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002188 if self._is_special:
2189 ans = self._check_nans(context=context)
2190 if ans:
2191 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002192
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002193 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002194 if dup._isinfinity():
2195 return dup
2196
2197 if not dup:
2198 return Decimal( (dup._sign, (0,), 0) )
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002199 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002200 end = len(dup._int)
2201 exp = dup._exp
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002202 while dup._int[end-1] == 0 and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002203 exp += 1
2204 end -= 1
2205 return Decimal( (dup._sign, dup._int[:end], exp) )
2206
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002207 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002208 """Quantize self so its exponent is the same as that of exp.
2209
2210 Similar to self._rescale(exp._exp) but with error checking.
2211 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002212 exp = _convert_other(exp, raiseit=True)
2213
2214 if context is None:
2215 context = getcontext()
2216 if rounding is None:
2217 rounding = context.rounding
2218
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002219 if self._is_special or exp._is_special:
2220 ans = self._check_nans(exp, context)
2221 if ans:
2222 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002223
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002224 if exp._isinfinity() or self._isinfinity():
2225 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002226 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002227 return context._raise_error(InvalidOperation,
2228 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002229
2230 # if we're not watching exponents, do a simple rescale
2231 if not watchexp:
2232 ans = self._rescale(exp._exp, rounding)
2233 # raise Inexact and Rounded where appropriate
2234 if ans._exp > self._exp:
2235 context._raise_error(Rounded)
2236 if ans != self:
2237 context._raise_error(Inexact)
2238 return ans
2239
2240 # exp._exp should be between Etiny and Emax
2241 if not (context.Etiny() <= exp._exp <= context.Emax):
2242 return context._raise_error(InvalidOperation,
2243 'target exponent out of bounds in quantize')
2244
2245 if not self:
2246 ans = Decimal((self._sign, (0,), exp._exp))
2247 return ans._fix(context)
2248
2249 self_adjusted = self.adjusted()
2250 if self_adjusted > context.Emax:
2251 return context._raise_error(InvalidOperation,
2252 'exponent of quantize result too large for current context')
2253 if self_adjusted - exp._exp + 1 > context.prec:
2254 return context._raise_error(InvalidOperation,
2255 'quantize result has too many digits for current context')
2256
2257 ans = self._rescale(exp._exp, rounding)
2258 if ans.adjusted() > context.Emax:
2259 return context._raise_error(InvalidOperation,
2260 'exponent of quantize result too large for current context')
2261 if len(ans._int) > context.prec:
2262 return context._raise_error(InvalidOperation,
2263 'quantize result has too many digits for current context')
2264
2265 # raise appropriate flags
2266 if ans._exp > self._exp:
2267 context._raise_error(Rounded)
2268 if ans != self:
2269 context._raise_error(Inexact)
2270 if ans and ans.adjusted() < context.Emin:
2271 context._raise_error(Subnormal)
2272
2273 # call to fix takes care of any necessary folddown
2274 ans = ans._fix(context)
2275 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002276
2277 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002278 """Return True if self and other have the same exponent; otherwise
2279 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002280
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002281 If either operand is a special value, the following rules are used:
2282 * return True if both operands are infinities
2283 * return True if both operands are NaNs
2284 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002285 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002286 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002287 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002288 return (self.is_nan() and other.is_nan() or
2289 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002290 return self._exp == other._exp
2291
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002292 def _rescale(self, exp, rounding):
2293 """Rescale self so that the exponent is exp, either by padding with zeros
2294 or by truncating digits, using the given rounding mode.
2295
2296 Specials are returned without change. This operation is
2297 quiet: it raises no flags, and uses no information from the
2298 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002299
2300 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002301 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002302 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002303 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002304 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002305 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002306 return Decimal((self._sign, (0,), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002307
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002308 if self._exp >= exp:
2309 # pad answer with zeros if necessary
2310 return Decimal((self._sign, self._int + (0,)*(self._exp - exp), exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002311
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002312 # too many digits; round and lose data. If self.adjusted() <
2313 # exp-1, replace self by 10**(exp-1) before rounding
2314 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002315 if digits < 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002316 self = Decimal((self._sign, (1,), exp-1))
2317 digits = 0
2318 this_function = getattr(self, self._pick_rounding_function[rounding])
2319 return this_function(digits)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002320
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002321 def to_integral_exact(self, rounding=None, context=None):
2322 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002323
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002324 If no rounding mode is specified, take the rounding mode from
2325 the context. This method raises the Rounded and Inexact flags
2326 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002327
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002328 See also: to_integral_value, which does exactly the same as
2329 this method except that it doesn't raise Inexact or Rounded.
2330 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002331 if self._is_special:
2332 ans = self._check_nans(context=context)
2333 if ans:
2334 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002335 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002336 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002337 return Decimal(self)
2338 if not self:
2339 return Decimal((self._sign, (0,), 0))
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002340 if context is None:
2341 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002342 if rounding is None:
2343 rounding = context.rounding
2344 context._raise_error(Rounded)
2345 ans = self._rescale(0, rounding)
2346 if ans != self:
2347 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002348 return ans
2349
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002350 def to_integral_value(self, rounding=None, context=None):
2351 """Rounds to the nearest integer, without raising inexact, rounded."""
2352 if context is None:
2353 context = getcontext()
2354 if rounding is None:
2355 rounding = context.rounding
2356 if self._is_special:
2357 ans = self._check_nans(context=context)
2358 if ans:
2359 return ans
2360 return Decimal(self)
2361 if self._exp >= 0:
2362 return Decimal(self)
2363 else:
2364 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002365
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002366 # the method name changed, but we provide also the old one, for compatibility
2367 to_integral = to_integral_value
2368
2369 def sqrt(self, context=None):
2370 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002371 if self._is_special:
2372 ans = self._check_nans(context=context)
2373 if ans:
2374 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002375
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002376 if self._isinfinity() and self._sign == 0:
2377 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002378
2379 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002380 # exponent = self._exp // 2. sqrt(-0) = -0
2381 ans = Decimal((self._sign, (0,), self._exp // 2))
2382 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002383
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002384 if context is None:
2385 context = getcontext()
2386
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002387 if self._sign == 1:
2388 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2389
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002390 # At this point self represents a positive number. Let p be
2391 # the desired precision and express self in the form c*100**e
2392 # with c a positive real number and e an integer, c and e
2393 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2394 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2395 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2396 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2397 # the closest integer to sqrt(c) with the even integer chosen
2398 # in the case of a tie.
2399 #
2400 # To ensure correct rounding in all cases, we use the
2401 # following trick: we compute the square root to an extra
2402 # place (precision p+1 instead of precision p), rounding down.
2403 # Then, if the result is inexact and its last digit is 0 or 5,
2404 # we increase the last digit to 1 or 6 respectively; if it's
2405 # exact we leave the last digit alone. Now the final round to
2406 # p places (or fewer in the case of underflow) will round
2407 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002408
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002409 # use an extra digit of precision
2410 prec = context.prec+1
2411
2412 # write argument in the form c*100**e where e = self._exp//2
2413 # is the 'ideal' exponent, to be used if the square root is
2414 # exactly representable. l is the number of 'digits' of c in
2415 # base 100, so that 100**(l-1) <= c < 100**l.
2416 op = _WorkRep(self)
2417 e = op.exp >> 1
2418 if op.exp & 1:
2419 c = op.int * 10
2420 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002421 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002422 c = op.int
2423 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002424
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002425 # rescale so that c has exactly prec base 100 'digits'
2426 shift = prec-l
2427 if shift >= 0:
2428 c *= 100**shift
2429 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002430 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002431 c, remainder = divmod(c, 100**-shift)
2432 exact = not remainder
2433 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002434
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002435 # find n = floor(sqrt(c)) using Newton's method
2436 n = 10**prec
2437 while True:
2438 q = c//n
2439 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002440 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002441 else:
2442 n = n + q >> 1
2443 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002444
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002445 if exact:
2446 # result is exact; rescale to use ideal exponent e
2447 if shift >= 0:
2448 # assert n % 10**shift == 0
2449 n //= 10**shift
2450 else:
2451 n *= 10**-shift
2452 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002453 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002454 # result is not exact; fix last digit as described above
2455 if n % 5 == 0:
2456 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002457
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002458 ans = Decimal((0, list(map(int, str(n))), e))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002459
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002460 # round, and fit to current context
2461 context = context._shallow_copy()
2462 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002463 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002464 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002465
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002466 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002467
2468 def max(self, other, context=None):
2469 """Returns the larger value.
2470
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002471 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002472 NaN (and signals if one is sNaN). Also rounds.
2473 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002474 other = _convert_other(other, raiseit=True)
2475
2476 if context is None:
2477 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002478
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002479 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002480 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002481 # number is always returned
2482 sn = self._isnan()
2483 on = other._isnan()
2484 if sn or on:
2485 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002486 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002487 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002488 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002489 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002490
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002491 c = self.__cmp__(other)
2492 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002493 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002494 # then an ordering is applied:
2495 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002496 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002497 # positive sign and min returns the operand with the negative sign
2498 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002499 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002500 # the result. This is exactly the ordering used in compare_total.
2501 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002502
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002503 if c == -1:
2504 ans = other
2505 else:
2506 ans = self
2507
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002508 if context._rounding_decision == ALWAYS_ROUND:
2509 return ans._fix(context)
2510 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002511
2512 def min(self, other, context=None):
2513 """Returns the smaller value.
2514
Guido van Rossumd8faa362007-04-27 19:54:29 +00002515 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002516 NaN (and signals if one is sNaN). Also rounds.
2517 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002518 other = _convert_other(other, raiseit=True)
2519
2520 if context is None:
2521 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002522
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002523 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002524 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002525 # number is always returned
2526 sn = self._isnan()
2527 on = other._isnan()
2528 if sn or on:
2529 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002530 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002531 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002532 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002533 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002534
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002535 c = self.__cmp__(other)
2536 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002537 c = self.compare_total(other)
2538
2539 if c == -1:
2540 ans = self
2541 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002542 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002543
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002544 if context._rounding_decision == ALWAYS_ROUND:
2545 return ans._fix(context)
2546 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002547
2548 def _isinteger(self):
2549 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002550 if self._is_special:
2551 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002552 if self._exp >= 0:
2553 return True
2554 rest = self._int[self._exp:]
2555 return rest == (0,)*len(rest)
2556
2557 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002558 """Returns True if self is even. Assumes self is an integer."""
2559 if not self or self._exp > 0:
2560 return True
Raymond Hettinger61992ef2004-08-06 23:42:16 +00002561 return self._int[-1+self._exp] & 1 == 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002562
2563 def adjusted(self):
2564 """Return the adjusted exponent of self"""
2565 try:
2566 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002567 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002568 except TypeError:
2569 return 0
2570
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002571 def canonical(self, context=None):
2572 """Returns the same Decimal object.
2573
2574 As we do not have different encodings for the same number, the
2575 received object already is in its canonical form.
2576 """
2577 return self
2578
2579 def compare_signal(self, other, context=None):
2580 """Compares self to the other operand numerically.
2581
2582 It's pretty much like compare(), but all NaNs signal, with signaling
2583 NaNs taking precedence over quiet NaNs.
2584 """
2585 if context is None:
2586 context = getcontext()
2587
2588 self_is_nan = self._isnan()
2589 other_is_nan = other._isnan()
2590 if self_is_nan == 2:
2591 return context._raise_error(InvalidOperation, 'sNaN',
2592 1, self)
2593 if other_is_nan == 2:
2594 return context._raise_error(InvalidOperation, 'sNaN',
2595 1, other)
2596 if self_is_nan:
2597 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2598 1, self)
2599 if other_is_nan:
2600 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2601 1, other)
2602 return self.compare(other, context=context)
2603
2604 def compare_total(self, other):
2605 """Compares self to other using the abstract representations.
2606
2607 This is not like the standard compare, which use their numerical
2608 value. Note that a total ordering is defined for all possible abstract
2609 representations.
2610 """
2611 # if one is negative and the other is positive, it's easy
2612 if self._sign and not other._sign:
2613 return Dec_n1
2614 if not self._sign and other._sign:
2615 return Dec_p1
2616 sign = self._sign
2617
2618 # let's handle both NaN types
2619 self_nan = self._isnan()
2620 other_nan = other._isnan()
2621 if self_nan or other_nan:
2622 if self_nan == other_nan:
2623 if self._int < other._int:
2624 if sign:
2625 return Dec_p1
2626 else:
2627 return Dec_n1
2628 if self._int > other._int:
2629 if sign:
2630 return Dec_n1
2631 else:
2632 return Dec_p1
2633 return Dec_0
2634
2635 if sign:
2636 if self_nan == 1:
2637 return Dec_n1
2638 if other_nan == 1:
2639 return Dec_p1
2640 if self_nan == 2:
2641 return Dec_n1
2642 if other_nan == 2:
2643 return Dec_p1
2644 else:
2645 if self_nan == 1:
2646 return Dec_p1
2647 if other_nan == 1:
2648 return Dec_n1
2649 if self_nan == 2:
2650 return Dec_p1
2651 if other_nan == 2:
2652 return Dec_n1
2653
2654 if self < other:
2655 return Dec_n1
2656 if self > other:
2657 return Dec_p1
2658
2659 if self._exp < other._exp:
2660 if sign:
2661 return Dec_p1
2662 else:
2663 return Dec_n1
2664 if self._exp > other._exp:
2665 if sign:
2666 return Dec_n1
2667 else:
2668 return Dec_p1
2669 return Dec_0
2670
2671
2672 def compare_total_mag(self, other):
2673 """Compares self to other using abstract repr., ignoring sign.
2674
2675 Like compare_total, but with operand's sign ignored and assumed to be 0.
2676 """
2677 s = self.copy_abs()
2678 o = other.copy_abs()
2679 return s.compare_total(o)
2680
2681 def copy_abs(self):
2682 """Returns a copy with the sign set to 0. """
2683 return Decimal((0, self._int, self._exp))
2684
2685 def copy_negate(self):
2686 """Returns a copy with the sign inverted."""
2687 if self._sign:
2688 return Decimal((0, self._int, self._exp))
2689 else:
2690 return Decimal((1, self._int, self._exp))
2691
2692 def copy_sign(self, other):
2693 """Returns self with the sign of other."""
2694 return Decimal((other._sign, self._int, self._exp))
2695
2696 def exp(self, context=None):
2697 """Returns e ** self."""
2698
2699 if context is None:
2700 context = getcontext()
2701
2702 # exp(NaN) = NaN
2703 ans = self._check_nans(context=context)
2704 if ans:
2705 return ans
2706
2707 # exp(-Infinity) = 0
2708 if self._isinfinity() == -1:
2709 return Dec_0
2710
2711 # exp(0) = 1
2712 if not self:
2713 return Dec_p1
2714
2715 # exp(Infinity) = Infinity
2716 if self._isinfinity() == 1:
2717 return Decimal(self)
2718
2719 # the result is now guaranteed to be inexact (the true
2720 # mathematical result is transcendental). There's no need to
2721 # raise Rounded and Inexact here---they'll always be raised as
2722 # a result of the call to _fix.
2723 p = context.prec
2724 adj = self.adjusted()
2725
2726 # we only need to do any computation for quite a small range
2727 # of adjusted exponents---for example, -29 <= adj <= 10 for
2728 # the default context. For smaller exponent the result is
2729 # indistinguishable from 1 at the given precision, while for
2730 # larger exponent the result either overflows or underflows.
2731 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2732 # overflow
2733 ans = Decimal((0, (1,), context.Emax+1))
2734 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2735 # underflow to 0
2736 ans = Decimal((0, (1,), context.Etiny()-1))
2737 elif self._sign == 0 and adj < -p:
2738 # p+1 digits; final round will raise correct flags
2739 ans = Decimal((0, (1,) + (0,)*(p-1) + (1,), -p))
2740 elif self._sign == 1 and adj < -p-1:
2741 # p+1 digits; final round will raise correct flags
2742 ans = Decimal((0, (9,)*(p+1), -p-1))
2743 # general case
2744 else:
2745 op = _WorkRep(self)
2746 c, e = op.int, op.exp
2747 if op.sign == 1:
2748 c = -c
2749
2750 # compute correctly rounded result: increase precision by
2751 # 3 digits at a time until we get an unambiguously
2752 # roundable result
2753 extra = 3
2754 while True:
2755 coeff, exp = _dexp(c, e, p+extra)
2756 if coeff % (5*10**(len(str(coeff))-p-1)):
2757 break
2758 extra += 3
2759
2760 ans = Decimal((0, list(map(int, str(coeff))), exp))
2761
2762 # at this stage, ans should round correctly with *any*
2763 # rounding mode, not just with ROUND_HALF_EVEN
2764 context = context._shallow_copy()
2765 rounding = context._set_rounding(ROUND_HALF_EVEN)
2766 ans = ans._fix(context)
2767 context.rounding = rounding
2768
2769 return ans
2770
2771 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002772 """Return True if self is canonical; otherwise return False.
2773
2774 Currently, the encoding of a Decimal instance is always
2775 canonical, so this method returns True for any Decimal.
2776 """
2777 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002778
2779 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002780 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002781
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002782 A Decimal instance is considered finite if it is neither
2783 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002784 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002785 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002786
2787 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002788 """Return True if self is infinite; otherwise return False."""
2789 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002790
2791 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002792 """Return True if self is a qNaN or sNaN; otherwise return False."""
2793 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002794
2795 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002796 """Return True if self is a normal number; otherwise return False."""
2797 if self._is_special or not self:
2798 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002799 if context is None:
2800 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002801 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002802
2803 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002804 """Return True if self is a quiet NaN; otherwise return False."""
2805 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002806
2807 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002808 """Return True if self is negative; otherwise return False."""
2809 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002810
2811 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002812 """Return True if self is a signaling NaN; otherwise return False."""
2813 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002814
2815 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002816 """Return True if self is subnormal; otherwise return False."""
2817 if self._is_special or not self:
2818 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002819 if context is None:
2820 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002821 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002822
2823 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002824 """Return True if self is a zero; otherwise return False."""
2825 return not self._is_special and self._int[0] == 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002826
2827 def _ln_exp_bound(self):
2828 """Compute a lower bound for the adjusted exponent of self.ln().
2829 In other words, compute r such that self.ln() >= 10**r. Assumes
2830 that self is finite and positive and that self != 1.
2831 """
2832
2833 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2834 adj = self._exp + len(self._int) - 1
2835 if adj >= 1:
2836 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2837 return len(str(adj*23//10)) - 1
2838 if adj <= -2:
2839 # argument <= 0.1
2840 return len(str((-1-adj)*23//10)) - 1
2841 op = _WorkRep(self)
2842 c, e = op.int, op.exp
2843 if adj == 0:
2844 # 1 < self < 10
2845 num = str(c-10**-e)
2846 den = str(c)
2847 return len(num) - len(den) - (num < den)
2848 # adj == -1, 0.1 <= self < 1
2849 return e + len(str(10**-e - c)) - 1
2850
2851
2852 def ln(self, context=None):
2853 """Returns the natural (base e) logarithm of self."""
2854
2855 if context is None:
2856 context = getcontext()
2857
2858 # ln(NaN) = NaN
2859 ans = self._check_nans(context=context)
2860 if ans:
2861 return ans
2862
2863 # ln(0.0) == -Infinity
2864 if not self:
2865 return negInf
2866
2867 # ln(Infinity) = Infinity
2868 if self._isinfinity() == 1:
2869 return Inf
2870
2871 # ln(1.0) == 0.0
2872 if self == Dec_p1:
2873 return Dec_0
2874
2875 # ln(negative) raises InvalidOperation
2876 if self._sign == 1:
2877 return context._raise_error(InvalidOperation,
2878 'ln of a negative value')
2879
2880 # result is irrational, so necessarily inexact
2881 op = _WorkRep(self)
2882 c, e = op.int, op.exp
2883 p = context.prec
2884
2885 # correctly rounded result: repeatedly increase precision by 3
2886 # until we get an unambiguously roundable result
2887 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2888 while True:
2889 coeff = _dlog(c, e, places)
2890 # assert len(str(abs(coeff)))-p >= 1
2891 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2892 break
2893 places += 3
2894 ans = Decimal((int(coeff<0), list(map(int, str(abs(coeff)))), -places))
2895
2896 context = context._shallow_copy()
2897 rounding = context._set_rounding(ROUND_HALF_EVEN)
2898 ans = ans._fix(context)
2899 context.rounding = rounding
2900 return ans
2901
2902 def _log10_exp_bound(self):
2903 """Compute a lower bound for the adjusted exponent of self.log10().
2904 In other words, find r such that self.log10() >= 10**r.
2905 Assumes that self is finite and positive and that self != 1.
2906 """
2907
2908 # For x >= 10 or x < 0.1 we only need a bound on the integer
2909 # part of log10(self), and this comes directly from the
2910 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2911 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2912 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2913
2914 adj = self._exp + len(self._int) - 1
2915 if adj >= 1:
2916 # self >= 10
2917 return len(str(adj))-1
2918 if adj <= -2:
2919 # self < 0.1
2920 return len(str(-1-adj))-1
2921 op = _WorkRep(self)
2922 c, e = op.int, op.exp
2923 if adj == 0:
2924 # 1 < self < 10
2925 num = str(c-10**-e)
2926 den = str(231*c)
2927 return len(num) - len(den) - (num < den) + 2
2928 # adj == -1, 0.1 <= self < 1
2929 num = str(10**-e-c)
2930 return len(num) + e - (num < "231") - 1
2931
2932 def log10(self, context=None):
2933 """Returns the base 10 logarithm of self."""
2934
2935 if context is None:
2936 context = getcontext()
2937
2938 # log10(NaN) = NaN
2939 ans = self._check_nans(context=context)
2940 if ans:
2941 return ans
2942
2943 # log10(0.0) == -Infinity
2944 if not self:
2945 return negInf
2946
2947 # log10(Infinity) = Infinity
2948 if self._isinfinity() == 1:
2949 return Inf
2950
2951 # log10(negative or -Infinity) raises InvalidOperation
2952 if self._sign == 1:
2953 return context._raise_error(InvalidOperation,
2954 'log10 of a negative value')
2955
2956 # log10(10**n) = n
2957 if self._int[0] == 1 and self._int[1:] == (0,)*(len(self._int) - 1):
2958 # answer may need rounding
2959 ans = Decimal(self._exp + len(self._int) - 1)
2960 else:
2961 # result is irrational, so necessarily inexact
2962 op = _WorkRep(self)
2963 c, e = op.int, op.exp
2964 p = context.prec
2965
2966 # correctly rounded result: repeatedly increase precision
2967 # until result is unambiguously roundable
2968 places = p-self._log10_exp_bound()+2
2969 while True:
2970 coeff = _dlog10(c, e, places)
2971 # assert len(str(abs(coeff)))-p >= 1
2972 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2973 break
2974 places += 3
2975 ans = Decimal((int(coeff<0), list(map(int, str(abs(coeff)))),
2976 -places))
2977
2978 context = context._shallow_copy()
2979 rounding = context._set_rounding(ROUND_HALF_EVEN)
2980 ans = ans._fix(context)
2981 context.rounding = rounding
2982 return ans
2983
2984 def logb(self, context=None):
2985 """ Returns the exponent of the magnitude of self's MSD.
2986
2987 The result is the integer which is the exponent of the magnitude
2988 of the most significant digit of self (as though it were truncated
2989 to a single digit while maintaining the value of that digit and
2990 without limiting the resulting exponent).
2991 """
2992 # logb(NaN) = NaN
2993 ans = self._check_nans(context=context)
2994 if ans:
2995 return ans
2996
2997 if context is None:
2998 context = getcontext()
2999
3000 # logb(+/-Inf) = +Inf
3001 if self._isinfinity():
3002 return Inf
3003
3004 # logb(0) = -Inf, DivisionByZero
3005 if not self:
3006 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3007
3008 # otherwise, simply return the adjusted exponent of self, as a
3009 # Decimal. Note that no attempt is made to fit the result
3010 # into the current context.
3011 return Decimal(self.adjusted())
3012
3013 def _islogical(self):
3014 """Return True if self is a logical operand.
3015
3016 For being logical, it must be a finite numbers with a sign of 0,
3017 an exponent of 0, and a coefficient whose digits must all be
3018 either 0 or 1.
3019 """
3020 if self._sign != 0 or self._exp != 0:
3021 return False
3022 for dig in self._int:
3023 if dig not in (0, 1):
3024 return False
3025 return True
3026
3027 def _fill_logical(self, context, opa, opb):
3028 dif = context.prec - len(opa)
3029 if dif > 0:
3030 opa = (0,)*dif + opa
3031 elif dif < 0:
3032 opa = opa[-context.prec:]
3033 dif = context.prec - len(opb)
3034 if dif > 0:
3035 opb = (0,)*dif + opb
3036 elif dif < 0:
3037 opb = opb[-context.prec:]
3038 return opa, opb
3039
3040 def logical_and(self, other, context=None):
3041 """Applies an 'and' operation between self and other's digits."""
3042 if context is None:
3043 context = getcontext()
3044 if not self._islogical() or not other._islogical():
3045 return context._raise_error(InvalidOperation)
3046
3047 # fill to context.prec
3048 (opa, opb) = self._fill_logical(context, self._int, other._int)
3049
3050 # make the operation, and clean starting zeroes
3051 result = [a&b for a,b in zip(opa,opb)]
3052 for i,d in enumerate(result):
3053 if d == 1:
3054 break
3055 result = tuple(result[i:])
3056
3057 # if empty, we must have at least a zero
3058 if not result:
3059 result = (0,)
3060 return Decimal((0, result, 0))
3061
3062 def logical_invert(self, context=None):
3063 """Invert all its digits."""
3064 if context is None:
3065 context = getcontext()
3066 return self.logical_xor(Decimal((0,(1,)*context.prec,0)), context)
3067
3068 def logical_or(self, other, context=None):
3069 """Applies an 'or' operation between self and other's digits."""
3070 if context is None:
3071 context = getcontext()
3072 if not self._islogical() or not other._islogical():
3073 return context._raise_error(InvalidOperation)
3074
3075 # fill to context.prec
3076 (opa, opb) = self._fill_logical(context, self._int, other._int)
3077
3078 # make the operation, and clean starting zeroes
3079 result = [a|b for a,b in zip(opa,opb)]
3080 for i,d in enumerate(result):
3081 if d == 1:
3082 break
3083 result = tuple(result[i:])
3084
3085 # if empty, we must have at least a zero
3086 if not result:
3087 result = (0,)
3088 return Decimal((0, result, 0))
3089
3090 def logical_xor(self, other, context=None):
3091 """Applies an 'xor' operation between self and other's digits."""
3092 if context is None:
3093 context = getcontext()
3094 if not self._islogical() or not other._islogical():
3095 return context._raise_error(InvalidOperation)
3096
3097 # fill to context.prec
3098 (opa, opb) = self._fill_logical(context, self._int, other._int)
3099
3100 # make the operation, and clean starting zeroes
3101 result = [a^b for a,b in zip(opa,opb)]
3102 for i,d in enumerate(result):
3103 if d == 1:
3104 break
3105 result = tuple(result[i:])
3106
3107 # if empty, we must have at least a zero
3108 if not result:
3109 result = (0,)
3110 return Decimal((0, result, 0))
3111
3112 def max_mag(self, other, context=None):
3113 """Compares the values numerically with their sign ignored."""
3114 other = _convert_other(other, raiseit=True)
3115
3116 if context is None:
3117 context = getcontext()
3118
3119 if self._is_special or other._is_special:
3120 # If one operand is a quiet NaN and the other is number, then the
3121 # number is always returned
3122 sn = self._isnan()
3123 on = other._isnan()
3124 if sn or on:
3125 if on == 1 and sn != 2:
3126 return self._fix_nan(context)
3127 if sn == 1 and on != 2:
3128 return other._fix_nan(context)
3129 return self._check_nans(other, context)
3130
3131 c = self.copy_abs().__cmp__(other.copy_abs())
3132 if c == 0:
3133 c = self.compare_total(other)
3134
3135 if c == -1:
3136 ans = other
3137 else:
3138 ans = self
3139
3140 if context._rounding_decision == ALWAYS_ROUND:
3141 return ans._fix(context)
3142 return ans
3143
3144 def min_mag(self, other, context=None):
3145 """Compares the values numerically with their sign ignored."""
3146 other = _convert_other(other, raiseit=True)
3147
3148 if context is None:
3149 context = getcontext()
3150
3151 if self._is_special or other._is_special:
3152 # If one operand is a quiet NaN and the other is number, then the
3153 # number is always returned
3154 sn = self._isnan()
3155 on = other._isnan()
3156 if sn or on:
3157 if on == 1 and sn != 2:
3158 return self._fix_nan(context)
3159 if sn == 1 and on != 2:
3160 return other._fix_nan(context)
3161 return self._check_nans(other, context)
3162
3163 c = self.copy_abs().__cmp__(other.copy_abs())
3164 if c == 0:
3165 c = self.compare_total(other)
3166
3167 if c == -1:
3168 ans = self
3169 else:
3170 ans = other
3171
3172 if context._rounding_decision == ALWAYS_ROUND:
3173 return ans._fix(context)
3174 return ans
3175
3176 def next_minus(self, context=None):
3177 """Returns the largest representable number smaller than itself."""
3178 if context is None:
3179 context = getcontext()
3180
3181 ans = self._check_nans(context=context)
3182 if ans:
3183 return ans
3184
3185 if self._isinfinity() == -1:
3186 return negInf
3187 if self._isinfinity() == 1:
3188 return Decimal((0, (9,)*context.prec, context.Etop()))
3189
3190 context = context.copy()
3191 context._set_rounding(ROUND_FLOOR)
3192 context._ignore_all_flags()
3193 new_self = self._fix(context)
3194 if new_self != self:
3195 return new_self
3196 return self.__sub__(Decimal((0, (1,), context.Etiny()-1)), context)
3197
3198 def next_plus(self, context=None):
3199 """Returns the smallest representable number larger than itself."""
3200 if context is None:
3201 context = getcontext()
3202
3203 ans = self._check_nans(context=context)
3204 if ans:
3205 return ans
3206
3207 if self._isinfinity() == 1:
3208 return Inf
3209 if self._isinfinity() == -1:
3210 return Decimal((1, (9,)*context.prec, context.Etop()))
3211
3212 context = context.copy()
3213 context._set_rounding(ROUND_CEILING)
3214 context._ignore_all_flags()
3215 new_self = self._fix(context)
3216 if new_self != self:
3217 return new_self
3218 return self.__add__(Decimal((0, (1,), context.Etiny()-1)), context)
3219
3220 def next_toward(self, other, context=None):
3221 """Returns the number closest to self, in the direction towards other.
3222
3223 The result is the closest representable number to self
3224 (excluding self) that is in the direction towards other,
3225 unless both have the same value. If the two operands are
3226 numerically equal, then the result is a copy of self with the
3227 sign set to be the same as the sign of other.
3228 """
3229 other = _convert_other(other, raiseit=True)
3230
3231 if context is None:
3232 context = getcontext()
3233
3234 ans = self._check_nans(other, context)
3235 if ans:
3236 return ans
3237
3238 comparison = self.__cmp__(other)
3239 if comparison == 0:
3240 return Decimal((other._sign, self._int, self._exp))
3241
3242 if comparison == -1:
3243 ans = self.next_plus(context)
3244 else: # comparison == 1
3245 ans = self.next_minus(context)
3246
3247 # decide which flags to raise using value of ans
3248 if ans._isinfinity():
3249 context._raise_error(Overflow,
3250 'Infinite result from next_toward',
3251 ans._sign)
3252 context._raise_error(Rounded)
3253 context._raise_error(Inexact)
3254 elif ans.adjusted() < context.Emin:
3255 context._raise_error(Underflow)
3256 context._raise_error(Subnormal)
3257 context._raise_error(Rounded)
3258 context._raise_error(Inexact)
3259 # if precision == 1 then we don't raise Clamped for a
3260 # result 0E-Etiny.
3261 if not ans:
3262 context._raise_error(Clamped)
3263
3264 return ans
3265
3266 def number_class(self, context=None):
3267 """Returns an indication of the class of self.
3268
3269 The class is one of the following strings:
3270 -sNaN
3271 -NaN
3272 -Infinity
3273 -Normal
3274 -Subnormal
3275 -Zero
3276 +Zero
3277 +Subnormal
3278 +Normal
3279 +Infinity
3280 """
3281 if self.is_snan():
3282 return "sNaN"
3283 if self.is_qnan():
3284 return "NaN"
3285 inf = self._isinfinity()
3286 if inf == 1:
3287 return "+Infinity"
3288 if inf == -1:
3289 return "-Infinity"
3290 if self.is_zero():
3291 if self._sign:
3292 return "-Zero"
3293 else:
3294 return "+Zero"
3295 if context is None:
3296 context = getcontext()
3297 if self.is_subnormal(context=context):
3298 if self._sign:
3299 return "-Subnormal"
3300 else:
3301 return "+Subnormal"
3302 # just a normal, regular, boring number, :)
3303 if self._sign:
3304 return "-Normal"
3305 else:
3306 return "+Normal"
3307
3308 def radix(self):
3309 """Just returns 10, as this is Decimal, :)"""
3310 return Decimal(10)
3311
3312 def rotate(self, other, context=None):
3313 """Returns a rotated copy of self, value-of-other times."""
3314 if context is None:
3315 context = getcontext()
3316
3317 ans = self._check_nans(other, context)
3318 if ans:
3319 return ans
3320
3321 if other._exp != 0:
3322 return context._raise_error(InvalidOperation)
3323 if not (-context.prec <= int(other) <= context.prec):
3324 return context._raise_error(InvalidOperation)
3325
3326 if self._isinfinity():
3327 return Decimal(self)
3328
3329 # get values, pad if necessary
3330 torot = int(other)
3331 rotdig = self._int
3332 topad = context.prec - len(rotdig)
3333 if topad:
3334 rotdig = ((0,)*topad) + rotdig
3335
3336 # let's rotate!
3337 rotated = rotdig[torot:] + rotdig[:torot]
3338
3339 # clean starting zeroes
3340 for i,d in enumerate(rotated):
3341 if d != 0:
3342 break
3343 rotated = rotated[i:]
3344
3345 return Decimal((self._sign, rotated, self._exp))
3346
3347
3348 def scaleb (self, other, context=None):
3349 """Returns self operand after adding the second value to its exp."""
3350 if context is None:
3351 context = getcontext()
3352
3353 ans = self._check_nans(other, context)
3354 if ans:
3355 return ans
3356
3357 if other._exp != 0:
3358 return context._raise_error(InvalidOperation)
3359 liminf = -2 * (context.Emax + context.prec)
3360 limsup = 2 * (context.Emax + context.prec)
3361 if not (liminf <= int(other) <= limsup):
3362 return context._raise_error(InvalidOperation)
3363
3364 if self._isinfinity():
3365 return Decimal(self)
3366
3367 d = Decimal((self._sign, self._int, self._exp + int(other)))
3368 d = d._fix(context)
3369 return d
3370
3371 def shift(self, other, context=None):
3372 """Returns a shifted copy of self, value-of-other times."""
3373 if context is None:
3374 context = getcontext()
3375
3376 ans = self._check_nans(other, context)
3377 if ans:
3378 return ans
3379
3380 if other._exp != 0:
3381 return context._raise_error(InvalidOperation)
3382 if not (-context.prec <= int(other) <= context.prec):
3383 return context._raise_error(InvalidOperation)
3384
3385 if self._isinfinity():
3386 return Decimal(self)
3387
3388 # get values, pad if necessary
3389 torot = int(other)
3390 if not torot:
3391 return Decimal(self)
3392 rotdig = self._int
3393 topad = context.prec - len(rotdig)
3394 if topad:
3395 rotdig = ((0,)*topad) + rotdig
3396
3397 # let's shift!
3398 if torot < 0:
3399 rotated = rotdig[:torot]
3400 else:
3401 rotated = (rotdig + ((0,) * torot))
3402 rotated = rotated[-context.prec:]
3403
3404 # clean starting zeroes
3405 if rotated:
3406 for i,d in enumerate(rotated):
3407 if d != 0:
3408 break
3409 rotated = rotated[i:]
3410 else:
3411 rotated = (0,)
3412
3413 return Decimal((self._sign, rotated, self._exp))
3414
3415
Guido van Rossumd8faa362007-04-27 19:54:29 +00003416 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003417 def __reduce__(self):
3418 return (self.__class__, (str(self),))
3419
3420 def __copy__(self):
3421 if type(self) == Decimal:
3422 return self # I'm immutable; therefore I am my own clone
3423 return self.__class__(str(self))
3424
3425 def __deepcopy__(self, memo):
3426 if type(self) == Decimal:
3427 return self # My components are also immutable
3428 return self.__class__(str(self))
3429
Guido van Rossumd8faa362007-04-27 19:54:29 +00003430##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003431
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003432
3433# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003434rounding_functions = [name for name in Decimal.__dict__.keys()
3435 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003436for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003437 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003438 globalname = name[1:].upper()
3439 val = globals()[globalname]
3440 Decimal._pick_rounding_function[val] = name
3441
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003442del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003443
Thomas Wouters89f507f2006-12-13 04:49:30 +00003444class _ContextManager(object):
3445 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003446
Thomas Wouters89f507f2006-12-13 04:49:30 +00003447 Sets a copy of the supplied context in __enter__() and restores
3448 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003449 """
3450 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003451 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003452 def __enter__(self):
3453 self.saved_context = getcontext()
3454 setcontext(self.new_context)
3455 return self.new_context
3456 def __exit__(self, t, v, tb):
3457 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003458
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003459class Context(object):
3460 """Contains the context for a Decimal instance.
3461
3462 Contains:
3463 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003464 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003465 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003466 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003467 raised when it is caused. Otherwise, a value is
3468 substituted in.
3469 flags - When an exception is caused, flags[exception] is incremented.
3470 (Whether or not the trap_enabler is set)
3471 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003472 Emin - Minimum exponent
3473 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003474 capitals - If 1, 1*10^1 is printed as 1E+1.
3475 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003476 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003477 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003478
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003479 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003480 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003481 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003482 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003483 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003484 _ignored_flags=None):
3485 if flags is None:
3486 flags = []
3487 if _ignored_flags is None:
3488 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003489 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003490 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003491 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003492 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003493 for name, val in locals().items():
3494 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003495 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003496 else:
3497 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003498 del self.self
3499
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003500 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003501 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003502 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003503 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3504 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3505 % vars(self))
3506 names = [f.__name__ for f, v in self.flags.items() if v]
3507 s.append('flags=[' + ', '.join(names) + ']')
3508 names = [t.__name__ for t, v in self.traps.items() if v]
3509 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003510 return ', '.join(s) + ')'
3511
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003512 def clear_flags(self):
3513 """Reset all flags to zero"""
3514 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003515 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003516
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003517 def _shallow_copy(self):
3518 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003519 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003520 self._rounding_decision, self.Emin, self.Emax,
3521 self.capitals, self._clamp, self._ignored_flags)
3522 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003523
3524 def copy(self):
3525 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003526 nc = Context(self.prec, self.rounding, self.traps.copy(),
3527 self.flags.copy(), self._rounding_decision, self.Emin,
3528 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003529 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003530 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003531
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003532 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003533 """Handles an error
3534
3535 If the flag is in _ignored_flags, returns the default response.
3536 Otherwise, it increments the flag, then, if the corresponding
3537 trap_enabler is set, it reaises the exception. Otherwise, it returns
3538 the default value after incrementing the flag.
3539 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003540 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003541 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003542 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003543 return error().handle(self, *args)
3544
3545 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003546 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003547 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003548 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003549
3550 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003551 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003552 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003553
3554 def _ignore_all_flags(self):
3555 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003556 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003557
3558 def _ignore_flags(self, *flags):
3559 """Ignore the flags, if they are raised"""
3560 # Do not mutate-- This way, copies of a context leave the original
3561 # alone.
3562 self._ignored_flags = (self._ignored_flags + list(flags))
3563 return list(flags)
3564
3565 def _regard_flags(self, *flags):
3566 """Stop ignoring the flags, if they are raised"""
3567 if flags and isinstance(flags[0], (tuple,list)):
3568 flags = flags[0]
3569 for flag in flags:
3570 self._ignored_flags.remove(flag)
3571
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003572 def __hash__(self):
3573 """A Context cannot be hashed."""
3574 # We inherit object.__hash__, so we must deny this explicitly
Guido van Rossumd8faa362007-04-27 19:54:29 +00003575 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003576
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003577 def Etiny(self):
3578 """Returns Etiny (= Emin - prec + 1)"""
3579 return int(self.Emin - self.prec + 1)
3580
3581 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003582 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003583 return int(self.Emax - self.prec + 1)
3584
3585 def _set_rounding_decision(self, type):
3586 """Sets the rounding decision.
3587
3588 Sets the rounding decision, and returns the current (previous)
3589 rounding decision. Often used like:
3590
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003591 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003592 # That so you don't change the calling context
3593 # if an error occurs in the middle (say DivisionImpossible is raised).
3594
3595 rounding = context._set_rounding_decision(NEVER_ROUND)
3596 instance = instance / Decimal(2)
3597 context._set_rounding_decision(rounding)
3598
3599 This will make it not round for that operation.
3600 """
3601
3602 rounding = self._rounding_decision
3603 self._rounding_decision = type
3604 return rounding
3605
3606 def _set_rounding(self, type):
3607 """Sets the rounding type.
3608
3609 Sets the rounding type, and returns the current (previous)
3610 rounding type. Often used like:
3611
3612 context = context.copy()
3613 # so you don't change the calling context
3614 # if an error occurs in the middle.
3615 rounding = context._set_rounding(ROUND_UP)
3616 val = self.__sub__(other, context=context)
3617 context._set_rounding(rounding)
3618
3619 This will make it round up for that operation.
3620 """
3621 rounding = self.rounding
3622 self.rounding= type
3623 return rounding
3624
Raymond Hettingerfed52962004-07-14 15:41:57 +00003625 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003626 """Creates a new Decimal instance but using self as context."""
3627 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003628 if d._isnan() and len(d._int) > self.prec - self._clamp:
3629 return self._raise_error(ConversionSyntax,
3630 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003631 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003632
Guido van Rossumd8faa362007-04-27 19:54:29 +00003633 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003634 def abs(self, a):
3635 """Returns the absolute value of the operand.
3636
3637 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003638 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003639 the plus operation on the operand.
3640
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003641 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003642 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003643 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003644 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003645 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003646 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003647 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003648 Decimal("101.5")
3649 """
3650 return a.__abs__(context=self)
3651
3652 def add(self, a, b):
3653 """Return the sum of the two operands.
3654
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003655 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003656 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003657 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003658 Decimal("1.02E+4")
3659 """
3660 return a.__add__(b, context=self)
3661
3662 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003663 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003664
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003665 def canonical(self, a):
3666 """Returns the same Decimal object.
3667
3668 As we do not have different encodings for the same number, the
3669 received object already is in its canonical form.
3670
3671 >>> ExtendedContext.canonical(Decimal('2.50'))
3672 Decimal("2.50")
3673 """
3674 return a.canonical(context=self)
3675
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003676 def compare(self, a, b):
3677 """Compares values numerically.
3678
3679 If the signs of the operands differ, a value representing each operand
3680 ('-1' if the operand is less than zero, '0' if the operand is zero or
3681 negative zero, or '1' if the operand is greater than zero) is used in
3682 place of that operand for the comparison instead of the actual
3683 operand.
3684
3685 The comparison is then effected by subtracting the second operand from
3686 the first and then returning a value according to the result of the
3687 subtraction: '-1' if the result is less than zero, '0' if the result is
3688 zero or negative zero, or '1' if the result is greater than zero.
3689
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003690 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003691 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003692 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003693 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003694 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003695 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003696 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003697 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003698 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003699 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003700 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003701 Decimal("-1")
3702 """
3703 return a.compare(b, context=self)
3704
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003705 def compare_signal(self, a, b):
3706 """Compares the values of the two operands numerically.
3707
3708 It's pretty much like compare(), but all NaNs signal, with signaling
3709 NaNs taking precedence over quiet NaNs.
3710
3711 >>> c = ExtendedContext
3712 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3713 Decimal("-1")
3714 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3715 Decimal("0")
3716 >>> c.flags[InvalidOperation] = 0
3717 >>> print(c.flags[InvalidOperation])
3718 0
3719 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3720 Decimal("NaN")
3721 >>> print(c.flags[InvalidOperation])
3722 1
3723 >>> c.flags[InvalidOperation] = 0
3724 >>> print(c.flags[InvalidOperation])
3725 0
3726 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3727 Decimal("NaN")
3728 >>> print(c.flags[InvalidOperation])
3729 1
3730 """
3731 return a.compare_signal(b, context=self)
3732
3733 def compare_total(self, a, b):
3734 """Compares two operands using their abstract representation.
3735
3736 This is not like the standard compare, which use their numerical
3737 value. Note that a total ordering is defined for all possible abstract
3738 representations.
3739
3740 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3741 Decimal("-1")
3742 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3743 Decimal("-1")
3744 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3745 Decimal("-1")
3746 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3747 Decimal("0")
3748 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3749 Decimal("1")
3750 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3751 Decimal("-1")
3752 """
3753 return a.compare_total(b)
3754
3755 def compare_total_mag(self, a, b):
3756 """Compares two operands using their abstract representation ignoring sign.
3757
3758 Like compare_total, but with operand's sign ignored and assumed to be 0.
3759 """
3760 return a.compare_total_mag(b)
3761
3762 def copy_abs(self, a):
3763 """Returns a copy of the operand with the sign set to 0.
3764
3765 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3766 Decimal("2.1")
3767 >>> ExtendedContext.copy_abs(Decimal('-100'))
3768 Decimal("100")
3769 """
3770 return a.copy_abs()
3771
3772 def copy_decimal(self, a):
3773 """Returns a copy of the decimal objet.
3774
3775 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3776 Decimal("2.1")
3777 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3778 Decimal("-1.00")
3779 """
3780 return Decimal(a)
3781
3782 def copy_negate(self, a):
3783 """Returns a copy of the operand with the sign inverted.
3784
3785 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3786 Decimal("-101.5")
3787 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3788 Decimal("101.5")
3789 """
3790 return a.copy_negate()
3791
3792 def copy_sign(self, a, b):
3793 """Copies the second operand's sign to the first one.
3794
3795 In detail, it returns a copy of the first operand with the sign
3796 equal to the sign of the second operand.
3797
3798 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3799 Decimal("1.50")
3800 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3801 Decimal("1.50")
3802 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3803 Decimal("-1.50")
3804 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3805 Decimal("-1.50")
3806 """
3807 return a.copy_sign(b)
3808
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003809 def divide(self, a, b):
3810 """Decimal division in a specified context.
3811
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003812 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003813 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003814 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003815 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003816 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003817 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003818 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003819 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003820 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003821 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003822 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003823 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003824 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003825 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003826 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003827 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003828 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003829 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003830 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003831 Decimal("1.20E+6")
3832 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003833 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003834
3835 def divide_int(self, a, b):
3836 """Divides two numbers and returns the integer part of the result.
3837
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003838 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003839 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003840 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003841 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003842 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003843 Decimal("3")
3844 """
3845 return a.__floordiv__(b, context=self)
3846
3847 def divmod(self, a, b):
3848 return a.__divmod__(b, context=self)
3849
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003850 def exp(self, a):
3851 """Returns e ** a.
3852
3853 >>> c = ExtendedContext.copy()
3854 >>> c.Emin = -999
3855 >>> c.Emax = 999
3856 >>> c.exp(Decimal('-Infinity'))
3857 Decimal("0")
3858 >>> c.exp(Decimal('-1'))
3859 Decimal("0.367879441")
3860 >>> c.exp(Decimal('0'))
3861 Decimal("1")
3862 >>> c.exp(Decimal('1'))
3863 Decimal("2.71828183")
3864 >>> c.exp(Decimal('0.693147181'))
3865 Decimal("2.00000000")
3866 >>> c.exp(Decimal('+Infinity'))
3867 Decimal("Infinity")
3868 """
3869 return a.exp(context=self)
3870
3871 def fma(self, a, b, c):
3872 """Returns a multiplied by b, plus c.
3873
3874 The first two operands are multiplied together, using multiply,
3875 the third operand is then added to the result of that
3876 multiplication, using add, all with only one final rounding.
3877
3878 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3879 Decimal("22")
3880 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3881 Decimal("-8")
3882 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3883 Decimal("1.38435736E+12")
3884 """
3885 return a.fma(b, c, context=self)
3886
3887 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003888 """Return True if the operand is canonical; otherwise return False.
3889
3890 Currently, the encoding of a Decimal instance is always
3891 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003892
3893 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003894 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003895 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003896 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003897
3898 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003899 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003900
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003901 A Decimal instance is considered finite if it is neither
3902 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003903
3904 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003905 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003906 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003907 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003908 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003909 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003910 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003911 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003912 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003913 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003914 """
3915 return a.is_finite()
3916
3917 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003918 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003919
3920 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003921 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003922 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003923 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003924 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003925 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003926 """
3927 return a.is_infinite()
3928
3929 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003930 """Return True if the operand is a qNaN or sNaN;
3931 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003932
3933 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003934 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003935 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003936 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003937 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003938 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003939 """
3940 return a.is_nan()
3941
3942 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003943 """Return True if the operand is a normal number;
3944 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003945
3946 >>> c = ExtendedContext.copy()
3947 >>> c.Emin = -999
3948 >>> c.Emax = 999
3949 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003950 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003951 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003952 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003953 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003954 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003955 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003956 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003957 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003958 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003959 """
3960 return a.is_normal(context=self)
3961
3962 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003963 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003964
3965 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003966 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003967 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003968 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003969 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003970 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003971 """
3972 return a.is_qnan()
3973
3974 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003975 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003976
3977 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003978 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003979 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003980 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003981 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003982 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003983 """
3984 return a.is_signed()
3985
3986 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003987 """Return True if the operand is a signaling NaN;
3988 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003989
3990 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003991 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003992 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003993 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003994 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003995 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003996 """
3997 return a.is_snan()
3998
3999 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004000 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004001
4002 >>> c = ExtendedContext.copy()
4003 >>> c.Emin = -999
4004 >>> c.Emax = 999
4005 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004006 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004007 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004008 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004009 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004010 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004011 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004012 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004013 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004014 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004015 """
4016 return a.is_subnormal(context=self)
4017
4018 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004019 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004020
4021 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004022 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004023 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004024 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004025 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004026 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004027 """
4028 return a.is_zero()
4029
4030 def ln(self, a):
4031 """Returns the natural (base e) logarithm of the operand.
4032
4033 >>> c = ExtendedContext.copy()
4034 >>> c.Emin = -999
4035 >>> c.Emax = 999
4036 >>> c.ln(Decimal('0'))
4037 Decimal("-Infinity")
4038 >>> c.ln(Decimal('1.000'))
4039 Decimal("0")
4040 >>> c.ln(Decimal('2.71828183'))
4041 Decimal("1.00000000")
4042 >>> c.ln(Decimal('10'))
4043 Decimal("2.30258509")
4044 >>> c.ln(Decimal('+Infinity'))
4045 Decimal("Infinity")
4046 """
4047 return a.ln(context=self)
4048
4049 def log10(self, a):
4050 """Returns the base 10 logarithm of the operand.
4051
4052 >>> c = ExtendedContext.copy()
4053 >>> c.Emin = -999
4054 >>> c.Emax = 999
4055 >>> c.log10(Decimal('0'))
4056 Decimal("-Infinity")
4057 >>> c.log10(Decimal('0.001'))
4058 Decimal("-3")
4059 >>> c.log10(Decimal('1.000'))
4060 Decimal("0")
4061 >>> c.log10(Decimal('2'))
4062 Decimal("0.301029996")
4063 >>> c.log10(Decimal('10'))
4064 Decimal("1")
4065 >>> c.log10(Decimal('70'))
4066 Decimal("1.84509804")
4067 >>> c.log10(Decimal('+Infinity'))
4068 Decimal("Infinity")
4069 """
4070 return a.log10(context=self)
4071
4072 def logb(self, a):
4073 """ Returns the exponent of the magnitude of the operand's MSD.
4074
4075 The result is the integer which is the exponent of the magnitude
4076 of the most significant digit of the operand (as though the
4077 operand were truncated to a single digit while maintaining the
4078 value of that digit and without limiting the resulting exponent).
4079
4080 >>> ExtendedContext.logb(Decimal('250'))
4081 Decimal("2")
4082 >>> ExtendedContext.logb(Decimal('2.50'))
4083 Decimal("0")
4084 >>> ExtendedContext.logb(Decimal('0.03'))
4085 Decimal("-2")
4086 >>> ExtendedContext.logb(Decimal('0'))
4087 Decimal("-Infinity")
4088 """
4089 return a.logb(context=self)
4090
4091 def logical_and(self, a, b):
4092 """Applies the logical operation 'and' between each operand's digits.
4093
4094 The operands must be both logical numbers.
4095
4096 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4097 Decimal("0")
4098 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4099 Decimal("0")
4100 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4101 Decimal("0")
4102 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4103 Decimal("1")
4104 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4105 Decimal("1000")
4106 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4107 Decimal("10")
4108 """
4109 return a.logical_and(b, context=self)
4110
4111 def logical_invert(self, a):
4112 """Invert all the digits in the operand.
4113
4114 The operand must be a logical number.
4115
4116 >>> ExtendedContext.logical_invert(Decimal('0'))
4117 Decimal("111111111")
4118 >>> ExtendedContext.logical_invert(Decimal('1'))
4119 Decimal("111111110")
4120 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4121 Decimal("0")
4122 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4123 Decimal("10101010")
4124 """
4125 return a.logical_invert(context=self)
4126
4127 def logical_or(self, a, b):
4128 """Applies the logical operation 'or' between each operand's digits.
4129
4130 The operands must be both logical numbers.
4131
4132 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4133 Decimal("0")
4134 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4135 Decimal("1")
4136 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4137 Decimal("1")
4138 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4139 Decimal("1")
4140 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4141 Decimal("1110")
4142 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4143 Decimal("1110")
4144 """
4145 return a.logical_or(b, context=self)
4146
4147 def logical_xor(self, a, b):
4148 """Applies the logical operation 'xor' between each operand's digits.
4149
4150 The operands must be both logical numbers.
4151
4152 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4153 Decimal("0")
4154 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4155 Decimal("1")
4156 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4157 Decimal("1")
4158 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4159 Decimal("0")
4160 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4161 Decimal("110")
4162 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4163 Decimal("1101")
4164 """
4165 return a.logical_xor(b, context=self)
4166
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004167 def max(self, a,b):
4168 """max compares two values numerically and returns the maximum.
4169
4170 If either operand is a NaN then the general rules apply.
4171 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004172 operation. If they are numerically equal then the left-hand operand
4173 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004174 infinity) of the two operands is chosen as the result.
4175
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004176 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004177 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004178 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004179 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004180 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004181 Decimal("1")
4182 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4183 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004184 """
4185 return a.max(b, context=self)
4186
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004187 def max_mag(self, a, b):
4188 """Compares the values numerically with their sign ignored."""
4189 return a.max_mag(b, context=self)
4190
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004191 def min(self, a,b):
4192 """min compares two values numerically and returns the minimum.
4193
4194 If either operand is a NaN then the general rules apply.
4195 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004196 operation. If they are numerically equal then the left-hand operand
4197 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004198 infinity) of the two operands is chosen as the result.
4199
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004200 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004201 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004202 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004203 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004204 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004205 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004206 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4207 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004208 """
4209 return a.min(b, context=self)
4210
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004211 def min_mag(self, a, b):
4212 """Compares the values numerically with their sign ignored."""
4213 return a.min_mag(b, context=self)
4214
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004215 def minus(self, a):
4216 """Minus corresponds to unary prefix minus in Python.
4217
4218 The operation is evaluated using the same rules as subtract; the
4219 operation minus(a) is calculated as subtract('0', a) where the '0'
4220 has the same exponent as the operand.
4221
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004222 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004223 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004224 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004225 Decimal("1.3")
4226 """
4227 return a.__neg__(context=self)
4228
4229 def multiply(self, a, b):
4230 """multiply multiplies two operands.
4231
4232 If either operand is a special value then the general rules apply.
4233 Otherwise, the operands are multiplied together ('long multiplication'),
4234 resulting in a number which may be as long as the sum of the lengths
4235 of the two operands.
4236
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004237 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004238 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004239 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004240 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004241 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004242 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004243 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004244 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004245 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004246 Decimal("4.28135971E+11")
4247 """
4248 return a.__mul__(b, context=self)
4249
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004250 def next_minus(self, a):
4251 """Returns the largest representable number smaller than a.
4252
4253 >>> c = ExtendedContext.copy()
4254 >>> c.Emin = -999
4255 >>> c.Emax = 999
4256 >>> ExtendedContext.next_minus(Decimal('1'))
4257 Decimal("0.999999999")
4258 >>> c.next_minus(Decimal('1E-1007'))
4259 Decimal("0E-1007")
4260 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4261 Decimal("-1.00000004")
4262 >>> c.next_minus(Decimal('Infinity'))
4263 Decimal("9.99999999E+999")
4264 """
4265 return a.next_minus(context=self)
4266
4267 def next_plus(self, a):
4268 """Returns the smallest representable number larger than a.
4269
4270 >>> c = ExtendedContext.copy()
4271 >>> c.Emin = -999
4272 >>> c.Emax = 999
4273 >>> ExtendedContext.next_plus(Decimal('1'))
4274 Decimal("1.00000001")
4275 >>> c.next_plus(Decimal('-1E-1007'))
4276 Decimal("-0E-1007")
4277 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4278 Decimal("-1.00000002")
4279 >>> c.next_plus(Decimal('-Infinity'))
4280 Decimal("-9.99999999E+999")
4281 """
4282 return a.next_plus(context=self)
4283
4284 def next_toward(self, a, b):
4285 """Returns the number closest to a, in direction towards b.
4286
4287 The result is the closest representable number from the first
4288 operand (but not the first operand) that is in the direction
4289 towards the second operand, unless the operands have the same
4290 value.
4291
4292 >>> c = ExtendedContext.copy()
4293 >>> c.Emin = -999
4294 >>> c.Emax = 999
4295 >>> c.next_toward(Decimal('1'), Decimal('2'))
4296 Decimal("1.00000001")
4297 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4298 Decimal("-0E-1007")
4299 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4300 Decimal("-1.00000002")
4301 >>> c.next_toward(Decimal('1'), Decimal('0'))
4302 Decimal("0.999999999")
4303 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4304 Decimal("0E-1007")
4305 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4306 Decimal("-1.00000004")
4307 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4308 Decimal("-0.00")
4309 """
4310 return a.next_toward(b, context=self)
4311
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004312 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004313 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004314
4315 Essentially a plus operation with all trailing zeros removed from the
4316 result.
4317
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004318 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004319 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004320 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004321 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004322 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004323 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004324 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004325 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004326 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004327 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004328 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004329 Decimal("0")
4330 """
4331 return a.normalize(context=self)
4332
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004333 def number_class(self, a):
4334 """Returns an indication of the class of the operand.
4335
4336 The class is one of the following strings:
4337 -sNaN
4338 -NaN
4339 -Infinity
4340 -Normal
4341 -Subnormal
4342 -Zero
4343 +Zero
4344 +Subnormal
4345 +Normal
4346 +Infinity
4347
4348 >>> c = Context(ExtendedContext)
4349 >>> c.Emin = -999
4350 >>> c.Emax = 999
4351 >>> c.number_class(Decimal('Infinity'))
4352 '+Infinity'
4353 >>> c.number_class(Decimal('1E-10'))
4354 '+Normal'
4355 >>> c.number_class(Decimal('2.50'))
4356 '+Normal'
4357 >>> c.number_class(Decimal('0.1E-999'))
4358 '+Subnormal'
4359 >>> c.number_class(Decimal('0'))
4360 '+Zero'
4361 >>> c.number_class(Decimal('-0'))
4362 '-Zero'
4363 >>> c.number_class(Decimal('-0.1E-999'))
4364 '-Subnormal'
4365 >>> c.number_class(Decimal('-1E-10'))
4366 '-Normal'
4367 >>> c.number_class(Decimal('-2.50'))
4368 '-Normal'
4369 >>> c.number_class(Decimal('-Infinity'))
4370 '-Infinity'
4371 >>> c.number_class(Decimal('NaN'))
4372 'NaN'
4373 >>> c.number_class(Decimal('-NaN'))
4374 'NaN'
4375 >>> c.number_class(Decimal('sNaN'))
4376 'sNaN'
4377 """
4378 return a.number_class(context=self)
4379
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004380 def plus(self, a):
4381 """Plus corresponds to unary prefix plus in Python.
4382
4383 The operation is evaluated using the same rules as add; the
4384 operation plus(a) is calculated as add('0', a) where the '0'
4385 has the same exponent as the operand.
4386
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004387 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004388 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004389 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004390 Decimal("-1.3")
4391 """
4392 return a.__pos__(context=self)
4393
4394 def power(self, a, b, modulo=None):
4395 """Raises a to the power of b, to modulo if given.
4396
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004397 With two arguments, compute a**b. If a is negative then b
4398 must be integral. The result will be inexact unless b is
4399 integral and the result is finite and can be expressed exactly
4400 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004401
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004402 With three arguments, compute (a**b) % modulo. For the
4403 three argument form, the following restrictions on the
4404 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004405
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004406 - all three arguments must be integral
4407 - b must be nonnegative
4408 - at least one of a or b must be nonzero
4409 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004410
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004411 The result of pow(a, b, modulo) is identical to the result
4412 that would be obtained by computing (a**b) % modulo with
4413 unbounded precision, but is computed more efficiently. It is
4414 always exact.
4415
4416 >>> c = ExtendedContext.copy()
4417 >>> c.Emin = -999
4418 >>> c.Emax = 999
4419 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004420 Decimal("8")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004421 >>> c.power(Decimal('-2'), Decimal('3'))
4422 Decimal("-8")
4423 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004424 Decimal("0.125")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004425 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004426 Decimal("69.7575744")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004427 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4428 Decimal("2.00000000")
4429 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004430 Decimal("0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004431 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004432 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004433 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004434 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004435 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004436 Decimal("-0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004437 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004438 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004439 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004440 Decimal("-Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004441 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004442 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004443 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004444 Decimal("NaN")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004445
4446 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4447 Decimal("11")
4448 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4449 Decimal("-11")
4450 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4451 Decimal("1")
4452 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4453 Decimal("11")
4454 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4455 Decimal("11729830")
4456 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4457 Decimal("-0")
4458 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4459 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004460 """
4461 return a.__pow__(b, modulo, context=self)
4462
4463 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004464 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004465
4466 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004467 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004468 exponent is being increased), multiplied by a positive power of ten (if
4469 the exponent is being decreased), or is unchanged (if the exponent is
4470 already equal to that of the right-hand operand).
4471
4472 Unlike other operations, if the length of the coefficient after the
4473 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004474 operation condition is raised. This guarantees that, unless there is
4475 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004476 equal to that of the right-hand operand.
4477
4478 Also unlike other operations, quantize will never raise Underflow, even
4479 if the result is subnormal and inexact.
4480
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004481 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004482 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004483 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004484 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004485 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004486 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004487 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004488 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004489 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004490 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004491 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004492 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004493 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004494 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004495 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004496 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004497 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004498 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004499 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004500 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004501 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004502 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004503 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004504 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004505 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004506 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004507 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004508 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004509 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004510 Decimal("2E+2")
4511 """
4512 return a.quantize(b, context=self)
4513
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004514 def radix(self):
4515 """Just returns 10, as this is Decimal, :)
4516
4517 >>> ExtendedContext.radix()
4518 Decimal("10")
4519 """
4520 return Decimal(10)
4521
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004522 def remainder(self, a, b):
4523 """Returns the remainder from integer division.
4524
4525 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004526 calculating integer division as described for divide-integer, rounded
4527 to precision digits if necessary. The sign of the result, if
4528 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004529
4530 This operation will fail under the same conditions as integer division
4531 (that is, if integer division on the same two operands would fail, the
4532 remainder cannot be calculated).
4533
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004534 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004535 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004536 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004537 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004538 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004539 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004540 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004541 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004542 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004543 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004544 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004545 Decimal("1.0")
4546 """
4547 return a.__mod__(b, context=self)
4548
4549 def remainder_near(self, a, b):
4550 """Returns to be "a - b * n", where n is the integer nearest the exact
4551 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004552 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004553 sign of a.
4554
4555 This operation will fail under the same conditions as integer division
4556 (that is, if integer division on the same two operands would fail, the
4557 remainder cannot be calculated).
4558
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004559 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004560 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004561 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004562 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004563 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004564 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004565 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004566 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004567 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004568 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004569 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004570 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004571 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004572 Decimal("-0.3")
4573 """
4574 return a.remainder_near(b, context=self)
4575
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004576 def rotate(self, a, b):
4577 """Returns a rotated copy of a, b times.
4578
4579 The coefficient of the result is a rotated copy of the digits in
4580 the coefficient of the first operand. The number of places of
4581 rotation is taken from the absolute value of the second operand,
4582 with the rotation being to the left if the second operand is
4583 positive or to the right otherwise.
4584
4585 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4586 Decimal("400000003")
4587 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4588 Decimal("12")
4589 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4590 Decimal("891234567")
4591 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4592 Decimal("123456789")
4593 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4594 Decimal("345678912")
4595 """
4596 return a.rotate(b, context=self)
4597
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004598 def same_quantum(self, a, b):
4599 """Returns True if the two operands have the same exponent.
4600
4601 The result is never affected by either the sign or the coefficient of
4602 either operand.
4603
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004604 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004605 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004606 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004607 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004608 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004609 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004610 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004611 True
4612 """
4613 return a.same_quantum(b)
4614
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004615 def scaleb (self, a, b):
4616 """Returns the first operand after adding the second value its exp.
4617
4618 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4619 Decimal("0.0750")
4620 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4621 Decimal("7.50")
4622 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4623 Decimal("7.50E+3")
4624 """
4625 return a.scaleb (b, context=self)
4626
4627 def shift(self, a, b):
4628 """Returns a shifted copy of a, b times.
4629
4630 The coefficient of the result is a shifted copy of the digits
4631 in the coefficient of the first operand. The number of places
4632 to shift is taken from the absolute value of the second operand,
4633 with the shift being to the left if the second operand is
4634 positive or to the right otherwise. Digits shifted into the
4635 coefficient are zeros.
4636
4637 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4638 Decimal("400000000")
4639 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4640 Decimal("0")
4641 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4642 Decimal("1234567")
4643 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4644 Decimal("123456789")
4645 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4646 Decimal("345678900")
4647 """
4648 return a.shift(b, context=self)
4649
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004650 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004651 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004652
4653 If the result must be inexact, it is rounded using the round-half-even
4654 algorithm.
4655
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004656 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004657 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004658 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004659 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004660 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004661 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004662 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004663 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004664 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004665 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004666 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004667 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004668 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004669 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004670 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004671 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004672 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004673 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004674 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004675 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004676 """
4677 return a.sqrt(context=self)
4678
4679 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004680 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004681
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004682 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004683 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004684 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004685 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004686 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004687 Decimal("-0.77")
4688 """
4689 return a.__sub__(b, context=self)
4690
4691 def to_eng_string(self, a):
4692 """Converts a number to a string, using scientific notation.
4693
4694 The operation is not affected by the context.
4695 """
4696 return a.to_eng_string(context=self)
4697
4698 def to_sci_string(self, a):
4699 """Converts a number to a string, using scientific notation.
4700
4701 The operation is not affected by the context.
4702 """
4703 return a.__str__(context=self)
4704
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004705 def to_integral_exact(self, a):
4706 """Rounds to an integer.
4707
4708 When the operand has a negative exponent, the result is the same
4709 as using the quantize() operation using the given operand as the
4710 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4711 of the operand as the precision setting; Inexact and Rounded flags
4712 are allowed in this operation. The rounding mode is taken from the
4713 context.
4714
4715 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4716 Decimal("2")
4717 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4718 Decimal("100")
4719 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4720 Decimal("100")
4721 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4722 Decimal("102")
4723 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4724 Decimal("-102")
4725 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4726 Decimal("1.0E+6")
4727 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4728 Decimal("7.89E+77")
4729 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4730 Decimal("-Infinity")
4731 """
4732 return a.to_integral_exact(context=self)
4733
4734 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004735 """Rounds to an integer.
4736
4737 When the operand has a negative exponent, the result is the same
4738 as using the quantize() operation using the given operand as the
4739 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4740 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004741 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004742
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004743 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004744 Decimal("2")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004745 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004746 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004747 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004748 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004749 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004750 Decimal("102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004751 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004752 Decimal("-102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004753 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004754 Decimal("1.0E+6")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004755 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004756 Decimal("7.89E+77")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004757 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004758 Decimal("-Infinity")
4759 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004760 return a.to_integral_value(context=self)
4761
4762 # the method name changed, but we provide also the old one, for compatibility
4763 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004764
4765class _WorkRep(object):
4766 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004767 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004768 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004769 # exp: None, int, or string
4770
4771 def __init__(self, value=None):
4772 if value is None:
4773 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004774 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004775 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004776 elif isinstance(value, Decimal):
4777 self.sign = value._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004778 cum = 0
Raymond Hettinger17931de2004-10-27 06:21:46 +00004779 for digit in value._int:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004780 cum = cum * 10 + digit
4781 self.int = cum
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004782 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004783 else:
4784 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004785 self.sign = value[0]
4786 self.int = value[1]
4787 self.exp = value[2]
4788
4789 def __repr__(self):
4790 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4791
4792 __str__ = __repr__
4793
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004794
4795
4796def _normalize(op1, op2, shouldround = 0, prec = 0):
4797 """Normalizes op1, op2 to have the same exp and length of coefficient.
4798
4799 Done during addition.
4800 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004801 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004802 tmp = op2
4803 other = op1
4804 else:
4805 tmp = op1
4806 other = op2
4807
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004808 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4809 # Then adding 10**exp to tmp has the same effect (after rounding)
4810 # as adding any positive quantity smaller than 10**exp; similarly
4811 # for subtraction. So if other is smaller than 10**exp we replace
4812 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4813 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004814 tmp_len = len(str(tmp.int))
4815 other_len = len(str(other.int))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004816 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4817 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004818 other.int = 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004819 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004820
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004821 tmp.int *= 10 ** (tmp.exp - other.exp)
4822 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004823 return op1, op2
4824
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004825##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004826
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004827# This function from Tim Peters was taken from here:
4828# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4829# The correction being in the function definition is for speed, and
4830# the whole function is not resolved with math.log because of avoiding
4831# the use of floats.
4832def _nbits(n, correction = {
4833 '0': 4, '1': 3, '2': 2, '3': 2,
4834 '4': 1, '5': 1, '6': 1, '7': 1,
4835 '8': 0, '9': 0, 'a': 0, 'b': 0,
4836 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4837 """Number of bits in binary representation of the positive integer n,
4838 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004839 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004840 if n < 0:
4841 raise ValueError("The argument to _nbits should be nonnegative.")
4842 hex_n = "%x" % n
4843 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004844
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004845def _sqrt_nearest(n, a):
4846 """Closest integer to the square root of the positive integer n. a is
4847 an initial approximation to the square root. Any positive integer
4848 will do for a, but the closer a is to the square root of n the
4849 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004850
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004851 """
4852 if n <= 0 or a <= 0:
4853 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4854
4855 b=0
4856 while a != b:
4857 b, a = a, a--n//a>>1
4858 return a
4859
4860def _rshift_nearest(x, shift):
4861 """Given an integer x and a nonnegative integer shift, return closest
4862 integer to x / 2**shift; use round-to-even in case of a tie.
4863
4864 """
4865 b, q = 1 << shift, x >> shift
4866 return q + (2*(x & (b-1)) + (q&1) > b)
4867
4868def _div_nearest(a, b):
4869 """Closest integer to a/b, a and b positive integers; rounds to even
4870 in the case of a tie.
4871
4872 """
4873 q, r = divmod(a, b)
4874 return q + (2*r + (q&1) > b)
4875
4876def _ilog(x, M, L = 8):
4877 """Integer approximation to M*log(x/M), with absolute error boundable
4878 in terms only of x/M.
4879
4880 Given positive integers x and M, return an integer approximation to
4881 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4882 between the approximation and the exact result is at most 22. For
4883 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4884 both cases these are upper bounds on the error; it will usually be
4885 much smaller."""
4886
4887 # The basic algorithm is the following: let log1p be the function
4888 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4889 # the reduction
4890 #
4891 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4892 #
4893 # repeatedly until the argument to log1p is small (< 2**-L in
4894 # absolute value). For small y we can use the Taylor series
4895 # expansion
4896 #
4897 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4898 #
4899 # truncating at T such that y**T is small enough. The whole
4900 # computation is carried out in a form of fixed-point arithmetic,
4901 # with a real number z being represented by an integer
4902 # approximation to z*M. To avoid loss of precision, the y below
4903 # is actually an integer approximation to 2**R*y*M, where R is the
4904 # number of reductions performed so far.
4905
4906 y = x-M
4907 # argument reduction; R = number of reductions performed
4908 R = 0
4909 while (R <= L and abs(y) << L-R >= M or
4910 R > L and abs(y) >> R-L >= M):
4911 y = _div_nearest((M*y) << 1,
4912 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4913 R += 1
4914
4915 # Taylor series with T terms
4916 T = -int(-10*len(str(M))//(3*L))
4917 yshift = _rshift_nearest(y, R)
4918 w = _div_nearest(M, T)
4919 for k in range(T-1, 0, -1):
4920 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4921
4922 return _div_nearest(w*y, M)
4923
4924def _dlog10(c, e, p):
4925 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4926 approximation to 10**p * log10(c*10**e), with an absolute error of
4927 at most 1. Assumes that c*10**e is not exactly 1."""
4928
4929 # increase precision by 2; compensate for this by dividing
4930 # final result by 100
4931 p += 2
4932
4933 # write c*10**e as d*10**f with either:
4934 # f >= 0 and 1 <= d <= 10, or
4935 # f <= 0 and 0.1 <= d <= 1.
4936 # Thus for c*10**e close to 1, f = 0
4937 l = len(str(c))
4938 f = e+l - (e+l >= 1)
4939
4940 if p > 0:
4941 M = 10**p
4942 k = e+p-f
4943 if k >= 0:
4944 c *= 10**k
4945 else:
4946 c = _div_nearest(c, 10**-k)
4947
4948 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004949 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004950 log_d = _div_nearest(log_d*M, log_10)
4951 log_tenpower = f*M # exact
4952 else:
4953 log_d = 0 # error < 2.31
4954 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4955
4956 return _div_nearest(log_tenpower+log_d, 100)
4957
4958def _dlog(c, e, p):
4959 """Given integers c, e and p with c > 0, compute an integer
4960 approximation to 10**p * log(c*10**e), with an absolute error of
4961 at most 1. Assumes that c*10**e is not exactly 1."""
4962
4963 # Increase precision by 2. The precision increase is compensated
4964 # for at the end with a division by 100.
4965 p += 2
4966
4967 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4968 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4969 # as 10**p * log(d) + 10**p*f * log(10).
4970 l = len(str(c))
4971 f = e+l - (e+l >= 1)
4972
4973 # compute approximation to 10**p*log(d), with error < 27
4974 if p > 0:
4975 k = e+p-f
4976 if k >= 0:
4977 c *= 10**k
4978 else:
4979 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4980
4981 # _ilog magnifies existing error in c by a factor of at most 10
4982 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4983 else:
4984 # p <= 0: just approximate the whole thing by 0; error < 2.31
4985 log_d = 0
4986
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004987 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004988 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004989 extra = len(str(abs(f)))-1
4990 if p + extra >= 0:
4991 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4992 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4993 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004994 else:
4995 f_log_ten = 0
4996 else:
4997 f_log_ten = 0
4998
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004999 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005000 return _div_nearest(f_log_ten + log_d, 100)
5001
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005002class _Log10Memoize(object):
5003 """Class to compute, store, and allow retrieval of, digits of the
5004 constant log(10) = 2.302585.... This constant is needed by
5005 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5006 def __init__(self):
5007 self.digits = "23025850929940456840179914546843642076011014886"
5008
5009 def getdigits(self, p):
5010 """Given an integer p >= 0, return floor(10**p)*log(10).
5011
5012 For example, self.getdigits(3) returns 2302.
5013 """
5014 # digits are stored as a string, for quick conversion to
5015 # integer in the case that we've already computed enough
5016 # digits; the stored digits should always be correct
5017 # (truncated, not rounded to nearest).
5018 if p < 0:
5019 raise ValueError("p should be nonnegative")
5020
5021 if p >= len(self.digits):
5022 # compute p+3, p+6, p+9, ... digits; continue until at
5023 # least one of the extra digits is nonzero
5024 extra = 3
5025 while True:
5026 # compute p+extra digits, correct to within 1ulp
5027 M = 10**(p+extra+2)
5028 digits = str(_div_nearest(_ilog(10*M, M), 100))
5029 if digits[-extra:] != '0'*extra:
5030 break
5031 extra += 3
5032 # keep all reliable digits so far; remove trailing zeros
5033 # and next nonzero digit
5034 self.digits = digits.rstrip('0')[:-1]
5035 return int(self.digits[:p+1])
5036
5037_log10_digits = _Log10Memoize().getdigits
5038
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005039def _iexp(x, M, L=8):
5040 """Given integers x and M, M > 0, such that x/M is small in absolute
5041 value, compute an integer approximation to M*exp(x/M). For 0 <=
5042 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5043 is usually much smaller)."""
5044
5045 # Algorithm: to compute exp(z) for a real number z, first divide z
5046 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5047 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5048 # series
5049 #
5050 # expm1(x) = x + x**2/2! + x**3/3! + ...
5051 #
5052 # Now use the identity
5053 #
5054 # expm1(2x) = expm1(x)*(expm1(x)+2)
5055 #
5056 # R times to compute the sequence expm1(z/2**R),
5057 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5058
5059 # Find R such that x/2**R/M <= 2**-L
5060 R = _nbits((x<<L)//M)
5061
5062 # Taylor series. (2**L)**T > M
5063 T = -int(-10*len(str(M))//(3*L))
5064 y = _div_nearest(x, T)
5065 Mshift = M<<R
5066 for i in range(T-1, 0, -1):
5067 y = _div_nearest(x*(Mshift + y), Mshift * i)
5068
5069 # Expansion
5070 for k in range(R-1, -1, -1):
5071 Mshift = M<<(k+2)
5072 y = _div_nearest(y*(y+Mshift), Mshift)
5073
5074 return M+y
5075
5076def _dexp(c, e, p):
5077 """Compute an approximation to exp(c*10**e), with p decimal places of
5078 precision.
5079
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005080 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005081
5082 10**(p-1) <= d <= 10**p, and
5083 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5084
5085 In other words, d*10**f is an approximation to exp(c*10**e) with p
5086 digits of precision, and with an error in d of at most 1. This is
5087 almost, but not quite, the same as the error being < 1ulp: when d
5088 = 10**(p-1) the error could be up to 10 ulp."""
5089
5090 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5091 p += 2
5092
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005093 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005094 extra = max(0, e + len(str(c)) - 1)
5095 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005096
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005097 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005098 # rounding down
5099 shift = e+q
5100 if shift >= 0:
5101 cshift = c*10**shift
5102 else:
5103 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005104 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005105
5106 # reduce remainder back to original precision
5107 rem = _div_nearest(rem, 10**extra)
5108
5109 # error in result of _iexp < 120; error after division < 0.62
5110 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5111
5112def _dpower(xc, xe, yc, ye, p):
5113 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5114 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5115
5116 10**(p-1) <= c <= 10**p, and
5117 (c-1)*10**e < x**y < (c+1)*10**e
5118
5119 in other words, c*10**e is an approximation to x**y with p digits
5120 of precision, and with an error in c of at most 1. (This is
5121 almost, but not quite, the same as the error being < 1ulp: when c
5122 == 10**(p-1) we can only guarantee error < 10ulp.)
5123
5124 We assume that: x is positive and not equal to 1, and y is nonzero.
5125 """
5126
5127 # Find b such that 10**(b-1) <= |y| <= 10**b
5128 b = len(str(abs(yc))) + ye
5129
5130 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5131 lxc = _dlog(xc, xe, p+b+1)
5132
5133 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5134 shift = ye-b
5135 if shift >= 0:
5136 pc = lxc*yc*10**shift
5137 else:
5138 pc = _div_nearest(lxc*yc, 10**-shift)
5139
5140 if pc == 0:
5141 # we prefer a result that isn't exactly 1; this makes it
5142 # easier to compute a correctly rounded result in __pow__
5143 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5144 coeff, exp = 10**(p-1)+1, 1-p
5145 else:
5146 coeff, exp = 10**p-1, -p
5147 else:
5148 coeff, exp = _dexp(pc, -(p+1), p+1)
5149 coeff = _div_nearest(coeff, 10)
5150 exp += 1
5151
5152 return coeff, exp
5153
5154def _log10_lb(c, correction = {
5155 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5156 '6': 23, '7': 16, '8': 10, '9': 5}):
5157 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5158 if c <= 0:
5159 raise ValueError("The argument to _log10_lb should be nonnegative.")
5160 str_c = str(c)
5161 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005162
Guido van Rossumd8faa362007-04-27 19:54:29 +00005163##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005164
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005165def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005166 """Convert other to Decimal.
5167
5168 Verifies that it's ok to use in an implicit construction.
5169 """
5170 if isinstance(other, Decimal):
5171 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005172 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005173 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005174 if raiseit:
5175 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005176 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005177
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005178_infinity_map = {
5179 'inf' : 1,
5180 'infinity' : 1,
5181 '+inf' : 1,
5182 '+infinity' : 1,
5183 '-inf' : -1,
5184 '-infinity' : -1
5185}
5186
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005187def _isinfinity(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005188 """Determines whether a string or float is infinity.
5189
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005190 +1 for negative infinity; 0 for finite ; +1 for positive infinity
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005191 """
5192 num = str(num).lower()
5193 return _infinity_map.get(num, 0)
5194
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00005195def _isnan(num):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005196 """Determines whether a string or float is NaN
5197
5198 (1, sign, diagnostic info as string) => NaN
5199 (2, sign, diagnostic info as string) => sNaN
5200 0 => not a NaN
5201 """
5202 num = str(num).lower()
5203 if not num:
5204 return 0
5205
Guido van Rossumd8faa362007-04-27 19:54:29 +00005206 # Get the sign, get rid of trailing [+-]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005207 sign = 0
5208 if num[0] == '+':
5209 num = num[1:]
Guido van Rossumd8faa362007-04-27 19:54:29 +00005210 elif num[0] == '-': # elif avoids '+-nan'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005211 num = num[1:]
5212 sign = 1
5213
5214 if num.startswith('nan'):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005215 if len(num) > 3 and not num[3:].isdigit(): # diagnostic info
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005216 return 0
5217 return (1, sign, num[3:].lstrip('0'))
5218 if num.startswith('snan'):
5219 if len(num) > 4 and not num[4:].isdigit():
5220 return 0
5221 return (2, sign, num[4:].lstrip('0'))
5222 return 0
5223
5224
Guido van Rossumd8faa362007-04-27 19:54:29 +00005225##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005226
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005227# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005228# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005229
5230DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005231 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005232 traps=[DivisionByZero, Overflow, InvalidOperation],
5233 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005234 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005235 Emax=999999999,
5236 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005237 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005238)
5239
5240# Pre-made alternate contexts offered by the specification
5241# Don't change these; the user should be able to select these
5242# contexts and be able to reproduce results from other implementations
5243# of the spec.
5244
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005245BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005246 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005247 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5248 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005249)
5250
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005251ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005252 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005253 traps=[],
5254 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005255)
5256
5257
Guido van Rossumd8faa362007-04-27 19:54:29 +00005258##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005259
Guido van Rossumd8faa362007-04-27 19:54:29 +00005260# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005261Inf = Decimal('Inf')
5262negInf = Decimal('-Inf')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005263NaN = Decimal('NaN')
5264Dec_0 = Decimal(0)
5265Dec_p1 = Decimal(1)
5266Dec_n1 = Decimal(-1)
5267Dec_p2 = Decimal(2)
5268Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005269
Guido van Rossumd8faa362007-04-27 19:54:29 +00005270# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005271Infsign = (Inf, negInf)
5272
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005273
Guido van Rossumd8faa362007-04-27 19:54:29 +00005274##### crud for parsing strings #############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005275import re
5276
5277# There's an optional sign at the start, and an optional exponent
5278# at the end. The exponent has an optional sign and at least one
5279# digit. In between, must have either at least one digit followed
5280# by an optional fraction, or a decimal point followed by at least
5281# one digit. Yuck.
5282
5283_parser = re.compile(r"""
5284# \s*
5285 (?P<sign>[-+])?
5286 (
5287 (?P<int>\d+) (\. (?P<frac>\d*))?
5288 |
5289 \. (?P<onlyfrac>\d+)
5290 )
5291 ([eE](?P<exp>[-+]? \d+))?
5292# \s*
5293 $
Guido van Rossumd8faa362007-04-27 19:54:29 +00005294""", re.VERBOSE).match # Uncomment the \s* to allow leading or trailing spaces.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005295
5296del re
5297
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005298def _string2exact(s):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005299 """Return sign, n, p s.t.
5300
5301 Float string value == -1**sign * n * 10**p exactly
5302 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005303 m = _parser(s)
5304 if m is None:
5305 raise ValueError("invalid literal for Decimal: %r" % s)
5306
5307 if m.group('sign') == "-":
5308 sign = 1
5309 else:
5310 sign = 0
5311
5312 exp = m.group('exp')
5313 if exp is None:
5314 exp = 0
5315 else:
5316 exp = int(exp)
5317
5318 intpart = m.group('int')
5319 if intpart is None:
5320 intpart = ""
5321 fracpart = m.group('onlyfrac')
5322 else:
5323 fracpart = m.group('frac')
5324 if fracpart is None:
5325 fracpart = ""
5326
5327 exp -= len(fracpart)
5328
5329 mantissa = intpart + fracpart
Guido van Rossumc1f779c2007-07-03 08:25:58 +00005330 tmp = list(map(int, mantissa))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005331 backup = tmp
5332 while tmp and tmp[0] == 0:
5333 del tmp[0]
5334
5335 # It's a zero
5336 if not tmp:
5337 if backup:
5338 return (sign, tuple(backup), exp)
5339 return (sign, (0,), exp)
5340 mantissa = tuple(tmp)
5341
5342 return (sign, mantissa, exp)
5343
5344
5345if __name__ == '__main__':
5346 import doctest, sys
5347 doctest.testmod(sys.modules[__name__])