blob: 7f957684afc09618988402e6010ae36ac471f6ec [file] [log] [blame]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001# Copyright (c) 2004 Python Software Foundation.
2# All rights reserved.
3
4# Written by Eric Price <eprice at tjhsst.edu>
5# and Facundo Batista <facundo at taniquetil.com.ar>
6# and Raymond Hettinger <python at rcn.com>
Fred Drake1f34eb12004-07-01 14:28:36 +00007# and Aahz <aahz at pobox.com>
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00008# and Tim Peters
9
Raymond Hettinger27dbcf22004-08-19 22:39:55 +000010# This module is currently Py2.3 compatible and should be kept that way
11# unless a major compelling advantage arises. IOW, 2.3 compatibility is
12# strongly preferred, but not guaranteed.
13
14# Also, this module should be kept in sync with the latest updates of
15# the IBM specification as it evolves. Those updates will be treated
16# as bug fixes (deviation from the spec is a compatibility, usability
17# bug) and will be backported. At this point the spec is stabilizing
18# and the updates are becoming fewer, smaller, and less significant.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000019
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000020"""
21This is a Py2.3 implementation of decimal floating point arithmetic based on
22the General Decimal Arithmetic Specification:
23
24 www2.hursley.ibm.com/decimal/decarith.html
25
Raymond Hettinger0ea241e2004-07-04 13:53:24 +000026and IEEE standard 854-1987:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000027
28 www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
29
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000030Decimal floating point has finite precision with arbitrarily large bounds.
31
Guido van Rossumd8faa362007-04-27 19:54:29 +000032The purpose of this module is to support arithmetic using familiar
33"schoolhouse" rules and to avoid some of the tricky representation
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000034issues associated with binary floating point. The package is especially
35useful for financial applications or for contexts where users have
36expectations that are at odds with binary floating point (for instance,
37in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
38of the expected Decimal("0.00") returned by decimal floating point).
39
40Here are some examples of using the decimal module:
41
42>>> from decimal import *
Raymond Hettingerbd7f76d2004-07-08 00:49:18 +000043>>> setcontext(ExtendedContext)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000044>>> Decimal(0)
45Decimal("0")
46>>> Decimal("1")
47Decimal("1")
48>>> Decimal("-.0123")
49Decimal("-0.0123")
50>>> Decimal(123456)
51Decimal("123456")
52>>> Decimal("123.45e12345678901234567890")
53Decimal("1.2345E+12345678901234567892")
54>>> Decimal("1.33") + Decimal("1.27")
55Decimal("2.60")
56>>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41")
57Decimal("-2.20")
58>>> dig = Decimal(1)
Guido van Rossum7131f842007-02-09 20:13:25 +000059>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000600.333333333
61>>> getcontext().prec = 18
Guido van Rossum7131f842007-02-09 20:13:25 +000062>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000630.333333333333333333
Guido van Rossum7131f842007-02-09 20:13:25 +000064>>> print(dig.sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000651
Guido van Rossum7131f842007-02-09 20:13:25 +000066>>> print(Decimal(3).sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000671.73205080756887729
Guido van Rossum7131f842007-02-09 20:13:25 +000068>>> print(Decimal(3) ** 123)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000694.85192780976896427E+58
70>>> inf = Decimal(1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000071>>> print(inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000072Infinity
73>>> neginf = Decimal(-1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000074>>> print(neginf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000075-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000076>>> print(neginf + inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000077NaN
Guido van Rossum7131f842007-02-09 20:13:25 +000078>>> print(neginf * inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000079-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000080>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000081Infinity
Raymond Hettingerbf440692004-07-10 14:14:37 +000082>>> getcontext().traps[DivisionByZero] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000083>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000084Traceback (most recent call last):
85 ...
86 ...
87 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +000088decimal.DivisionByZero: x / 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000089>>> c = Context()
Raymond Hettingerbf440692004-07-10 14:14:37 +000090>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000091>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000920
93>>> c.divide(Decimal(0), Decimal(0))
94Decimal("NaN")
Raymond Hettingerbf440692004-07-10 14:14:37 +000095>>> c.traps[InvalidOperation] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000096>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000098>>> c.flags[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000099>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000
Guido van Rossum7131f842007-02-09 20:13:25 +0000101>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000102Traceback (most recent call last):
103 ...
104 ...
105 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +0000106decimal.InvalidOperation: 0 / 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000107>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000109>>> c.flags[InvalidOperation] = 0
Raymond Hettingerbf440692004-07-10 14:14:37 +0000110>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000111>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000112NaN
Guido van Rossum7131f842007-02-09 20:13:25 +0000113>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141
115>>>
116"""
117
118__all__ = [
119 # Two major classes
120 'Decimal', 'Context',
121
122 # Contexts
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +0000123 'DefaultContext', 'BasicContext', 'ExtendedContext',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000124
125 # Exceptions
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +0000126 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
127 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000128
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000129 # Constants for use in setting up contexts
130 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000131 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000132
133 # Functions for manipulating contexts
Thomas Wouters89f507f2006-12-13 04:49:30 +0000134 'setcontext', 'getcontext', 'localcontext'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000135]
136
Raymond Hettingereb260842005-06-07 18:52:34 +0000137import copy as _copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000138
Guido van Rossumd8faa362007-04-27 19:54:29 +0000139# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000140ROUND_DOWN = 'ROUND_DOWN'
141ROUND_HALF_UP = 'ROUND_HALF_UP'
142ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
143ROUND_CEILING = 'ROUND_CEILING'
144ROUND_FLOOR = 'ROUND_FLOOR'
145ROUND_UP = 'ROUND_UP'
146ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000147ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000148
Guido van Rossumd8faa362007-04-27 19:54:29 +0000149# Rounding decision (not part of the public API)
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000150NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY
151ALWAYS_ROUND = 'ALWAYS_ROUND' # Every operation rounds at end.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000152
Guido van Rossumd8faa362007-04-27 19:54:29 +0000153# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000154
155class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000156 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000157
158 Used exceptions derive from this.
159 If an exception derives from another exception besides this (such as
160 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
161 called if the others are present. This isn't actually used for
162 anything, though.
163
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000164 handle -- Called when context._raise_error is called and the
165 trap_enabler is set. First argument is self, second is the
166 context. More arguments can be given, those being after
167 the explanation in _raise_error (For example,
168 context._raise_error(NewError, '(-x)!', self._sign) would
169 call NewError().handle(context, self._sign).)
170
171 To define a new exception, it should be sufficient to have it derive
172 from DecimalException.
173 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000174 def handle(self, context, *args):
175 pass
176
177
178class Clamped(DecimalException):
179 """Exponent of a 0 changed to fit bounds.
180
181 This occurs and signals clamped if the exponent of a result has been
182 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000183 representation. This may occur when the exponent of a zero result would
184 be outside the bounds of a representation, or when a large normal
185 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000186 this latter case, the exponent is reduced to fit and the corresponding
187 number of zero digits are appended to the coefficient ("fold-down").
188 """
189
190
191class InvalidOperation(DecimalException):
192 """An invalid operation was performed.
193
194 Various bad things cause this:
195
196 Something creates a signaling NaN
197 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000198 0 * (+-)INF
199 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000200 x % 0
201 (+-)INF % x
202 x._rescale( non-integer )
203 sqrt(-x) , x > 0
204 0 ** 0
205 x ** (non-integer)
206 x ** (+-)INF
207 An operand is invalid
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000208
209 The result of the operation after these is a quiet positive NaN,
210 except when the cause is a signaling NaN, in which case the result is
211 also a quiet NaN, but with the original sign, and an optional
212 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000213 """
214 def handle(self, context, *args):
215 if args:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000216 if args[0] == 1: # sNaN, must drop 's' but keep diagnostics
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000217 ans = _dec_from_triple(args[1]._sign, args[1]._int, 'n', True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000218 return ans._fix_nan(context)
219 elif args[0] == 2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000220 return _dec_from_triple(args[1], args[2], 'n', True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000221 return NaN
222
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000223
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000224class ConversionSyntax(InvalidOperation):
225 """Trying to convert badly formed string.
226
227 This occurs and signals invalid-operation if an string is being
228 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000229 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000230 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000231 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000232 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000233
234class DivisionByZero(DecimalException, ZeroDivisionError):
235 """Division by 0.
236
237 This occurs and signals division-by-zero if division of a finite number
238 by zero was attempted (during a divide-integer or divide operation, or a
239 power operation with negative right-hand operand), and the dividend was
240 not zero.
241
242 The result of the operation is [sign,inf], where sign is the exclusive
243 or of the signs of the operands for divide, or is 1 for an odd power of
244 -0, for power.
245 """
246
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000247 def handle(self, context, sign, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000248 return Infsign[sign]
249
250class DivisionImpossible(InvalidOperation):
251 """Cannot perform the division adequately.
252
253 This occurs and signals invalid-operation if the integer result of a
254 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000255 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000256 """
257
258 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000259 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000260
261class DivisionUndefined(InvalidOperation, ZeroDivisionError):
262 """Undefined result of division.
263
264 This occurs and signals invalid-operation if division by zero was
265 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000266 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000267 """
268
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000269 def handle(self, context, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000270 return NaN
271
272class Inexact(DecimalException):
273 """Had to round, losing information.
274
275 This occurs and signals inexact whenever the result of an operation is
276 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000277 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000278 result in all cases is unchanged.
279
280 The inexact signal may be tested (or trapped) to determine if a given
281 operation (or sequence of operations) was inexact.
282 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000283 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000284
285class InvalidContext(InvalidOperation):
286 """Invalid context. Unknown rounding, for example.
287
288 This occurs and signals invalid-operation if an invalid context was
Guido van Rossumd8faa362007-04-27 19:54:29 +0000289 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000290 on creation and either the precision exceeds the capability of the
291 underlying concrete representation or an unknown or unsupported rounding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000292 was specified. These aspects of the context need only be checked when
293 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000294 """
295
296 def handle(self, context, *args):
297 return NaN
298
299class Rounded(DecimalException):
300 """Number got rounded (not necessarily changed during rounding).
301
302 This occurs and signals rounded whenever the result of an operation is
303 rounded (that is, some zero or non-zero digits were discarded from the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000304 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000305 result in all cases is unchanged.
306
307 The rounded signal may be tested (or trapped) to determine if a given
308 operation (or sequence of operations) caused a loss of precision.
309 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000310 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000311
312class Subnormal(DecimalException):
313 """Exponent < Emin before rounding.
314
315 This occurs and signals subnormal whenever the result of a conversion or
316 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000317 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000318
319 The subnormal signal may be tested (or trapped) to determine if a given
320 or operation (or sequence of operations) yielded a subnormal result.
321 """
322 pass
323
324class Overflow(Inexact, Rounded):
325 """Numerical overflow.
326
327 This occurs and signals overflow if the adjusted exponent of a result
328 (from a conversion or from an operation that is not an attempt to divide
329 by zero), after rounding, would be greater than the largest value that
330 can be handled by the implementation (the value Emax).
331
332 The result depends on the rounding mode:
333
334 For round-half-up and round-half-even (and for round-half-down and
335 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000336 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000338 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000339 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000340 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000341 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000342 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000343 will also be raised.
344 """
345
346 def handle(self, context, sign, *args):
347 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000348 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000349 return Infsign[sign]
350 if sign == 0:
351 if context.rounding == ROUND_CEILING:
352 return Infsign[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000353 return _dec_from_triple(sign, '9'*context.prec,
354 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000355 if sign == 1:
356 if context.rounding == ROUND_FLOOR:
357 return Infsign[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000358 return _dec_from_triple(sign, '9'*context.prec,
359 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000360
361
362class Underflow(Inexact, Rounded, Subnormal):
363 """Numerical underflow with result rounded to 0.
364
365 This occurs and signals underflow if a result is inexact and the
366 adjusted exponent of the result would be smaller (more negative) than
367 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000368 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000369
370 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000371 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000372 in 0 with the sign of the intermediate result and an exponent of Etiny.
373
374 In all cases, Inexact, Rounded, and Subnormal will also be raised.
375 """
376
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000377# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000378_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000379 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000380
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000381# Map conditions (per the spec) to signals
382_condition_map = {ConversionSyntax:InvalidOperation,
383 DivisionImpossible:InvalidOperation,
384 DivisionUndefined:InvalidOperation,
385 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000386
Guido van Rossumd8faa362007-04-27 19:54:29 +0000387##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000388
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000389# The getcontext() and setcontext() function manage access to a thread-local
390# current context. Py2.4 offers direct support for thread locals. If that
391# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000392# work for older Pythons. If threads are not part of the build, create a
393# mock threading object with threading.local() returning the module namespace.
394
395try:
396 import threading
397except ImportError:
398 # Python was compiled without threads; create a mock object instead
399 import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +0000400 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000401 def local(self, sys=sys):
402 return sys.modules[__name__]
403 threading = MockThreading()
404 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000405
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000406try:
407 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000408
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000409except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000410
Guido van Rossumd8faa362007-04-27 19:54:29 +0000411 # To fix reloading, force it to create a new context
412 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000413 if hasattr(threading.currentThread(), '__decimal_context__'):
414 del threading.currentThread().__decimal_context__
415
416 def setcontext(context):
417 """Set this thread's context to context."""
418 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000419 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000420 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000421 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000422
423 def getcontext():
424 """Returns this thread's context.
425
426 If this thread does not yet have a context, returns
427 a new context and sets this thread's context.
428 New contexts are copies of DefaultContext.
429 """
430 try:
431 return threading.currentThread().__decimal_context__
432 except AttributeError:
433 context = Context()
434 threading.currentThread().__decimal_context__ = context
435 return context
436
437else:
438
439 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000440 if hasattr(local, '__decimal_context__'):
441 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000442
443 def getcontext(_local=local):
444 """Returns this thread's context.
445
446 If this thread does not yet have a context, returns
447 a new context and sets this thread's context.
448 New contexts are copies of DefaultContext.
449 """
450 try:
451 return _local.__decimal_context__
452 except AttributeError:
453 context = Context()
454 _local.__decimal_context__ = context
455 return context
456
457 def setcontext(context, _local=local):
458 """Set this thread's context to context."""
459 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000460 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000461 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000462 _local.__decimal_context__ = context
463
464 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000465
Thomas Wouters89f507f2006-12-13 04:49:30 +0000466def localcontext(ctx=None):
467 """Return a context manager for a copy of the supplied context
468
469 Uses a copy of the current context if no context is specified
470 The returned context manager creates a local decimal context
471 in a with statement:
472 def sin(x):
473 with localcontext() as ctx:
474 ctx.prec += 2
475 # Rest of sin calculation algorithm
476 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000477 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000478
479 def sin(x):
480 with localcontext(ExtendedContext):
481 # Rest of sin calculation algorithm
482 # uses the Extended Context from the
483 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000484 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000485
486 """
487 # The string below can't be included in the docstring until Python 2.6
488 # as the doctest module doesn't understand __future__ statements
489 """
490 >>> from __future__ import with_statement
Guido van Rossum7131f842007-02-09 20:13:25 +0000491 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000492 28
493 >>> with localcontext():
494 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000495 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000496 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000497 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000498 30
499 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000500 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000501 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000502 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000503 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000504 28
505 """
506 if ctx is None: ctx = getcontext()
507 return _ContextManager(ctx)
508
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000509
Guido van Rossumd8faa362007-04-27 19:54:29 +0000510##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000511
512class Decimal(object):
513 """Floating point class for decimal arithmetic."""
514
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000515 __slots__ = ('_exp','_int','_sign', '_is_special')
516 # Generally, the value of the Decimal instance is given by
517 # (-1)**_sign * _int * 10**_exp
518 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000519
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000520 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000521 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000522 """Create a decimal point instance.
523
524 >>> Decimal('3.14') # string input
525 Decimal("3.14")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000526 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000527 Decimal("3.14")
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000528 >>> Decimal(314) # int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000529 Decimal("314")
530 >>> Decimal(Decimal(314)) # another decimal instance
531 Decimal("314")
532 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000533
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000534 # Note that the coefficient, self._int, is actually stored as
535 # a string rather than as a tuple of digits. This speeds up
536 # the "digits to integer" and "integer to digits" conversions
537 # that are used in almost every arithmetic operation on
538 # Decimals. This is an internal detail: the as_tuple function
539 # and the Decimal constructor still deal with tuples of
540 # digits.
541
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000542 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000543
Christian Heimesd59c64c2007-11-30 19:27:20 +0000544 # From a string
545 # REs insist on real strings, so we can too.
546 if isinstance(value, str):
547 m = _parser(value)
548 if m is None:
549 if context is None:
550 context = getcontext()
551 return context._raise_error(ConversionSyntax,
552 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000553
Christian Heimesd59c64c2007-11-30 19:27:20 +0000554 if m.group('sign') == "-":
555 self._sign = 1
556 else:
557 self._sign = 0
558 intpart = m.group('int')
559 if intpart is not None:
560 # finite number
561 fracpart = m.group('frac')
562 exp = int(m.group('exp') or '0')
563 if fracpart is not None:
564 self._int = (intpart+fracpart).lstrip('0') or '0'
565 self._exp = exp - len(fracpart)
566 else:
567 self._int = intpart.lstrip('0') or '0'
568 self._exp = exp
569 self._is_special = False
570 else:
571 diag = m.group('diag')
572 if diag is not None:
573 # NaN
574 self._int = diag.lstrip('0')
575 if m.group('signal'):
576 self._exp = 'N'
577 else:
578 self._exp = 'n'
579 else:
580 # infinity
581 self._int = '0'
582 self._exp = 'F'
583 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000584 return self
585
586 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000587 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000588 if value >= 0:
589 self._sign = 0
590 else:
591 self._sign = 1
592 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000593 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000594 self._is_special = False
595 return self
596
597 # From another decimal
598 if isinstance(value, Decimal):
599 self._exp = value._exp
600 self._sign = value._sign
601 self._int = value._int
602 self._is_special = value._is_special
603 return self
604
605 # From an internal working value
606 if isinstance(value, _WorkRep):
607 self._sign = value.sign
608 self._int = str(value.int)
609 self._exp = int(value.exp)
610 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000611 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000612
613 # tuple/list conversion (possibly from as_tuple())
614 if isinstance(value, (list,tuple)):
615 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000616 raise ValueError('Invalid tuple size in creation of Decimal '
617 'from list or tuple. The list or tuple '
618 'should have exactly three elements.')
619 # process sign. The isinstance test rejects floats
620 if not (isinstance(value[0], int) and value[0] in (0,1)):
621 raise ValueError("Invalid sign. The first value in the tuple "
622 "should be an integer; either 0 for a "
623 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000624 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000625 if value[2] == 'F':
626 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000627 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000628 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000629 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000630 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000631 # process and validate the digits in value[1]
632 digits = []
633 for digit in value[1]:
634 if isinstance(digit, int) and 0 <= digit <= 9:
635 # skip leading zeros
636 if digits or digit != 0:
637 digits.append(digit)
638 else:
639 raise ValueError("The second value in the tuple must "
640 "be composed of integers in the range "
641 "0 through 9.")
642 if value[2] in ('n', 'N'):
643 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000644 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000645 self._exp = value[2]
646 self._is_special = True
647 elif isinstance(value[2], int):
648 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000649 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000650 self._exp = value[2]
651 self._is_special = False
652 else:
653 raise ValueError("The third value in the tuple must "
654 "be an integer, or one of the "
655 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000656 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000657
Raymond Hettingerbf440692004-07-10 14:14:37 +0000658 if isinstance(value, float):
659 raise TypeError("Cannot convert float to Decimal. " +
660 "First convert the float to a string")
661
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000662 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000663
664 def _isnan(self):
665 """Returns whether the number is not actually one.
666
667 0 if a number
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000668 1 if NaN (it could be a normal quiet NaN or a phantom one)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000669 2 if sNaN
670 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000671 if self._is_special:
672 exp = self._exp
673 if exp == 'n':
674 return 1
675 elif exp == 'N':
676 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000677 return 0
678
679 def _isinfinity(self):
680 """Returns whether the number is infinite
681
682 0 if finite or not a number
683 1 if +INF
684 -1 if -INF
685 """
686 if self._exp == 'F':
687 if self._sign:
688 return -1
689 return 1
690 return 0
691
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000692 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000693 """Returns whether the number is not actually one.
694
695 if self, other are sNaN, signal
696 if self, other are NaN return nan
697 return 0
698
699 Done before operations.
700 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000701
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000702 self_is_nan = self._isnan()
703 if other is None:
704 other_is_nan = False
705 else:
706 other_is_nan = other._isnan()
707
708 if self_is_nan or other_is_nan:
709 if context is None:
710 context = getcontext()
711
712 if self_is_nan == 2:
713 return context._raise_error(InvalidOperation, 'sNaN',
714 1, self)
715 if other_is_nan == 2:
716 return context._raise_error(InvalidOperation, 'sNaN',
717 1, other)
718 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000719 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000720
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000721 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000722 return 0
723
Jack Diederich4dafcc42006-11-28 19:15:13 +0000724 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000725 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000726
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000727 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000728 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000729 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000730
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000731 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000732 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000733 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000734 # Never return NotImplemented
735 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000736
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000737 if self._is_special or other._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000738 # check for nans, without raising on a signaling nan
739 if self._isnan() or other._isnan():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000740 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000741
742 # INF = INF
743 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000744
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000745 # check for zeros; note that cmp(0, -0) should return 0
746 if not self:
747 if not other:
748 return 0
749 else:
750 return -((-1)**other._sign)
751 if not other:
752 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000753
Guido van Rossumd8faa362007-04-27 19:54:29 +0000754 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000755 if other._sign < self._sign:
756 return -1
757 if self._sign < other._sign:
758 return 1
759
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000760 self_adjusted = self.adjusted()
761 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000762 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000763 self_padded = self._int + '0'*(self._exp - other._exp)
764 other_padded = other._int + '0'*(other._exp - self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000765 return cmp(self_padded, other_padded) * (-1)**self._sign
766 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000767 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000768 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000769 return -((-1)**self._sign)
770
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000771 def __eq__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000772 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000773 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000774 return self.__cmp__(other) == 0
775
776 def __ne__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000777 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000778 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000779 return self.__cmp__(other) != 0
780
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000781 def __lt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000782 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000783 return NotImplemented
784 return self.__cmp__(other) < 0
785
786 def __le__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000787 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000788 return NotImplemented
789 return self.__cmp__(other) <= 0
790
791 def __gt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000792 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000793 return NotImplemented
794 return self.__cmp__(other) > 0
795
796 def __ge__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000797 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000798 return NotImplemented
799 return self.__cmp__(other) >= 0
800
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000801 def compare(self, other, context=None):
802 """Compares one to another.
803
804 -1 => a < b
805 0 => a = b
806 1 => a > b
807 NaN => one is NaN
808 Like __cmp__, but returns Decimal instances.
809 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000810 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000811
Guido van Rossumd8faa362007-04-27 19:54:29 +0000812 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000813 if (self._is_special or other and other._is_special):
814 ans = self._check_nans(other, context)
815 if ans:
816 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000817
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000818 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000819
820 def __hash__(self):
821 """x.__hash__() <==> hash(x)"""
822 # Decimal integers must hash the same as the ints
823 # Non-integer decimals are normalized and hashed as strings
Thomas Wouters477c8d52006-05-27 19:21:47 +0000824 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000825 if self._is_special:
826 if self._isnan():
827 raise TypeError('Cannot hash a NaN value.')
828 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000829 if not self:
830 return 0
831 if self._isinteger():
832 op = _WorkRep(self.to_integral_value())
833 # to make computation feasible for Decimals with large
834 # exponent, we use the fact that hash(n) == hash(m) for
835 # any two nonzero integers n and m such that (i) n and m
836 # have the same sign, and (ii) n is congruent to m modulo
837 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
838 # hash((-1)**s*c*pow(10, e, 2**64-1).
839 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000840 return hash(str(self.normalize()))
841
842 def as_tuple(self):
843 """Represents the number as a triple tuple.
844
845 To show the internals exactly as they are.
846 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000847 return (self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000848
849 def __repr__(self):
850 """Represents the number as an instance of Decimal."""
851 # Invariant: eval(repr(d)) == d
852 return 'Decimal("%s")' % str(self)
853
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000854 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000855 """Return string representation of the number in scientific notation.
856
857 Captures all of the information in the underlying representation.
858 """
859
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000860 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000861 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000862 if self._exp == 'F':
863 return sign + 'Infinity'
864 elif self._exp == 'n':
865 return sign + 'NaN' + self._int
866 else: # self._exp == 'N'
867 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000868
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000869 # number of digits of self._int to left of decimal point
870 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000871
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000872 # dotplace is number of digits of self._int to the left of the
873 # decimal point in the mantissa of the output string (that is,
874 # after adjusting the exponent)
875 if self._exp <= 0 and leftdigits > -6:
876 # no exponent required
877 dotplace = leftdigits
878 elif not eng:
879 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000880 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000881 elif self._int == '0':
882 # engineering notation, zero
883 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000884 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000885 # engineering notation, nonzero
886 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000887
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000888 if dotplace <= 0:
889 intpart = '0'
890 fracpart = '.' + '0'*(-dotplace) + self._int
891 elif dotplace >= len(self._int):
892 intpart = self._int+'0'*(dotplace-len(self._int))
893 fracpart = ''
894 else:
895 intpart = self._int[:dotplace]
896 fracpart = '.' + self._int[dotplace:]
897 if leftdigits == dotplace:
898 exp = ''
899 else:
900 if context is None:
901 context = getcontext()
902 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
903
904 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000905
906 def to_eng_string(self, context=None):
907 """Convert to engineering-type string.
908
909 Engineering notation has an exponent which is a multiple of 3, so there
910 are up to 3 digits left of the decimal place.
911
912 Same rules for when in exponential and when as a value as in __str__.
913 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000914 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000915
916 def __neg__(self, context=None):
917 """Returns a copy with the sign switched.
918
919 Rounds, if it has reason.
920 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000921 if self._is_special:
922 ans = self._check_nans(context=context)
923 if ans:
924 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000925
926 if not self:
927 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000928 ans = self.copy_sign(Dec_0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000929 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000930 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000931
932 if context is None:
933 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000934 if context._rounding_decision == ALWAYS_ROUND:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000935 return ans._fix(context)
936 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000937
938 def __pos__(self, context=None):
939 """Returns a copy, unless it is a sNaN.
940
941 Rounds the number (if more then precision digits)
942 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000943 if self._is_special:
944 ans = self._check_nans(context=context)
945 if ans:
946 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000947
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000948 if not self:
949 # + (-0) = 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000950 ans = self.copy_sign(Dec_0)
951 else:
952 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000953
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000954 if context is None:
955 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000956 if context._rounding_decision == ALWAYS_ROUND:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000957 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000958 return ans
959
960 def __abs__(self, round=1, context=None):
961 """Returns the absolute value of self.
962
963 If the second argument is 0, do not round.
964 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000965 if self._is_special:
966 ans = self._check_nans(context=context)
967 if ans:
968 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000969
970 if not round:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000971 if context is None:
972 context = getcontext()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000973 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000974 context._set_rounding_decision(NEVER_ROUND)
975
976 if self._sign:
977 ans = self.__neg__(context=context)
978 else:
979 ans = self.__pos__(context=context)
980
981 return ans
982
983 def __add__(self, other, context=None):
984 """Returns self + other.
985
986 -INF + INF (or the reverse) cause InvalidOperation errors.
987 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000988 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000989 if other is NotImplemented:
990 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000991
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000992 if context is None:
993 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000994
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000995 if self._is_special or other._is_special:
996 ans = self._check_nans(other, context)
997 if ans:
998 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000999
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001000 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001001 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001002 if self._sign != other._sign and other._isinfinity():
1003 return context._raise_error(InvalidOperation, '-INF + INF')
1004 return Decimal(self)
1005 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001006 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001007
1008 shouldround = context._rounding_decision == ALWAYS_ROUND
1009
1010 exp = min(self._exp, other._exp)
1011 negativezero = 0
1012 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001013 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001014 negativezero = 1
1015
1016 if not self and not other:
1017 sign = min(self._sign, other._sign)
1018 if negativezero:
1019 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001020 ans = _dec_from_triple(sign, '0', exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001021 if shouldround:
1022 ans = ans._fix(context)
1023 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001024 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001025 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001026 ans = other._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001027 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001028 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001029 return ans
1030 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001031 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001032 ans = self._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001033 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001034 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001035 return ans
1036
1037 op1 = _WorkRep(self)
1038 op2 = _WorkRep(other)
1039 op1, op2 = _normalize(op1, op2, shouldround, context.prec)
1040
1041 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001042 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001043 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001044 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001045 ans = _dec_from_triple(negativezero, '0', exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001046 if shouldround:
1047 ans = ans._fix(context)
1048 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001049 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001050 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001051 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001052 if op1.sign == 1:
1053 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001054 op1.sign, op2.sign = op2.sign, op1.sign
1055 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001056 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001057 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001058 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001059 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001060 op1.sign, op2.sign = (0, 0)
1061 else:
1062 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001063 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001064
Raymond Hettinger17931de2004-10-27 06:21:46 +00001065 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001066 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001067 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001068 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001069
1070 result.exp = op1.exp
1071 ans = Decimal(result)
1072 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001073 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001074 return ans
1075
1076 __radd__ = __add__
1077
1078 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001079 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001080 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001081 if other is NotImplemented:
1082 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001083
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001084 if self._is_special or other._is_special:
1085 ans = self._check_nans(other, context=context)
1086 if ans:
1087 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001088
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001089 # self - other is computed as self + other.copy_negate()
1090 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001091
1092 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001093 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001094 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001095 if other is NotImplemented:
1096 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001097
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001098 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001099
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001100 def __mul__(self, other, context=None):
1101 """Return self * other.
1102
1103 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1104 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001105 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001106 if other is NotImplemented:
1107 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001108
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001109 if context is None:
1110 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001111
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001112 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001113
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001114 if self._is_special or other._is_special:
1115 ans = self._check_nans(other, context)
1116 if ans:
1117 return ans
1118
1119 if self._isinfinity():
1120 if not other:
1121 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1122 return Infsign[resultsign]
1123
1124 if other._isinfinity():
1125 if not self:
1126 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1127 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001128
1129 resultexp = self._exp + other._exp
1130 shouldround = context._rounding_decision == ALWAYS_ROUND
1131
1132 # Special case for multiplying by zero
1133 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001134 ans = _dec_from_triple(resultsign, '0', resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001135 if shouldround:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001136 # Fixing in case the exponent is out of bounds
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001137 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001138 return ans
1139
1140 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001141 if self._int == '1':
1142 ans = _dec_from_triple(resultsign, other._int, resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001143 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001144 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001145 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001146 if other._int == '1':
1147 ans = _dec_from_triple(resultsign, self._int, resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001148 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001149 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001150 return ans
1151
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001152 op1 = _WorkRep(self)
1153 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001154
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001155 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001156 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001157 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001158
1159 return ans
1160 __rmul__ = __mul__
1161
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001162 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001163 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001164 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001165 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001166 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001167
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001168 if context is None:
1169 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001170
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001171 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001172
1173 if self._is_special or other._is_special:
1174 ans = self._check_nans(other, context)
1175 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001176 return ans
1177
1178 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001179 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001180
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001181 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001182 return Infsign[sign]
1183
1184 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001185 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001186 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001187
1188 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001189 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001190 if not self:
1191 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001192 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001193
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001194 if not self:
1195 exp = self._exp - other._exp
1196 coeff = 0
1197 else:
1198 # OK, so neither = 0, INF or NaN
1199 shift = len(other._int) - len(self._int) + context.prec + 1
1200 exp = self._exp - other._exp - shift
1201 op1 = _WorkRep(self)
1202 op2 = _WorkRep(other)
1203 if shift >= 0:
1204 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1205 else:
1206 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1207 if remainder:
1208 # result is not exact; adjust to ensure correct rounding
1209 if coeff % 5 == 0:
1210 coeff += 1
1211 else:
1212 # result is exact; get as close to ideal exponent as possible
1213 ideal_exp = self._exp - other._exp
1214 while exp < ideal_exp and coeff % 10 == 0:
1215 coeff //= 10
1216 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001217
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001218 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001219 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001220
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001221 def _divide(self, other, context):
1222 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001223
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001224 Assumes that neither self nor other is a NaN, that self is not
1225 infinite and that other is nonzero.
1226 """
1227 sign = self._sign ^ other._sign
1228 if other._isinfinity():
1229 ideal_exp = self._exp
1230 else:
1231 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001232
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001233 expdiff = self.adjusted() - other.adjusted()
1234 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001235 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001236 self._rescale(ideal_exp, context.rounding))
1237 if expdiff <= context.prec:
1238 op1 = _WorkRep(self)
1239 op2 = _WorkRep(other)
1240 if op1.exp >= op2.exp:
1241 op1.int *= 10**(op1.exp - op2.exp)
1242 else:
1243 op2.int *= 10**(op2.exp - op1.exp)
1244 q, r = divmod(op1.int, op2.int)
1245 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001246 return (_dec_from_triple(sign, str(q), 0),
1247 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001248
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001249 # Here the quotient is too large to be representable
1250 ans = context._raise_error(DivisionImpossible,
1251 'quotient too large in //, % or divmod')
1252 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001253
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001254 def __rtruediv__(self, other, context=None):
1255 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001256 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001257 if other is NotImplemented:
1258 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001259 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001260
1261 def __divmod__(self, other, context=None):
1262 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001263 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001264 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001265 other = _convert_other(other)
1266 if other is NotImplemented:
1267 return other
1268
1269 if context is None:
1270 context = getcontext()
1271
1272 ans = self._check_nans(other, context)
1273 if ans:
1274 return (ans, ans)
1275
1276 sign = self._sign ^ other._sign
1277 if self._isinfinity():
1278 if other._isinfinity():
1279 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1280 return ans, ans
1281 else:
1282 return (Infsign[sign],
1283 context._raise_error(InvalidOperation, 'INF % x'))
1284
1285 if not other:
1286 if not self:
1287 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1288 return ans, ans
1289 else:
1290 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1291 context._raise_error(InvalidOperation, 'x % 0'))
1292
1293 quotient, remainder = self._divide(other, context)
1294 if context._rounding_decision == ALWAYS_ROUND:
1295 remainder = remainder._fix(context)
1296 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001297
1298 def __rdivmod__(self, other, context=None):
1299 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001300 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001301 if other is NotImplemented:
1302 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001303 return other.__divmod__(self, context=context)
1304
1305 def __mod__(self, other, context=None):
1306 """
1307 self % other
1308 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001309 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001310 if other is NotImplemented:
1311 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001312
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001313 if context is None:
1314 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001315
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001316 ans = self._check_nans(other, context)
1317 if ans:
1318 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001319
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001320 if self._isinfinity():
1321 return context._raise_error(InvalidOperation, 'INF % x')
1322 elif not other:
1323 if self:
1324 return context._raise_error(InvalidOperation, 'x % 0')
1325 else:
1326 return context._raise_error(DivisionUndefined, '0 % 0')
1327
1328 remainder = self._divide(other, context)[1]
1329 if context._rounding_decision == ALWAYS_ROUND:
1330 remainder = remainder._fix(context)
1331 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001332
1333 def __rmod__(self, other, context=None):
1334 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001335 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001336 if other is NotImplemented:
1337 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001338 return other.__mod__(self, context=context)
1339
1340 def remainder_near(self, other, context=None):
1341 """
1342 Remainder nearest to 0- abs(remainder-near) <= other/2
1343 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001344 if context is None:
1345 context = getcontext()
1346
1347 other = _convert_other(other, raiseit=True)
1348
1349 ans = self._check_nans(other, context)
1350 if ans:
1351 return ans
1352
1353 # self == +/-infinity -> InvalidOperation
1354 if self._isinfinity():
1355 return context._raise_error(InvalidOperation,
1356 'remainder_near(infinity, x)')
1357
1358 # other == 0 -> either InvalidOperation or DivisionUndefined
1359 if not other:
1360 if self:
1361 return context._raise_error(InvalidOperation,
1362 'remainder_near(x, 0)')
1363 else:
1364 return context._raise_error(DivisionUndefined,
1365 'remainder_near(0, 0)')
1366
1367 # other = +/-infinity -> remainder = self
1368 if other._isinfinity():
1369 ans = Decimal(self)
1370 return ans._fix(context)
1371
1372 # self = 0 -> remainder = self, with ideal exponent
1373 ideal_exponent = min(self._exp, other._exp)
1374 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001375 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001376 return ans._fix(context)
1377
1378 # catch most cases of large or small quotient
1379 expdiff = self.adjusted() - other.adjusted()
1380 if expdiff >= context.prec + 1:
1381 # expdiff >= prec+1 => abs(self/other) > 10**prec
1382 return context._raise_error(DivisionImpossible)
1383 if expdiff <= -2:
1384 # expdiff <= -2 => abs(self/other) < 0.1
1385 ans = self._rescale(ideal_exponent, context.rounding)
1386 return ans._fix(context)
1387
1388 # adjust both arguments to have the same exponent, then divide
1389 op1 = _WorkRep(self)
1390 op2 = _WorkRep(other)
1391 if op1.exp >= op2.exp:
1392 op1.int *= 10**(op1.exp - op2.exp)
1393 else:
1394 op2.int *= 10**(op2.exp - op1.exp)
1395 q, r = divmod(op1.int, op2.int)
1396 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1397 # 10**ideal_exponent. Apply correction to ensure that
1398 # abs(remainder) <= abs(other)/2
1399 if 2*r + (q&1) > op2.int:
1400 r -= op2.int
1401 q += 1
1402
1403 if q >= 10**context.prec:
1404 return context._raise_error(DivisionImpossible)
1405
1406 # result has same sign as self unless r is negative
1407 sign = self._sign
1408 if r < 0:
1409 sign = 1-sign
1410 r = -r
1411
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001412 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001413 return ans._fix(context)
1414
1415 def __floordiv__(self, other, context=None):
1416 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001417 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001418 if other is NotImplemented:
1419 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001420
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001421 if context is None:
1422 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001423
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001424 ans = self._check_nans(other, context)
1425 if ans:
1426 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001427
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001428 if self._isinfinity():
1429 if other._isinfinity():
1430 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001431 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001432 return Infsign[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001433
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001434 if not other:
1435 if self:
1436 return context._raise_error(DivisionByZero, 'x // 0',
1437 self._sign ^ other._sign)
1438 else:
1439 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001440
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001441 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001442
1443 def __rfloordiv__(self, other, context=None):
1444 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001445 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001446 if other is NotImplemented:
1447 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001448 return other.__floordiv__(self, context=context)
1449
1450 def __float__(self):
1451 """Float representation."""
1452 return float(str(self))
1453
1454 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001455 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001456 if self._is_special:
1457 if self._isnan():
1458 context = getcontext()
1459 return context._raise_error(InvalidContext)
1460 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001461 raise OverflowError("Cannot convert infinity to int")
1462 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001463 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001464 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001465 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001466 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001467
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001468 def _fix_nan(self, context):
1469 """Decapitate the payload of a NaN to fit the context"""
1470 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001471
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001472 # maximum length of payload is precision if _clamp=0,
1473 # precision-1 if _clamp=1.
1474 max_payload_len = context.prec - context._clamp
1475 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001476 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1477 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001478 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001479
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001480 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001481 """Round if it is necessary to keep self within prec precision.
1482
1483 Rounds and fixes the exponent. Does not raise on a sNaN.
1484
1485 Arguments:
1486 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001487 context - context used.
1488 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001489
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001490 if context is None:
1491 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001492
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001493 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001494 if self._isnan():
1495 # decapitate payload if necessary
1496 return self._fix_nan(context)
1497 else:
1498 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001499 return Decimal(self)
1500
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001501 # if self is zero then exponent should be between Etiny and
1502 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1503 Etiny = context.Etiny()
1504 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001505 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001506 exp_max = [context.Emax, Etop][context._clamp]
1507 new_exp = min(max(self._exp, Etiny), exp_max)
1508 if new_exp != self._exp:
1509 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001510 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001511 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001512 return Decimal(self)
1513
1514 # exp_min is the smallest allowable exponent of the result,
1515 # equal to max(self.adjusted()-context.prec+1, Etiny)
1516 exp_min = len(self._int) + self._exp - context.prec
1517 if exp_min > Etop:
1518 # overflow: exp_min > Etop iff self.adjusted() > Emax
1519 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001520 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001521 return context._raise_error(Overflow, 'above Emax', self._sign)
1522 self_is_subnormal = exp_min < Etiny
1523 if self_is_subnormal:
1524 context._raise_error(Subnormal)
1525 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001526
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001527 # round if self has too many digits
1528 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001529 context._raise_error(Rounded)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001530 digits = len(self._int) + self._exp - exp_min
1531 if digits < 0:
1532 self = _dec_from_triple(self._sign, '1', exp_min-1)
1533 digits = 0
1534 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1535 changed = this_function(digits)
1536 coeff = self._int[:digits] or '0'
1537 if changed == 1:
1538 coeff = str(int(coeff)+1)
1539 ans = _dec_from_triple(self._sign, coeff, exp_min)
1540
1541 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001542 context._raise_error(Inexact)
1543 if self_is_subnormal:
1544 context._raise_error(Underflow)
1545 if not ans:
1546 # raise Clamped on underflow to 0
1547 context._raise_error(Clamped)
1548 elif len(ans._int) == context.prec+1:
1549 # we get here only if rescaling rounds the
1550 # cofficient up to exactly 10**context.prec
1551 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001552 ans = _dec_from_triple(ans._sign,
1553 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001554 else:
1555 # Inexact and Rounded have already been raised
1556 ans = context._raise_error(Overflow, 'above Emax',
1557 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001558 return ans
1559
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001560 # fold down if _clamp == 1 and self has too few digits
1561 if context._clamp == 1 and self._exp > Etop:
1562 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001563 self_padded = self._int + '0'*(self._exp - Etop)
1564 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001565
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001566 # here self was representable to begin with; return unchanged
1567 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001568
1569 _pick_rounding_function = {}
1570
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001571 # for each of the rounding functions below:
1572 # self is a finite, nonzero Decimal
1573 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001574 #
1575 # each function returns either -1, 0, or 1, as follows:
1576 # 1 indicates that self should be rounded up (away from zero)
1577 # 0 indicates that self should be truncated, and that all the
1578 # digits to be truncated are zeros (so the value is unchanged)
1579 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001580
1581 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001582 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001583 if _all_zeros(self._int, prec):
1584 return 0
1585 else:
1586 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001587
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001588 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001589 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001590 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001591
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001592 def _round_half_up(self, prec):
1593 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001594 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001595 return 1
1596 elif _all_zeros(self._int, prec):
1597 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001598 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001599 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001600
1601 def _round_half_down(self, prec):
1602 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001603 if _exact_half(self._int, prec):
1604 return -1
1605 else:
1606 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001607
1608 def _round_half_even(self, prec):
1609 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001610 if _exact_half(self._int, prec) and \
1611 (prec == 0 or self._int[prec-1] in '02468'):
1612 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001613 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001614 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001615
1616 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001617 """Rounds up (not away from 0 if negative.)"""
1618 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001619 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001620 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001621 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001622
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001623 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001624 """Rounds down (not towards 0 if negative)"""
1625 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001626 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001627 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001628 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001629
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001630 def _round_05up(self, prec):
1631 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001632 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001633 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001634 else:
1635 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001636
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001637 def fma(self, other, third, context=None):
1638 """Fused multiply-add.
1639
1640 Returns self*other+third with no rounding of the intermediate
1641 product self*other.
1642
1643 self and other are multiplied together, with no rounding of
1644 the result. The third operand is then added to the result,
1645 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001646 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001647
1648 other = _convert_other(other, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001649
1650 # compute product; raise InvalidOperation if either operand is
1651 # a signaling NaN or if the product is zero times infinity.
1652 if self._is_special or other._is_special:
1653 if context is None:
1654 context = getcontext()
1655 if self._exp == 'N':
1656 return context._raise_error(InvalidOperation, 'sNaN',
1657 1, self)
1658 if other._exp == 'N':
1659 return context._raise_error(InvalidOperation, 'sNaN',
1660 1, other)
1661 if self._exp == 'n':
1662 product = self
1663 elif other._exp == 'n':
1664 product = other
1665 elif self._exp == 'F':
1666 if not other:
1667 return context._raise_error(InvalidOperation,
1668 'INF * 0 in fma')
1669 product = Infsign[self._sign ^ other._sign]
1670 elif other._exp == 'F':
1671 if not self:
1672 return context._raise_error(InvalidOperation,
1673 '0 * INF in fma')
1674 product = Infsign[self._sign ^ other._sign]
1675 else:
1676 product = _dec_from_triple(self._sign ^ other._sign,
1677 str(int(self._int) * int(other._int)),
1678 self._exp + other._exp)
1679
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001680 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001681 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001682
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001683 def _power_modulo(self, other, modulo, context=None):
1684 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001685
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001686 # if can't convert other and modulo to Decimal, raise
1687 # TypeError; there's no point returning NotImplemented (no
1688 # equivalent of __rpow__ for three argument pow)
1689 other = _convert_other(other, raiseit=True)
1690 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001691
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001692 if context is None:
1693 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001694
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001695 # deal with NaNs: if there are any sNaNs then first one wins,
1696 # (i.e. behaviour for NaNs is identical to that of fma)
1697 self_is_nan = self._isnan()
1698 other_is_nan = other._isnan()
1699 modulo_is_nan = modulo._isnan()
1700 if self_is_nan or other_is_nan or modulo_is_nan:
1701 if self_is_nan == 2:
1702 return context._raise_error(InvalidOperation, 'sNaN',
1703 1, self)
1704 if other_is_nan == 2:
1705 return context._raise_error(InvalidOperation, 'sNaN',
1706 1, other)
1707 if modulo_is_nan == 2:
1708 return context._raise_error(InvalidOperation, 'sNaN',
1709 1, modulo)
1710 if self_is_nan:
1711 return self._fix_nan(context)
1712 if other_is_nan:
1713 return other._fix_nan(context)
1714 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001715
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001716 # check inputs: we apply same restrictions as Python's pow()
1717 if not (self._isinteger() and
1718 other._isinteger() and
1719 modulo._isinteger()):
1720 return context._raise_error(InvalidOperation,
1721 'pow() 3rd argument not allowed '
1722 'unless all arguments are integers')
1723 if other < 0:
1724 return context._raise_error(InvalidOperation,
1725 'pow() 2nd argument cannot be '
1726 'negative when 3rd argument specified')
1727 if not modulo:
1728 return context._raise_error(InvalidOperation,
1729 'pow() 3rd argument cannot be 0')
1730
1731 # additional restriction for decimal: the modulus must be less
1732 # than 10**prec in absolute value
1733 if modulo.adjusted() >= context.prec:
1734 return context._raise_error(InvalidOperation,
1735 'insufficient precision: pow() 3rd '
1736 'argument must not have more than '
1737 'precision digits')
1738
1739 # define 0**0 == NaN, for consistency with two-argument pow
1740 # (even though it hurts!)
1741 if not other and not self:
1742 return context._raise_error(InvalidOperation,
1743 'at least one of pow() 1st argument '
1744 'and 2nd argument must be nonzero ;'
1745 '0**0 is not defined')
1746
1747 # compute sign of result
1748 if other._iseven():
1749 sign = 0
1750 else:
1751 sign = self._sign
1752
1753 # convert modulo to a Python integer, and self and other to
1754 # Decimal integers (i.e. force their exponents to be >= 0)
1755 modulo = abs(int(modulo))
1756 base = _WorkRep(self.to_integral_value())
1757 exponent = _WorkRep(other.to_integral_value())
1758
1759 # compute result using integer pow()
1760 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1761 for i in range(exponent.exp):
1762 base = pow(base, 10, modulo)
1763 base = pow(base, exponent.int, modulo)
1764
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001765 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001766
1767 def _power_exact(self, other, p):
1768 """Attempt to compute self**other exactly.
1769
1770 Given Decimals self and other and an integer p, attempt to
1771 compute an exact result for the power self**other, with p
1772 digits of precision. Return None if self**other is not
1773 exactly representable in p digits.
1774
1775 Assumes that elimination of special cases has already been
1776 performed: self and other must both be nonspecial; self must
1777 be positive and not numerically equal to 1; other must be
1778 nonzero. For efficiency, other._exp should not be too large,
1779 so that 10**abs(other._exp) is a feasible calculation."""
1780
1781 # In the comments below, we write x for the value of self and
1782 # y for the value of other. Write x = xc*10**xe and y =
1783 # yc*10**ye.
1784
1785 # The main purpose of this method is to identify the *failure*
1786 # of x**y to be exactly representable with as little effort as
1787 # possible. So we look for cheap and easy tests that
1788 # eliminate the possibility of x**y being exact. Only if all
1789 # these tests are passed do we go on to actually compute x**y.
1790
1791 # Here's the main idea. First normalize both x and y. We
1792 # express y as a rational m/n, with m and n relatively prime
1793 # and n>0. Then for x**y to be exactly representable (at
1794 # *any* precision), xc must be the nth power of a positive
1795 # integer and xe must be divisible by n. If m is negative
1796 # then additionally xc must be a power of either 2 or 5, hence
1797 # a power of 2**n or 5**n.
1798 #
1799 # There's a limit to how small |y| can be: if y=m/n as above
1800 # then:
1801 #
1802 # (1) if xc != 1 then for the result to be representable we
1803 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1804 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1805 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1806 # representable.
1807 #
1808 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1809 # |y| < 1/|xe| then the result is not representable.
1810 #
1811 # Note that since x is not equal to 1, at least one of (1) and
1812 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1813 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1814 #
1815 # There's also a limit to how large y can be, at least if it's
1816 # positive: the normalized result will have coefficient xc**y,
1817 # so if it's representable then xc**y < 10**p, and y <
1818 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1819 # not exactly representable.
1820
1821 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1822 # so |y| < 1/xe and the result is not representable.
1823 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1824 # < 1/nbits(xc).
1825
1826 x = _WorkRep(self)
1827 xc, xe = x.int, x.exp
1828 while xc % 10 == 0:
1829 xc //= 10
1830 xe += 1
1831
1832 y = _WorkRep(other)
1833 yc, ye = y.int, y.exp
1834 while yc % 10 == 0:
1835 yc //= 10
1836 ye += 1
1837
1838 # case where xc == 1: result is 10**(xe*y), with xe*y
1839 # required to be an integer
1840 if xc == 1:
1841 if ye >= 0:
1842 exponent = xe*yc*10**ye
1843 else:
1844 exponent, remainder = divmod(xe*yc, 10**-ye)
1845 if remainder:
1846 return None
1847 if y.sign == 1:
1848 exponent = -exponent
1849 # if other is a nonnegative integer, use ideal exponent
1850 if other._isinteger() and other._sign == 0:
1851 ideal_exponent = self._exp*int(other)
1852 zeros = min(exponent-ideal_exponent, p-1)
1853 else:
1854 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001855 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001856
1857 # case where y is negative: xc must be either a power
1858 # of 2 or a power of 5.
1859 if y.sign == 1:
1860 last_digit = xc % 10
1861 if last_digit in (2,4,6,8):
1862 # quick test for power of 2
1863 if xc & -xc != xc:
1864 return None
1865 # now xc is a power of 2; e is its exponent
1866 e = _nbits(xc)-1
1867 # find e*y and xe*y; both must be integers
1868 if ye >= 0:
1869 y_as_int = yc*10**ye
1870 e = e*y_as_int
1871 xe = xe*y_as_int
1872 else:
1873 ten_pow = 10**-ye
1874 e, remainder = divmod(e*yc, ten_pow)
1875 if remainder:
1876 return None
1877 xe, remainder = divmod(xe*yc, ten_pow)
1878 if remainder:
1879 return None
1880
1881 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1882 return None
1883 xc = 5**e
1884
1885 elif last_digit == 5:
1886 # e >= log_5(xc) if xc is a power of 5; we have
1887 # equality all the way up to xc=5**2658
1888 e = _nbits(xc)*28//65
1889 xc, remainder = divmod(5**e, xc)
1890 if remainder:
1891 return None
1892 while xc % 5 == 0:
1893 xc //= 5
1894 e -= 1
1895 if ye >= 0:
1896 y_as_integer = yc*10**ye
1897 e = e*y_as_integer
1898 xe = xe*y_as_integer
1899 else:
1900 ten_pow = 10**-ye
1901 e, remainder = divmod(e*yc, ten_pow)
1902 if remainder:
1903 return None
1904 xe, remainder = divmod(xe*yc, ten_pow)
1905 if remainder:
1906 return None
1907 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1908 return None
1909 xc = 2**e
1910 else:
1911 return None
1912
1913 if xc >= 10**p:
1914 return None
1915 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001916 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001917
1918 # now y is positive; find m and n such that y = m/n
1919 if ye >= 0:
1920 m, n = yc*10**ye, 1
1921 else:
1922 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1923 return None
1924 xc_bits = _nbits(xc)
1925 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1926 return None
1927 m, n = yc, 10**(-ye)
1928 while m % 2 == n % 2 == 0:
1929 m //= 2
1930 n //= 2
1931 while m % 5 == n % 5 == 0:
1932 m //= 5
1933 n //= 5
1934
1935 # compute nth root of xc*10**xe
1936 if n > 1:
1937 # if 1 < xc < 2**n then xc isn't an nth power
1938 if xc != 1 and xc_bits <= n:
1939 return None
1940
1941 xe, rem = divmod(xe, n)
1942 if rem != 0:
1943 return None
1944
1945 # compute nth root of xc using Newton's method
1946 a = 1 << -(-_nbits(xc)//n) # initial estimate
1947 while True:
1948 q, r = divmod(xc, a**(n-1))
1949 if a <= q:
1950 break
1951 else:
1952 a = (a*(n-1) + q)//n
1953 if not (a == q and r == 0):
1954 return None
1955 xc = a
1956
1957 # now xc*10**xe is the nth root of the original xc*10**xe
1958 # compute mth power of xc*10**xe
1959
1960 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1961 # 10**p and the result is not representable.
1962 if xc > 1 and m > p*100//_log10_lb(xc):
1963 return None
1964 xc = xc**m
1965 xe *= m
1966 if xc > 10**p:
1967 return None
1968
1969 # by this point the result *is* exactly representable
1970 # adjust the exponent to get as close as possible to the ideal
1971 # exponent, if necessary
1972 str_xc = str(xc)
1973 if other._isinteger() and other._sign == 0:
1974 ideal_exponent = self._exp*int(other)
1975 zeros = min(xe-ideal_exponent, p-len(str_xc))
1976 else:
1977 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001978 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001979
1980 def __pow__(self, other, modulo=None, context=None):
1981 """Return self ** other [ % modulo].
1982
1983 With two arguments, compute self**other.
1984
1985 With three arguments, compute (self**other) % modulo. For the
1986 three argument form, the following restrictions on the
1987 arguments hold:
1988
1989 - all three arguments must be integral
1990 - other must be nonnegative
1991 - either self or other (or both) must be nonzero
1992 - modulo must be nonzero and must have at most p digits,
1993 where p is the context precision.
1994
1995 If any of these restrictions is violated the InvalidOperation
1996 flag is raised.
1997
1998 The result of pow(self, other, modulo) is identical to the
1999 result that would be obtained by computing (self**other) %
2000 modulo with unbounded precision, but is computed more
2001 efficiently. It is always exact.
2002 """
2003
2004 if modulo is not None:
2005 return self._power_modulo(other, modulo, context)
2006
2007 other = _convert_other(other)
2008 if other is NotImplemented:
2009 return other
2010
2011 if context is None:
2012 context = getcontext()
2013
2014 # either argument is a NaN => result is NaN
2015 ans = self._check_nans(other, context)
2016 if ans:
2017 return ans
2018
2019 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2020 if not other:
2021 if not self:
2022 return context._raise_error(InvalidOperation, '0 ** 0')
2023 else:
2024 return Dec_p1
2025
2026 # result has sign 1 iff self._sign is 1 and other is an odd integer
2027 result_sign = 0
2028 if self._sign == 1:
2029 if other._isinteger():
2030 if not other._iseven():
2031 result_sign = 1
2032 else:
2033 # -ve**noninteger = NaN
2034 # (-0)**noninteger = 0**noninteger
2035 if self:
2036 return context._raise_error(InvalidOperation,
2037 'x ** y with x negative and y not an integer')
2038 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002039 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002040
2041 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2042 if not self:
2043 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002044 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002045 else:
2046 return Infsign[result_sign]
2047
2048 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002049 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002050 if other._sign == 0:
2051 return Infsign[result_sign]
2052 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002053 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002054
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002055 # 1**other = 1, but the choice of exponent and the flags
2056 # depend on the exponent of self, and on whether other is a
2057 # positive integer, a negative integer, or neither
2058 if self == Dec_p1:
2059 if other._isinteger():
2060 # exp = max(self._exp*max(int(other), 0),
2061 # 1-context.prec) but evaluating int(other) directly
2062 # is dangerous until we know other is small (other
2063 # could be 1e999999999)
2064 if other._sign == 1:
2065 multiplier = 0
2066 elif other > context.prec:
2067 multiplier = context.prec
2068 else:
2069 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002070
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002071 exp = self._exp * multiplier
2072 if exp < 1-context.prec:
2073 exp = 1-context.prec
2074 context._raise_error(Rounded)
2075 else:
2076 context._raise_error(Inexact)
2077 context._raise_error(Rounded)
2078 exp = 1-context.prec
2079
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002080 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002081
2082 # compute adjusted exponent of self
2083 self_adj = self.adjusted()
2084
2085 # self ** infinity is infinity if self > 1, 0 if self < 1
2086 # self ** -infinity is infinity if self < 1, 0 if self > 1
2087 if other._isinfinity():
2088 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002089 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002090 else:
2091 return Infsign[result_sign]
2092
2093 # from here on, the result always goes through the call
2094 # to _fix at the end of this function.
2095 ans = None
2096
2097 # crude test to catch cases of extreme overflow/underflow. If
2098 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2099 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2100 # self**other >= 10**(Emax+1), so overflow occurs. The test
2101 # for underflow is similar.
2102 bound = self._log10_exp_bound() + other.adjusted()
2103 if (self_adj >= 0) == (other._sign == 0):
2104 # self > 1 and other +ve, or self < 1 and other -ve
2105 # possibility of overflow
2106 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002107 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002108 else:
2109 # self > 1 and other -ve, or self < 1 and other +ve
2110 # possibility of underflow to 0
2111 Etiny = context.Etiny()
2112 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002113 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002114
2115 # try for an exact result with precision +1
2116 if ans is None:
2117 ans = self._power_exact(other, context.prec + 1)
2118 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002119 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002120
2121 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2122 if ans is None:
2123 p = context.prec
2124 x = _WorkRep(self)
2125 xc, xe = x.int, x.exp
2126 y = _WorkRep(other)
2127 yc, ye = y.int, y.exp
2128 if y.sign == 1:
2129 yc = -yc
2130
2131 # compute correctly rounded result: start with precision +3,
2132 # then increase precision until result is unambiguously roundable
2133 extra = 3
2134 while True:
2135 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2136 if coeff % (5*10**(len(str(coeff))-p-1)):
2137 break
2138 extra += 3
2139
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002140 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002141
2142 # the specification says that for non-integer other we need to
2143 # raise Inexact, even when the result is actually exact. In
2144 # the same way, we need to raise Underflow here if the result
2145 # is subnormal. (The call to _fix will take care of raising
2146 # Rounded and Subnormal, as usual.)
2147 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002148 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002149 # pad with zeros up to length context.prec+1 if necessary
2150 if len(ans._int) <= context.prec:
2151 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002152 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2153 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002154 if ans.adjusted() < context.Emin:
2155 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002156
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002157 # unlike exp, ln and log10, the power function respects the
2158 # rounding mode; no need to use ROUND_HALF_EVEN here
2159 ans = ans._fix(context)
2160 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002161
2162 def __rpow__(self, other, context=None):
2163 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002164 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002165 if other is NotImplemented:
2166 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002167 return other.__pow__(self, context=context)
2168
2169 def normalize(self, context=None):
2170 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002171
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002172 if context is None:
2173 context = getcontext()
2174
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002175 if self._is_special:
2176 ans = self._check_nans(context=context)
2177 if ans:
2178 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002179
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002180 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002181 if dup._isinfinity():
2182 return dup
2183
2184 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002185 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002186 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002187 end = len(dup._int)
2188 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002189 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002190 exp += 1
2191 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002192 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002193
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002194 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002195 """Quantize self so its exponent is the same as that of exp.
2196
2197 Similar to self._rescale(exp._exp) but with error checking.
2198 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002199 exp = _convert_other(exp, raiseit=True)
2200
2201 if context is None:
2202 context = getcontext()
2203 if rounding is None:
2204 rounding = context.rounding
2205
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002206 if self._is_special or exp._is_special:
2207 ans = self._check_nans(exp, context)
2208 if ans:
2209 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002210
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002211 if exp._isinfinity() or self._isinfinity():
2212 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002213 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002214 return context._raise_error(InvalidOperation,
2215 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002216
2217 # if we're not watching exponents, do a simple rescale
2218 if not watchexp:
2219 ans = self._rescale(exp._exp, rounding)
2220 # raise Inexact and Rounded where appropriate
2221 if ans._exp > self._exp:
2222 context._raise_error(Rounded)
2223 if ans != self:
2224 context._raise_error(Inexact)
2225 return ans
2226
2227 # exp._exp should be between Etiny and Emax
2228 if not (context.Etiny() <= exp._exp <= context.Emax):
2229 return context._raise_error(InvalidOperation,
2230 'target exponent out of bounds in quantize')
2231
2232 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002233 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002234 return ans._fix(context)
2235
2236 self_adjusted = self.adjusted()
2237 if self_adjusted > context.Emax:
2238 return context._raise_error(InvalidOperation,
2239 'exponent of quantize result too large for current context')
2240 if self_adjusted - exp._exp + 1 > context.prec:
2241 return context._raise_error(InvalidOperation,
2242 'quantize result has too many digits for current context')
2243
2244 ans = self._rescale(exp._exp, rounding)
2245 if ans.adjusted() > context.Emax:
2246 return context._raise_error(InvalidOperation,
2247 'exponent of quantize result too large for current context')
2248 if len(ans._int) > context.prec:
2249 return context._raise_error(InvalidOperation,
2250 'quantize result has too many digits for current context')
2251
2252 # raise appropriate flags
2253 if ans._exp > self._exp:
2254 context._raise_error(Rounded)
2255 if ans != self:
2256 context._raise_error(Inexact)
2257 if ans and ans.adjusted() < context.Emin:
2258 context._raise_error(Subnormal)
2259
2260 # call to fix takes care of any necessary folddown
2261 ans = ans._fix(context)
2262 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002263
2264 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002265 """Return True if self and other have the same exponent; otherwise
2266 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002267
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002268 If either operand is a special value, the following rules are used:
2269 * return True if both operands are infinities
2270 * return True if both operands are NaNs
2271 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002272 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002273 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002274 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002275 return (self.is_nan() and other.is_nan() or
2276 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002277 return self._exp == other._exp
2278
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002279 def _rescale(self, exp, rounding):
2280 """Rescale self so that the exponent is exp, either by padding with zeros
2281 or by truncating digits, using the given rounding mode.
2282
2283 Specials are returned without change. This operation is
2284 quiet: it raises no flags, and uses no information from the
2285 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002286
2287 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002288 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002289 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002290 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002291 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002292 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002293 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002294
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002295 if self._exp >= exp:
2296 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002297 return _dec_from_triple(self._sign,
2298 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002299
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002300 # too many digits; round and lose data. If self.adjusted() <
2301 # exp-1, replace self by 10**(exp-1) before rounding
2302 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002303 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002304 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002305 digits = 0
2306 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002307 changed = this_function(digits)
2308 coeff = self._int[:digits] or '0'
2309 if changed == 1:
2310 coeff = str(int(coeff)+1)
2311 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002312
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002313 def to_integral_exact(self, rounding=None, context=None):
2314 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002315
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002316 If no rounding mode is specified, take the rounding mode from
2317 the context. This method raises the Rounded and Inexact flags
2318 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002319
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002320 See also: to_integral_value, which does exactly the same as
2321 this method except that it doesn't raise Inexact or Rounded.
2322 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002323 if self._is_special:
2324 ans = self._check_nans(context=context)
2325 if ans:
2326 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002327 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002328 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002329 return Decimal(self)
2330 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002331 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002332 if context is None:
2333 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002334 if rounding is None:
2335 rounding = context.rounding
2336 context._raise_error(Rounded)
2337 ans = self._rescale(0, rounding)
2338 if ans != self:
2339 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002340 return ans
2341
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002342 def to_integral_value(self, rounding=None, context=None):
2343 """Rounds to the nearest integer, without raising inexact, rounded."""
2344 if context is None:
2345 context = getcontext()
2346 if rounding is None:
2347 rounding = context.rounding
2348 if self._is_special:
2349 ans = self._check_nans(context=context)
2350 if ans:
2351 return ans
2352 return Decimal(self)
2353 if self._exp >= 0:
2354 return Decimal(self)
2355 else:
2356 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002357
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002358 # the method name changed, but we provide also the old one, for compatibility
2359 to_integral = to_integral_value
2360
2361 def sqrt(self, context=None):
2362 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002363 if self._is_special:
2364 ans = self._check_nans(context=context)
2365 if ans:
2366 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002367
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002368 if self._isinfinity() and self._sign == 0:
2369 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002370
2371 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002372 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002373 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002374 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002375
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002376 if context is None:
2377 context = getcontext()
2378
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002379 if self._sign == 1:
2380 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2381
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002382 # At this point self represents a positive number. Let p be
2383 # the desired precision and express self in the form c*100**e
2384 # with c a positive real number and e an integer, c and e
2385 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2386 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2387 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2388 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2389 # the closest integer to sqrt(c) with the even integer chosen
2390 # in the case of a tie.
2391 #
2392 # To ensure correct rounding in all cases, we use the
2393 # following trick: we compute the square root to an extra
2394 # place (precision p+1 instead of precision p), rounding down.
2395 # Then, if the result is inexact and its last digit is 0 or 5,
2396 # we increase the last digit to 1 or 6 respectively; if it's
2397 # exact we leave the last digit alone. Now the final round to
2398 # p places (or fewer in the case of underflow) will round
2399 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002400
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002401 # use an extra digit of precision
2402 prec = context.prec+1
2403
2404 # write argument in the form c*100**e where e = self._exp//2
2405 # is the 'ideal' exponent, to be used if the square root is
2406 # exactly representable. l is the number of 'digits' of c in
2407 # base 100, so that 100**(l-1) <= c < 100**l.
2408 op = _WorkRep(self)
2409 e = op.exp >> 1
2410 if op.exp & 1:
2411 c = op.int * 10
2412 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002413 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002414 c = op.int
2415 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002416
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002417 # rescale so that c has exactly prec base 100 'digits'
2418 shift = prec-l
2419 if shift >= 0:
2420 c *= 100**shift
2421 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002422 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002423 c, remainder = divmod(c, 100**-shift)
2424 exact = not remainder
2425 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002426
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002427 # find n = floor(sqrt(c)) using Newton's method
2428 n = 10**prec
2429 while True:
2430 q = c//n
2431 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002432 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002433 else:
2434 n = n + q >> 1
2435 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002436
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002437 if exact:
2438 # result is exact; rescale to use ideal exponent e
2439 if shift >= 0:
2440 # assert n % 10**shift == 0
2441 n //= 10**shift
2442 else:
2443 n *= 10**-shift
2444 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002445 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002446 # result is not exact; fix last digit as described above
2447 if n % 5 == 0:
2448 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002449
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002450 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002451
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002452 # round, and fit to current context
2453 context = context._shallow_copy()
2454 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002455 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002456 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002457
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002458 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002459
2460 def max(self, other, context=None):
2461 """Returns the larger value.
2462
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002463 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002464 NaN (and signals if one is sNaN). Also rounds.
2465 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002466 other = _convert_other(other, raiseit=True)
2467
2468 if context is None:
2469 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002470
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002471 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002472 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002473 # number is always returned
2474 sn = self._isnan()
2475 on = other._isnan()
2476 if sn or on:
2477 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002478 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002479 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002480 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002481 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002482
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002483 c = self.__cmp__(other)
2484 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002485 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002486 # then an ordering is applied:
2487 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002488 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002489 # positive sign and min returns the operand with the negative sign
2490 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002491 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002492 # the result. This is exactly the ordering used in compare_total.
2493 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002494
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002495 if c == -1:
2496 ans = other
2497 else:
2498 ans = self
2499
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002500 if context._rounding_decision == ALWAYS_ROUND:
2501 return ans._fix(context)
2502 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002503
2504 def min(self, other, context=None):
2505 """Returns the smaller value.
2506
Guido van Rossumd8faa362007-04-27 19:54:29 +00002507 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002508 NaN (and signals if one is sNaN). Also rounds.
2509 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002510 other = _convert_other(other, raiseit=True)
2511
2512 if context is None:
2513 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002514
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002515 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002516 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002517 # number is always returned
2518 sn = self._isnan()
2519 on = other._isnan()
2520 if sn or on:
2521 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002522 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002523 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002524 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002525 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002526
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002527 c = self.__cmp__(other)
2528 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002529 c = self.compare_total(other)
2530
2531 if c == -1:
2532 ans = self
2533 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002534 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002535
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002536 if context._rounding_decision == ALWAYS_ROUND:
2537 return ans._fix(context)
2538 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002539
2540 def _isinteger(self):
2541 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002542 if self._is_special:
2543 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002544 if self._exp >= 0:
2545 return True
2546 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002547 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002548
2549 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002550 """Returns True if self is even. Assumes self is an integer."""
2551 if not self or self._exp > 0:
2552 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002553 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002554
2555 def adjusted(self):
2556 """Return the adjusted exponent of self"""
2557 try:
2558 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002559 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002560 except TypeError:
2561 return 0
2562
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002563 def canonical(self, context=None):
2564 """Returns the same Decimal object.
2565
2566 As we do not have different encodings for the same number, the
2567 received object already is in its canonical form.
2568 """
2569 return self
2570
2571 def compare_signal(self, other, context=None):
2572 """Compares self to the other operand numerically.
2573
2574 It's pretty much like compare(), but all NaNs signal, with signaling
2575 NaNs taking precedence over quiet NaNs.
2576 """
2577 if context is None:
2578 context = getcontext()
2579
2580 self_is_nan = self._isnan()
2581 other_is_nan = other._isnan()
2582 if self_is_nan == 2:
2583 return context._raise_error(InvalidOperation, 'sNaN',
2584 1, self)
2585 if other_is_nan == 2:
2586 return context._raise_error(InvalidOperation, 'sNaN',
2587 1, other)
2588 if self_is_nan:
2589 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2590 1, self)
2591 if other_is_nan:
2592 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2593 1, other)
2594 return self.compare(other, context=context)
2595
2596 def compare_total(self, other):
2597 """Compares self to other using the abstract representations.
2598
2599 This is not like the standard compare, which use their numerical
2600 value. Note that a total ordering is defined for all possible abstract
2601 representations.
2602 """
2603 # if one is negative and the other is positive, it's easy
2604 if self._sign and not other._sign:
2605 return Dec_n1
2606 if not self._sign and other._sign:
2607 return Dec_p1
2608 sign = self._sign
2609
2610 # let's handle both NaN types
2611 self_nan = self._isnan()
2612 other_nan = other._isnan()
2613 if self_nan or other_nan:
2614 if self_nan == other_nan:
2615 if self._int < other._int:
2616 if sign:
2617 return Dec_p1
2618 else:
2619 return Dec_n1
2620 if self._int > other._int:
2621 if sign:
2622 return Dec_n1
2623 else:
2624 return Dec_p1
2625 return Dec_0
2626
2627 if sign:
2628 if self_nan == 1:
2629 return Dec_n1
2630 if other_nan == 1:
2631 return Dec_p1
2632 if self_nan == 2:
2633 return Dec_n1
2634 if other_nan == 2:
2635 return Dec_p1
2636 else:
2637 if self_nan == 1:
2638 return Dec_p1
2639 if other_nan == 1:
2640 return Dec_n1
2641 if self_nan == 2:
2642 return Dec_p1
2643 if other_nan == 2:
2644 return Dec_n1
2645
2646 if self < other:
2647 return Dec_n1
2648 if self > other:
2649 return Dec_p1
2650
2651 if self._exp < other._exp:
2652 if sign:
2653 return Dec_p1
2654 else:
2655 return Dec_n1
2656 if self._exp > other._exp:
2657 if sign:
2658 return Dec_n1
2659 else:
2660 return Dec_p1
2661 return Dec_0
2662
2663
2664 def compare_total_mag(self, other):
2665 """Compares self to other using abstract repr., ignoring sign.
2666
2667 Like compare_total, but with operand's sign ignored and assumed to be 0.
2668 """
2669 s = self.copy_abs()
2670 o = other.copy_abs()
2671 return s.compare_total(o)
2672
2673 def copy_abs(self):
2674 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002675 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002676
2677 def copy_negate(self):
2678 """Returns a copy with the sign inverted."""
2679 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002680 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002681 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002682 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002683
2684 def copy_sign(self, other):
2685 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002686 return _dec_from_triple(other._sign, self._int,
2687 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002688
2689 def exp(self, context=None):
2690 """Returns e ** self."""
2691
2692 if context is None:
2693 context = getcontext()
2694
2695 # exp(NaN) = NaN
2696 ans = self._check_nans(context=context)
2697 if ans:
2698 return ans
2699
2700 # exp(-Infinity) = 0
2701 if self._isinfinity() == -1:
2702 return Dec_0
2703
2704 # exp(0) = 1
2705 if not self:
2706 return Dec_p1
2707
2708 # exp(Infinity) = Infinity
2709 if self._isinfinity() == 1:
2710 return Decimal(self)
2711
2712 # the result is now guaranteed to be inexact (the true
2713 # mathematical result is transcendental). There's no need to
2714 # raise Rounded and Inexact here---they'll always be raised as
2715 # a result of the call to _fix.
2716 p = context.prec
2717 adj = self.adjusted()
2718
2719 # we only need to do any computation for quite a small range
2720 # of adjusted exponents---for example, -29 <= adj <= 10 for
2721 # the default context. For smaller exponent the result is
2722 # indistinguishable from 1 at the given precision, while for
2723 # larger exponent the result either overflows or underflows.
2724 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2725 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002726 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002727 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2728 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002729 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002730 elif self._sign == 0 and adj < -p:
2731 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002732 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002733 elif self._sign == 1 and adj < -p-1:
2734 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002735 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002736 # general case
2737 else:
2738 op = _WorkRep(self)
2739 c, e = op.int, op.exp
2740 if op.sign == 1:
2741 c = -c
2742
2743 # compute correctly rounded result: increase precision by
2744 # 3 digits at a time until we get an unambiguously
2745 # roundable result
2746 extra = 3
2747 while True:
2748 coeff, exp = _dexp(c, e, p+extra)
2749 if coeff % (5*10**(len(str(coeff))-p-1)):
2750 break
2751 extra += 3
2752
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002753 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002754
2755 # at this stage, ans should round correctly with *any*
2756 # rounding mode, not just with ROUND_HALF_EVEN
2757 context = context._shallow_copy()
2758 rounding = context._set_rounding(ROUND_HALF_EVEN)
2759 ans = ans._fix(context)
2760 context.rounding = rounding
2761
2762 return ans
2763
2764 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002765 """Return True if self is canonical; otherwise return False.
2766
2767 Currently, the encoding of a Decimal instance is always
2768 canonical, so this method returns True for any Decimal.
2769 """
2770 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002771
2772 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002773 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002774
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002775 A Decimal instance is considered finite if it is neither
2776 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002777 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002778 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002779
2780 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002781 """Return True if self is infinite; otherwise return False."""
2782 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002783
2784 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002785 """Return True if self is a qNaN or sNaN; otherwise return False."""
2786 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002787
2788 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002789 """Return True if self is a normal number; otherwise return False."""
2790 if self._is_special or not self:
2791 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002792 if context is None:
2793 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002794 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002795
2796 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002797 """Return True if self is a quiet NaN; otherwise return False."""
2798 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002799
2800 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002801 """Return True if self is negative; otherwise return False."""
2802 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002803
2804 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002805 """Return True if self is a signaling NaN; otherwise return False."""
2806 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002807
2808 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002809 """Return True if self is subnormal; otherwise return False."""
2810 if self._is_special or not self:
2811 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002812 if context is None:
2813 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002814 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002815
2816 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002817 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002818 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002819
2820 def _ln_exp_bound(self):
2821 """Compute a lower bound for the adjusted exponent of self.ln().
2822 In other words, compute r such that self.ln() >= 10**r. Assumes
2823 that self is finite and positive and that self != 1.
2824 """
2825
2826 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2827 adj = self._exp + len(self._int) - 1
2828 if adj >= 1:
2829 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2830 return len(str(adj*23//10)) - 1
2831 if adj <= -2:
2832 # argument <= 0.1
2833 return len(str((-1-adj)*23//10)) - 1
2834 op = _WorkRep(self)
2835 c, e = op.int, op.exp
2836 if adj == 0:
2837 # 1 < self < 10
2838 num = str(c-10**-e)
2839 den = str(c)
2840 return len(num) - len(den) - (num < den)
2841 # adj == -1, 0.1 <= self < 1
2842 return e + len(str(10**-e - c)) - 1
2843
2844
2845 def ln(self, context=None):
2846 """Returns the natural (base e) logarithm of self."""
2847
2848 if context is None:
2849 context = getcontext()
2850
2851 # ln(NaN) = NaN
2852 ans = self._check_nans(context=context)
2853 if ans:
2854 return ans
2855
2856 # ln(0.0) == -Infinity
2857 if not self:
2858 return negInf
2859
2860 # ln(Infinity) = Infinity
2861 if self._isinfinity() == 1:
2862 return Inf
2863
2864 # ln(1.0) == 0.0
2865 if self == Dec_p1:
2866 return Dec_0
2867
2868 # ln(negative) raises InvalidOperation
2869 if self._sign == 1:
2870 return context._raise_error(InvalidOperation,
2871 'ln of a negative value')
2872
2873 # result is irrational, so necessarily inexact
2874 op = _WorkRep(self)
2875 c, e = op.int, op.exp
2876 p = context.prec
2877
2878 # correctly rounded result: repeatedly increase precision by 3
2879 # until we get an unambiguously roundable result
2880 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2881 while True:
2882 coeff = _dlog(c, e, places)
2883 # assert len(str(abs(coeff)))-p >= 1
2884 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2885 break
2886 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002887 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002888
2889 context = context._shallow_copy()
2890 rounding = context._set_rounding(ROUND_HALF_EVEN)
2891 ans = ans._fix(context)
2892 context.rounding = rounding
2893 return ans
2894
2895 def _log10_exp_bound(self):
2896 """Compute a lower bound for the adjusted exponent of self.log10().
2897 In other words, find r such that self.log10() >= 10**r.
2898 Assumes that self is finite and positive and that self != 1.
2899 """
2900
2901 # For x >= 10 or x < 0.1 we only need a bound on the integer
2902 # part of log10(self), and this comes directly from the
2903 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2904 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2905 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2906
2907 adj = self._exp + len(self._int) - 1
2908 if adj >= 1:
2909 # self >= 10
2910 return len(str(adj))-1
2911 if adj <= -2:
2912 # self < 0.1
2913 return len(str(-1-adj))-1
2914 op = _WorkRep(self)
2915 c, e = op.int, op.exp
2916 if adj == 0:
2917 # 1 < self < 10
2918 num = str(c-10**-e)
2919 den = str(231*c)
2920 return len(num) - len(den) - (num < den) + 2
2921 # adj == -1, 0.1 <= self < 1
2922 num = str(10**-e-c)
2923 return len(num) + e - (num < "231") - 1
2924
2925 def log10(self, context=None):
2926 """Returns the base 10 logarithm of self."""
2927
2928 if context is None:
2929 context = getcontext()
2930
2931 # log10(NaN) = NaN
2932 ans = self._check_nans(context=context)
2933 if ans:
2934 return ans
2935
2936 # log10(0.0) == -Infinity
2937 if not self:
2938 return negInf
2939
2940 # log10(Infinity) = Infinity
2941 if self._isinfinity() == 1:
2942 return Inf
2943
2944 # log10(negative or -Infinity) raises InvalidOperation
2945 if self._sign == 1:
2946 return context._raise_error(InvalidOperation,
2947 'log10 of a negative value')
2948
2949 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002950 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002951 # answer may need rounding
2952 ans = Decimal(self._exp + len(self._int) - 1)
2953 else:
2954 # result is irrational, so necessarily inexact
2955 op = _WorkRep(self)
2956 c, e = op.int, op.exp
2957 p = context.prec
2958
2959 # correctly rounded result: repeatedly increase precision
2960 # until result is unambiguously roundable
2961 places = p-self._log10_exp_bound()+2
2962 while True:
2963 coeff = _dlog10(c, e, places)
2964 # assert len(str(abs(coeff)))-p >= 1
2965 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2966 break
2967 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002968 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002969
2970 context = context._shallow_copy()
2971 rounding = context._set_rounding(ROUND_HALF_EVEN)
2972 ans = ans._fix(context)
2973 context.rounding = rounding
2974 return ans
2975
2976 def logb(self, context=None):
2977 """ Returns the exponent of the magnitude of self's MSD.
2978
2979 The result is the integer which is the exponent of the magnitude
2980 of the most significant digit of self (as though it were truncated
2981 to a single digit while maintaining the value of that digit and
2982 without limiting the resulting exponent).
2983 """
2984 # logb(NaN) = NaN
2985 ans = self._check_nans(context=context)
2986 if ans:
2987 return ans
2988
2989 if context is None:
2990 context = getcontext()
2991
2992 # logb(+/-Inf) = +Inf
2993 if self._isinfinity():
2994 return Inf
2995
2996 # logb(0) = -Inf, DivisionByZero
2997 if not self:
2998 return context._raise_error(DivisionByZero, 'logb(0)', 1)
2999
3000 # otherwise, simply return the adjusted exponent of self, as a
3001 # Decimal. Note that no attempt is made to fit the result
3002 # into the current context.
3003 return Decimal(self.adjusted())
3004
3005 def _islogical(self):
3006 """Return True if self is a logical operand.
3007
3008 For being logical, it must be a finite numbers with a sign of 0,
3009 an exponent of 0, and a coefficient whose digits must all be
3010 either 0 or 1.
3011 """
3012 if self._sign != 0 or self._exp != 0:
3013 return False
3014 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003015 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003016 return False
3017 return True
3018
3019 def _fill_logical(self, context, opa, opb):
3020 dif = context.prec - len(opa)
3021 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003022 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003023 elif dif < 0:
3024 opa = opa[-context.prec:]
3025 dif = context.prec - len(opb)
3026 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003027 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003028 elif dif < 0:
3029 opb = opb[-context.prec:]
3030 return opa, opb
3031
3032 def logical_and(self, other, context=None):
3033 """Applies an 'and' operation between self and other's digits."""
3034 if context is None:
3035 context = getcontext()
3036 if not self._islogical() or not other._islogical():
3037 return context._raise_error(InvalidOperation)
3038
3039 # fill to context.prec
3040 (opa, opb) = self._fill_logical(context, self._int, other._int)
3041
3042 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003043 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3044 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003045
3046 def logical_invert(self, context=None):
3047 """Invert all its digits."""
3048 if context is None:
3049 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003050 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3051 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003052
3053 def logical_or(self, other, context=None):
3054 """Applies an 'or' operation between self and other's digits."""
3055 if context is None:
3056 context = getcontext()
3057 if not self._islogical() or not other._islogical():
3058 return context._raise_error(InvalidOperation)
3059
3060 # fill to context.prec
3061 (opa, opb) = self._fill_logical(context, self._int, other._int)
3062
3063 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003064 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3065 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003066
3067 def logical_xor(self, other, context=None):
3068 """Applies an 'xor' operation between self and other's digits."""
3069 if context is None:
3070 context = getcontext()
3071 if not self._islogical() or not other._islogical():
3072 return context._raise_error(InvalidOperation)
3073
3074 # fill to context.prec
3075 (opa, opb) = self._fill_logical(context, self._int, other._int)
3076
3077 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003078 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3079 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003080
3081 def max_mag(self, other, context=None):
3082 """Compares the values numerically with their sign ignored."""
3083 other = _convert_other(other, raiseit=True)
3084
3085 if context is None:
3086 context = getcontext()
3087
3088 if self._is_special or other._is_special:
3089 # If one operand is a quiet NaN and the other is number, then the
3090 # number is always returned
3091 sn = self._isnan()
3092 on = other._isnan()
3093 if sn or on:
3094 if on == 1 and sn != 2:
3095 return self._fix_nan(context)
3096 if sn == 1 and on != 2:
3097 return other._fix_nan(context)
3098 return self._check_nans(other, context)
3099
3100 c = self.copy_abs().__cmp__(other.copy_abs())
3101 if c == 0:
3102 c = self.compare_total(other)
3103
3104 if c == -1:
3105 ans = other
3106 else:
3107 ans = self
3108
3109 if context._rounding_decision == ALWAYS_ROUND:
3110 return ans._fix(context)
3111 return ans
3112
3113 def min_mag(self, other, context=None):
3114 """Compares the values numerically with their sign ignored."""
3115 other = _convert_other(other, raiseit=True)
3116
3117 if context is None:
3118 context = getcontext()
3119
3120 if self._is_special or other._is_special:
3121 # If one operand is a quiet NaN and the other is number, then the
3122 # number is always returned
3123 sn = self._isnan()
3124 on = other._isnan()
3125 if sn or on:
3126 if on == 1 and sn != 2:
3127 return self._fix_nan(context)
3128 if sn == 1 and on != 2:
3129 return other._fix_nan(context)
3130 return self._check_nans(other, context)
3131
3132 c = self.copy_abs().__cmp__(other.copy_abs())
3133 if c == 0:
3134 c = self.compare_total(other)
3135
3136 if c == -1:
3137 ans = self
3138 else:
3139 ans = other
3140
3141 if context._rounding_decision == ALWAYS_ROUND:
3142 return ans._fix(context)
3143 return ans
3144
3145 def next_minus(self, context=None):
3146 """Returns the largest representable number smaller than itself."""
3147 if context is None:
3148 context = getcontext()
3149
3150 ans = self._check_nans(context=context)
3151 if ans:
3152 return ans
3153
3154 if self._isinfinity() == -1:
3155 return negInf
3156 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003157 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003158
3159 context = context.copy()
3160 context._set_rounding(ROUND_FLOOR)
3161 context._ignore_all_flags()
3162 new_self = self._fix(context)
3163 if new_self != self:
3164 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003165 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3166 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003167
3168 def next_plus(self, context=None):
3169 """Returns the smallest representable number larger than itself."""
3170 if context is None:
3171 context = getcontext()
3172
3173 ans = self._check_nans(context=context)
3174 if ans:
3175 return ans
3176
3177 if self._isinfinity() == 1:
3178 return Inf
3179 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003180 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003181
3182 context = context.copy()
3183 context._set_rounding(ROUND_CEILING)
3184 context._ignore_all_flags()
3185 new_self = self._fix(context)
3186 if new_self != self:
3187 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003188 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3189 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003190
3191 def next_toward(self, other, context=None):
3192 """Returns the number closest to self, in the direction towards other.
3193
3194 The result is the closest representable number to self
3195 (excluding self) that is in the direction towards other,
3196 unless both have the same value. If the two operands are
3197 numerically equal, then the result is a copy of self with the
3198 sign set to be the same as the sign of other.
3199 """
3200 other = _convert_other(other, raiseit=True)
3201
3202 if context is None:
3203 context = getcontext()
3204
3205 ans = self._check_nans(other, context)
3206 if ans:
3207 return ans
3208
3209 comparison = self.__cmp__(other)
3210 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003211 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003212
3213 if comparison == -1:
3214 ans = self.next_plus(context)
3215 else: # comparison == 1
3216 ans = self.next_minus(context)
3217
3218 # decide which flags to raise using value of ans
3219 if ans._isinfinity():
3220 context._raise_error(Overflow,
3221 'Infinite result from next_toward',
3222 ans._sign)
3223 context._raise_error(Rounded)
3224 context._raise_error(Inexact)
3225 elif ans.adjusted() < context.Emin:
3226 context._raise_error(Underflow)
3227 context._raise_error(Subnormal)
3228 context._raise_error(Rounded)
3229 context._raise_error(Inexact)
3230 # if precision == 1 then we don't raise Clamped for a
3231 # result 0E-Etiny.
3232 if not ans:
3233 context._raise_error(Clamped)
3234
3235 return ans
3236
3237 def number_class(self, context=None):
3238 """Returns an indication of the class of self.
3239
3240 The class is one of the following strings:
3241 -sNaN
3242 -NaN
3243 -Infinity
3244 -Normal
3245 -Subnormal
3246 -Zero
3247 +Zero
3248 +Subnormal
3249 +Normal
3250 +Infinity
3251 """
3252 if self.is_snan():
3253 return "sNaN"
3254 if self.is_qnan():
3255 return "NaN"
3256 inf = self._isinfinity()
3257 if inf == 1:
3258 return "+Infinity"
3259 if inf == -1:
3260 return "-Infinity"
3261 if self.is_zero():
3262 if self._sign:
3263 return "-Zero"
3264 else:
3265 return "+Zero"
3266 if context is None:
3267 context = getcontext()
3268 if self.is_subnormal(context=context):
3269 if self._sign:
3270 return "-Subnormal"
3271 else:
3272 return "+Subnormal"
3273 # just a normal, regular, boring number, :)
3274 if self._sign:
3275 return "-Normal"
3276 else:
3277 return "+Normal"
3278
3279 def radix(self):
3280 """Just returns 10, as this is Decimal, :)"""
3281 return Decimal(10)
3282
3283 def rotate(self, other, context=None):
3284 """Returns a rotated copy of self, value-of-other times."""
3285 if context is None:
3286 context = getcontext()
3287
3288 ans = self._check_nans(other, context)
3289 if ans:
3290 return ans
3291
3292 if other._exp != 0:
3293 return context._raise_error(InvalidOperation)
3294 if not (-context.prec <= int(other) <= context.prec):
3295 return context._raise_error(InvalidOperation)
3296
3297 if self._isinfinity():
3298 return Decimal(self)
3299
3300 # get values, pad if necessary
3301 torot = int(other)
3302 rotdig = self._int
3303 topad = context.prec - len(rotdig)
3304 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003305 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003306
3307 # let's rotate!
3308 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003309 return _dec_from_triple(self._sign,
3310 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003311
3312 def scaleb (self, other, context=None):
3313 """Returns self operand after adding the second value to its exp."""
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 liminf = -2 * (context.Emax + context.prec)
3324 limsup = 2 * (context.Emax + context.prec)
3325 if not (liminf <= int(other) <= limsup):
3326 return context._raise_error(InvalidOperation)
3327
3328 if self._isinfinity():
3329 return Decimal(self)
3330
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003331 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003332 d = d._fix(context)
3333 return d
3334
3335 def shift(self, other, context=None):
3336 """Returns a shifted copy of self, value-of-other times."""
3337 if context is None:
3338 context = getcontext()
3339
3340 ans = self._check_nans(other, context)
3341 if ans:
3342 return ans
3343
3344 if other._exp != 0:
3345 return context._raise_error(InvalidOperation)
3346 if not (-context.prec <= int(other) <= context.prec):
3347 return context._raise_error(InvalidOperation)
3348
3349 if self._isinfinity():
3350 return Decimal(self)
3351
3352 # get values, pad if necessary
3353 torot = int(other)
3354 if not torot:
3355 return Decimal(self)
3356 rotdig = self._int
3357 topad = context.prec - len(rotdig)
3358 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003359 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003360
3361 # let's shift!
3362 if torot < 0:
3363 rotated = rotdig[:torot]
3364 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003365 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003366 rotated = rotated[-context.prec:]
3367
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003368 return _dec_from_triple(self._sign,
3369 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003370
Guido van Rossumd8faa362007-04-27 19:54:29 +00003371 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003372 def __reduce__(self):
3373 return (self.__class__, (str(self),))
3374
3375 def __copy__(self):
3376 if type(self) == Decimal:
3377 return self # I'm immutable; therefore I am my own clone
3378 return self.__class__(str(self))
3379
3380 def __deepcopy__(self, memo):
3381 if type(self) == Decimal:
3382 return self # My components are also immutable
3383 return self.__class__(str(self))
3384
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003385def _dec_from_triple(sign, coefficient, exponent, special=False):
3386 """Create a decimal instance directly, without any validation,
3387 normalization (e.g. removal of leading zeros) or argument
3388 conversion.
3389
3390 This function is for *internal use only*.
3391 """
3392
3393 self = object.__new__(Decimal)
3394 self._sign = sign
3395 self._int = coefficient
3396 self._exp = exponent
3397 self._is_special = special
3398
3399 return self
3400
Guido van Rossumd8faa362007-04-27 19:54:29 +00003401##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003402
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003403
3404# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003405rounding_functions = [name for name in Decimal.__dict__.keys()
3406 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003407for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003408 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003409 globalname = name[1:].upper()
3410 val = globals()[globalname]
3411 Decimal._pick_rounding_function[val] = name
3412
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003413del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003414
Thomas Wouters89f507f2006-12-13 04:49:30 +00003415class _ContextManager(object):
3416 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003417
Thomas Wouters89f507f2006-12-13 04:49:30 +00003418 Sets a copy of the supplied context in __enter__() and restores
3419 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003420 """
3421 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003422 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003423 def __enter__(self):
3424 self.saved_context = getcontext()
3425 setcontext(self.new_context)
3426 return self.new_context
3427 def __exit__(self, t, v, tb):
3428 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003429
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003430class Context(object):
3431 """Contains the context for a Decimal instance.
3432
3433 Contains:
3434 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003435 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003436 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003437 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003438 raised when it is caused. Otherwise, a value is
3439 substituted in.
3440 flags - When an exception is caused, flags[exception] is incremented.
3441 (Whether or not the trap_enabler is set)
3442 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003443 Emin - Minimum exponent
3444 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003445 capitals - If 1, 1*10^1 is printed as 1E+1.
3446 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003447 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003448 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003449
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003450 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003451 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003452 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003453 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003454 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003455 _ignored_flags=None):
3456 if flags is None:
3457 flags = []
3458 if _ignored_flags is None:
3459 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003460 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003461 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003462 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003463 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003464 for name, val in locals().items():
3465 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003466 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003467 else:
3468 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003469 del self.self
3470
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003471 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003472 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003473 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003474 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3475 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3476 % vars(self))
3477 names = [f.__name__ for f, v in self.flags.items() if v]
3478 s.append('flags=[' + ', '.join(names) + ']')
3479 names = [t.__name__ for t, v in self.traps.items() if v]
3480 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003481 return ', '.join(s) + ')'
3482
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003483 def clear_flags(self):
3484 """Reset all flags to zero"""
3485 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003486 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003487
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003488 def _shallow_copy(self):
3489 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003490 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003491 self._rounding_decision, self.Emin, self.Emax,
3492 self.capitals, self._clamp, self._ignored_flags)
3493 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003494
3495 def copy(self):
3496 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003497 nc = Context(self.prec, self.rounding, self.traps.copy(),
3498 self.flags.copy(), self._rounding_decision, self.Emin,
3499 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003500 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003501 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003502
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003503 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003504 """Handles an error
3505
3506 If the flag is in _ignored_flags, returns the default response.
3507 Otherwise, it increments the flag, then, if the corresponding
3508 trap_enabler is set, it reaises the exception. Otherwise, it returns
3509 the default value after incrementing the flag.
3510 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003511 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003512 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003513 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003514 return error().handle(self, *args)
3515
3516 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003517 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003518 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003519 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003520
3521 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003522 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003523 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003524
3525 def _ignore_all_flags(self):
3526 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003527 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003528
3529 def _ignore_flags(self, *flags):
3530 """Ignore the flags, if they are raised"""
3531 # Do not mutate-- This way, copies of a context leave the original
3532 # alone.
3533 self._ignored_flags = (self._ignored_flags + list(flags))
3534 return list(flags)
3535
3536 def _regard_flags(self, *flags):
3537 """Stop ignoring the flags, if they are raised"""
3538 if flags and isinstance(flags[0], (tuple,list)):
3539 flags = flags[0]
3540 for flag in flags:
3541 self._ignored_flags.remove(flag)
3542
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003543 def __hash__(self):
3544 """A Context cannot be hashed."""
3545 # We inherit object.__hash__, so we must deny this explicitly
Guido van Rossumd8faa362007-04-27 19:54:29 +00003546 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003547
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003548 def Etiny(self):
3549 """Returns Etiny (= Emin - prec + 1)"""
3550 return int(self.Emin - self.prec + 1)
3551
3552 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003553 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003554 return int(self.Emax - self.prec + 1)
3555
3556 def _set_rounding_decision(self, type):
3557 """Sets the rounding decision.
3558
3559 Sets the rounding decision, and returns the current (previous)
3560 rounding decision. Often used like:
3561
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003562 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003563 # That so you don't change the calling context
3564 # if an error occurs in the middle (say DivisionImpossible is raised).
3565
3566 rounding = context._set_rounding_decision(NEVER_ROUND)
3567 instance = instance / Decimal(2)
3568 context._set_rounding_decision(rounding)
3569
3570 This will make it not round for that operation.
3571 """
3572
3573 rounding = self._rounding_decision
3574 self._rounding_decision = type
3575 return rounding
3576
3577 def _set_rounding(self, type):
3578 """Sets the rounding type.
3579
3580 Sets the rounding type, and returns the current (previous)
3581 rounding type. Often used like:
3582
3583 context = context.copy()
3584 # so you don't change the calling context
3585 # if an error occurs in the middle.
3586 rounding = context._set_rounding(ROUND_UP)
3587 val = self.__sub__(other, context=context)
3588 context._set_rounding(rounding)
3589
3590 This will make it round up for that operation.
3591 """
3592 rounding = self.rounding
3593 self.rounding= type
3594 return rounding
3595
Raymond Hettingerfed52962004-07-14 15:41:57 +00003596 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003597 """Creates a new Decimal instance but using self as context."""
3598 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003599 if d._isnan() and len(d._int) > self.prec - self._clamp:
3600 return self._raise_error(ConversionSyntax,
3601 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003602 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003603
Guido van Rossumd8faa362007-04-27 19:54:29 +00003604 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003605 def abs(self, a):
3606 """Returns the absolute value of the operand.
3607
3608 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003609 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003610 the plus operation on the operand.
3611
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003612 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003613 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003614 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003615 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003616 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003617 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003618 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003619 Decimal("101.5")
3620 """
3621 return a.__abs__(context=self)
3622
3623 def add(self, a, b):
3624 """Return the sum of the two operands.
3625
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003626 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003627 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003628 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003629 Decimal("1.02E+4")
3630 """
3631 return a.__add__(b, context=self)
3632
3633 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003634 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003635
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003636 def canonical(self, a):
3637 """Returns the same Decimal object.
3638
3639 As we do not have different encodings for the same number, the
3640 received object already is in its canonical form.
3641
3642 >>> ExtendedContext.canonical(Decimal('2.50'))
3643 Decimal("2.50")
3644 """
3645 return a.canonical(context=self)
3646
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003647 def compare(self, a, b):
3648 """Compares values numerically.
3649
3650 If the signs of the operands differ, a value representing each operand
3651 ('-1' if the operand is less than zero, '0' if the operand is zero or
3652 negative zero, or '1' if the operand is greater than zero) is used in
3653 place of that operand for the comparison instead of the actual
3654 operand.
3655
3656 The comparison is then effected by subtracting the second operand from
3657 the first and then returning a value according to the result of the
3658 subtraction: '-1' if the result is less than zero, '0' if the result is
3659 zero or negative zero, or '1' if the result is greater than zero.
3660
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003661 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003662 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003663 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003664 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003665 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003666 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003667 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003668 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003669 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003670 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003671 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003672 Decimal("-1")
3673 """
3674 return a.compare(b, context=self)
3675
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003676 def compare_signal(self, a, b):
3677 """Compares the values of the two operands numerically.
3678
3679 It's pretty much like compare(), but all NaNs signal, with signaling
3680 NaNs taking precedence over quiet NaNs.
3681
3682 >>> c = ExtendedContext
3683 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3684 Decimal("-1")
3685 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3686 Decimal("0")
3687 >>> c.flags[InvalidOperation] = 0
3688 >>> print(c.flags[InvalidOperation])
3689 0
3690 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3691 Decimal("NaN")
3692 >>> print(c.flags[InvalidOperation])
3693 1
3694 >>> c.flags[InvalidOperation] = 0
3695 >>> print(c.flags[InvalidOperation])
3696 0
3697 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3698 Decimal("NaN")
3699 >>> print(c.flags[InvalidOperation])
3700 1
3701 """
3702 return a.compare_signal(b, context=self)
3703
3704 def compare_total(self, a, b):
3705 """Compares two operands using their abstract representation.
3706
3707 This is not like the standard compare, which use their numerical
3708 value. Note that a total ordering is defined for all possible abstract
3709 representations.
3710
3711 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3712 Decimal("-1")
3713 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3714 Decimal("-1")
3715 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3716 Decimal("-1")
3717 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3718 Decimal("0")
3719 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3720 Decimal("1")
3721 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3722 Decimal("-1")
3723 """
3724 return a.compare_total(b)
3725
3726 def compare_total_mag(self, a, b):
3727 """Compares two operands using their abstract representation ignoring sign.
3728
3729 Like compare_total, but with operand's sign ignored and assumed to be 0.
3730 """
3731 return a.compare_total_mag(b)
3732
3733 def copy_abs(self, a):
3734 """Returns a copy of the operand with the sign set to 0.
3735
3736 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3737 Decimal("2.1")
3738 >>> ExtendedContext.copy_abs(Decimal('-100'))
3739 Decimal("100")
3740 """
3741 return a.copy_abs()
3742
3743 def copy_decimal(self, a):
3744 """Returns a copy of the decimal objet.
3745
3746 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3747 Decimal("2.1")
3748 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3749 Decimal("-1.00")
3750 """
3751 return Decimal(a)
3752
3753 def copy_negate(self, a):
3754 """Returns a copy of the operand with the sign inverted.
3755
3756 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3757 Decimal("-101.5")
3758 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3759 Decimal("101.5")
3760 """
3761 return a.copy_negate()
3762
3763 def copy_sign(self, a, b):
3764 """Copies the second operand's sign to the first one.
3765
3766 In detail, it returns a copy of the first operand with the sign
3767 equal to the sign of the second operand.
3768
3769 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3770 Decimal("1.50")
3771 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3772 Decimal("1.50")
3773 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3774 Decimal("-1.50")
3775 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3776 Decimal("-1.50")
3777 """
3778 return a.copy_sign(b)
3779
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003780 def divide(self, a, b):
3781 """Decimal division in a specified context.
3782
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003783 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003784 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003785 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003786 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003787 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003788 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003789 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003790 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003791 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003792 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003793 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003794 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003795 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003796 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003797 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003798 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003799 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003800 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003801 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003802 Decimal("1.20E+6")
3803 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003804 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003805
3806 def divide_int(self, a, b):
3807 """Divides two numbers and returns the integer part of the result.
3808
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003809 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003810 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003811 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003812 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003813 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003814 Decimal("3")
3815 """
3816 return a.__floordiv__(b, context=self)
3817
3818 def divmod(self, a, b):
3819 return a.__divmod__(b, context=self)
3820
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003821 def exp(self, a):
3822 """Returns e ** a.
3823
3824 >>> c = ExtendedContext.copy()
3825 >>> c.Emin = -999
3826 >>> c.Emax = 999
3827 >>> c.exp(Decimal('-Infinity'))
3828 Decimal("0")
3829 >>> c.exp(Decimal('-1'))
3830 Decimal("0.367879441")
3831 >>> c.exp(Decimal('0'))
3832 Decimal("1")
3833 >>> c.exp(Decimal('1'))
3834 Decimal("2.71828183")
3835 >>> c.exp(Decimal('0.693147181'))
3836 Decimal("2.00000000")
3837 >>> c.exp(Decimal('+Infinity'))
3838 Decimal("Infinity")
3839 """
3840 return a.exp(context=self)
3841
3842 def fma(self, a, b, c):
3843 """Returns a multiplied by b, plus c.
3844
3845 The first two operands are multiplied together, using multiply,
3846 the third operand is then added to the result of that
3847 multiplication, using add, all with only one final rounding.
3848
3849 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3850 Decimal("22")
3851 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3852 Decimal("-8")
3853 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3854 Decimal("1.38435736E+12")
3855 """
3856 return a.fma(b, c, context=self)
3857
3858 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003859 """Return True if the operand is canonical; otherwise return False.
3860
3861 Currently, the encoding of a Decimal instance is always
3862 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003863
3864 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003865 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003866 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003867 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003868
3869 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003870 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003871
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003872 A Decimal instance is considered finite if it is neither
3873 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003874
3875 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003876 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003877 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003878 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003879 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003880 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003881 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003882 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003883 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003884 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003885 """
3886 return a.is_finite()
3887
3888 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003889 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003890
3891 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003892 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003893 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003894 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003895 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003896 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003897 """
3898 return a.is_infinite()
3899
3900 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003901 """Return True if the operand is a qNaN or sNaN;
3902 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003903
3904 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003905 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003906 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003907 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003908 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003909 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003910 """
3911 return a.is_nan()
3912
3913 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003914 """Return True if the operand is a normal number;
3915 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003916
3917 >>> c = ExtendedContext.copy()
3918 >>> c.Emin = -999
3919 >>> c.Emax = 999
3920 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003921 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003922 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003923 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003924 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003925 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003926 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003927 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003928 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003929 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003930 """
3931 return a.is_normal(context=self)
3932
3933 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003934 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003935
3936 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003937 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003938 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003939 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003940 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003941 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003942 """
3943 return a.is_qnan()
3944
3945 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003946 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003947
3948 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003949 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003950 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003951 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003952 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003953 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003954 """
3955 return a.is_signed()
3956
3957 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003958 """Return True if the operand is a signaling NaN;
3959 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003960
3961 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003962 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003963 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003964 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003965 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003966 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003967 """
3968 return a.is_snan()
3969
3970 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003971 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003972
3973 >>> c = ExtendedContext.copy()
3974 >>> c.Emin = -999
3975 >>> c.Emax = 999
3976 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003977 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003978 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003979 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003980 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003981 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003982 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003983 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003984 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003985 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003986 """
3987 return a.is_subnormal(context=self)
3988
3989 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003990 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003991
3992 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003993 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003994 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003995 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003996 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003997 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003998 """
3999 return a.is_zero()
4000
4001 def ln(self, a):
4002 """Returns the natural (base e) logarithm of the operand.
4003
4004 >>> c = ExtendedContext.copy()
4005 >>> c.Emin = -999
4006 >>> c.Emax = 999
4007 >>> c.ln(Decimal('0'))
4008 Decimal("-Infinity")
4009 >>> c.ln(Decimal('1.000'))
4010 Decimal("0")
4011 >>> c.ln(Decimal('2.71828183'))
4012 Decimal("1.00000000")
4013 >>> c.ln(Decimal('10'))
4014 Decimal("2.30258509")
4015 >>> c.ln(Decimal('+Infinity'))
4016 Decimal("Infinity")
4017 """
4018 return a.ln(context=self)
4019
4020 def log10(self, a):
4021 """Returns the base 10 logarithm of the operand.
4022
4023 >>> c = ExtendedContext.copy()
4024 >>> c.Emin = -999
4025 >>> c.Emax = 999
4026 >>> c.log10(Decimal('0'))
4027 Decimal("-Infinity")
4028 >>> c.log10(Decimal('0.001'))
4029 Decimal("-3")
4030 >>> c.log10(Decimal('1.000'))
4031 Decimal("0")
4032 >>> c.log10(Decimal('2'))
4033 Decimal("0.301029996")
4034 >>> c.log10(Decimal('10'))
4035 Decimal("1")
4036 >>> c.log10(Decimal('70'))
4037 Decimal("1.84509804")
4038 >>> c.log10(Decimal('+Infinity'))
4039 Decimal("Infinity")
4040 """
4041 return a.log10(context=self)
4042
4043 def logb(self, a):
4044 """ Returns the exponent of the magnitude of the operand's MSD.
4045
4046 The result is the integer which is the exponent of the magnitude
4047 of the most significant digit of the operand (as though the
4048 operand were truncated to a single digit while maintaining the
4049 value of that digit and without limiting the resulting exponent).
4050
4051 >>> ExtendedContext.logb(Decimal('250'))
4052 Decimal("2")
4053 >>> ExtendedContext.logb(Decimal('2.50'))
4054 Decimal("0")
4055 >>> ExtendedContext.logb(Decimal('0.03'))
4056 Decimal("-2")
4057 >>> ExtendedContext.logb(Decimal('0'))
4058 Decimal("-Infinity")
4059 """
4060 return a.logb(context=self)
4061
4062 def logical_and(self, a, b):
4063 """Applies the logical operation 'and' between each operand's digits.
4064
4065 The operands must be both logical numbers.
4066
4067 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4068 Decimal("0")
4069 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4070 Decimal("0")
4071 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4072 Decimal("0")
4073 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4074 Decimal("1")
4075 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4076 Decimal("1000")
4077 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4078 Decimal("10")
4079 """
4080 return a.logical_and(b, context=self)
4081
4082 def logical_invert(self, a):
4083 """Invert all the digits in the operand.
4084
4085 The operand must be a logical number.
4086
4087 >>> ExtendedContext.logical_invert(Decimal('0'))
4088 Decimal("111111111")
4089 >>> ExtendedContext.logical_invert(Decimal('1'))
4090 Decimal("111111110")
4091 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4092 Decimal("0")
4093 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4094 Decimal("10101010")
4095 """
4096 return a.logical_invert(context=self)
4097
4098 def logical_or(self, a, b):
4099 """Applies the logical operation 'or' between each operand's digits.
4100
4101 The operands must be both logical numbers.
4102
4103 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4104 Decimal("0")
4105 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4106 Decimal("1")
4107 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4108 Decimal("1")
4109 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4110 Decimal("1")
4111 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4112 Decimal("1110")
4113 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4114 Decimal("1110")
4115 """
4116 return a.logical_or(b, context=self)
4117
4118 def logical_xor(self, a, b):
4119 """Applies the logical operation 'xor' between each operand's digits.
4120
4121 The operands must be both logical numbers.
4122
4123 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4124 Decimal("0")
4125 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4126 Decimal("1")
4127 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4128 Decimal("1")
4129 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4130 Decimal("0")
4131 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4132 Decimal("110")
4133 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4134 Decimal("1101")
4135 """
4136 return a.logical_xor(b, context=self)
4137
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004138 def max(self, a,b):
4139 """max compares two values numerically and returns the maximum.
4140
4141 If either operand is a NaN then the general rules apply.
4142 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004143 operation. If they are numerically equal then the left-hand operand
4144 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004145 infinity) of the two operands is chosen as the result.
4146
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004147 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004148 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004149 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004150 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004151 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004152 Decimal("1")
4153 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4154 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004155 """
4156 return a.max(b, context=self)
4157
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004158 def max_mag(self, a, b):
4159 """Compares the values numerically with their sign ignored."""
4160 return a.max_mag(b, context=self)
4161
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004162 def min(self, a,b):
4163 """min compares two values numerically and returns the minimum.
4164
4165 If either operand is a NaN then the general rules apply.
4166 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004167 operation. If they are numerically equal then the left-hand operand
4168 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004169 infinity) of the two operands is chosen as the result.
4170
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004171 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004172 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004173 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004174 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004175 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004176 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004177 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4178 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004179 """
4180 return a.min(b, context=self)
4181
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004182 def min_mag(self, a, b):
4183 """Compares the values numerically with their sign ignored."""
4184 return a.min_mag(b, context=self)
4185
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004186 def minus(self, a):
4187 """Minus corresponds to unary prefix minus in Python.
4188
4189 The operation is evaluated using the same rules as subtract; the
4190 operation minus(a) is calculated as subtract('0', a) where the '0'
4191 has the same exponent as the operand.
4192
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004193 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004194 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004195 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004196 Decimal("1.3")
4197 """
4198 return a.__neg__(context=self)
4199
4200 def multiply(self, a, b):
4201 """multiply multiplies two operands.
4202
4203 If either operand is a special value then the general rules apply.
4204 Otherwise, the operands are multiplied together ('long multiplication'),
4205 resulting in a number which may be as long as the sum of the lengths
4206 of the two operands.
4207
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004208 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004209 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004210 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004211 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004212 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004213 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004214 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004215 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004216 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004217 Decimal("4.28135971E+11")
4218 """
4219 return a.__mul__(b, context=self)
4220
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004221 def next_minus(self, a):
4222 """Returns the largest representable number smaller than a.
4223
4224 >>> c = ExtendedContext.copy()
4225 >>> c.Emin = -999
4226 >>> c.Emax = 999
4227 >>> ExtendedContext.next_minus(Decimal('1'))
4228 Decimal("0.999999999")
4229 >>> c.next_minus(Decimal('1E-1007'))
4230 Decimal("0E-1007")
4231 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4232 Decimal("-1.00000004")
4233 >>> c.next_minus(Decimal('Infinity'))
4234 Decimal("9.99999999E+999")
4235 """
4236 return a.next_minus(context=self)
4237
4238 def next_plus(self, a):
4239 """Returns the smallest representable number larger than a.
4240
4241 >>> c = ExtendedContext.copy()
4242 >>> c.Emin = -999
4243 >>> c.Emax = 999
4244 >>> ExtendedContext.next_plus(Decimal('1'))
4245 Decimal("1.00000001")
4246 >>> c.next_plus(Decimal('-1E-1007'))
4247 Decimal("-0E-1007")
4248 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4249 Decimal("-1.00000002")
4250 >>> c.next_plus(Decimal('-Infinity'))
4251 Decimal("-9.99999999E+999")
4252 """
4253 return a.next_plus(context=self)
4254
4255 def next_toward(self, a, b):
4256 """Returns the number closest to a, in direction towards b.
4257
4258 The result is the closest representable number from the first
4259 operand (but not the first operand) that is in the direction
4260 towards the second operand, unless the operands have the same
4261 value.
4262
4263 >>> c = ExtendedContext.copy()
4264 >>> c.Emin = -999
4265 >>> c.Emax = 999
4266 >>> c.next_toward(Decimal('1'), Decimal('2'))
4267 Decimal("1.00000001")
4268 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4269 Decimal("-0E-1007")
4270 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4271 Decimal("-1.00000002")
4272 >>> c.next_toward(Decimal('1'), Decimal('0'))
4273 Decimal("0.999999999")
4274 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4275 Decimal("0E-1007")
4276 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4277 Decimal("-1.00000004")
4278 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4279 Decimal("-0.00")
4280 """
4281 return a.next_toward(b, context=self)
4282
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004283 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004284 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004285
4286 Essentially a plus operation with all trailing zeros removed from the
4287 result.
4288
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004289 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004290 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004291 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004292 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004293 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004294 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004295 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004296 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004297 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004298 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004299 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004300 Decimal("0")
4301 """
4302 return a.normalize(context=self)
4303
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004304 def number_class(self, a):
4305 """Returns an indication of the class of the operand.
4306
4307 The class is one of the following strings:
4308 -sNaN
4309 -NaN
4310 -Infinity
4311 -Normal
4312 -Subnormal
4313 -Zero
4314 +Zero
4315 +Subnormal
4316 +Normal
4317 +Infinity
4318
4319 >>> c = Context(ExtendedContext)
4320 >>> c.Emin = -999
4321 >>> c.Emax = 999
4322 >>> c.number_class(Decimal('Infinity'))
4323 '+Infinity'
4324 >>> c.number_class(Decimal('1E-10'))
4325 '+Normal'
4326 >>> c.number_class(Decimal('2.50'))
4327 '+Normal'
4328 >>> c.number_class(Decimal('0.1E-999'))
4329 '+Subnormal'
4330 >>> c.number_class(Decimal('0'))
4331 '+Zero'
4332 >>> c.number_class(Decimal('-0'))
4333 '-Zero'
4334 >>> c.number_class(Decimal('-0.1E-999'))
4335 '-Subnormal'
4336 >>> c.number_class(Decimal('-1E-10'))
4337 '-Normal'
4338 >>> c.number_class(Decimal('-2.50'))
4339 '-Normal'
4340 >>> c.number_class(Decimal('-Infinity'))
4341 '-Infinity'
4342 >>> c.number_class(Decimal('NaN'))
4343 'NaN'
4344 >>> c.number_class(Decimal('-NaN'))
4345 'NaN'
4346 >>> c.number_class(Decimal('sNaN'))
4347 'sNaN'
4348 """
4349 return a.number_class(context=self)
4350
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004351 def plus(self, a):
4352 """Plus corresponds to unary prefix plus in Python.
4353
4354 The operation is evaluated using the same rules as add; the
4355 operation plus(a) is calculated as add('0', a) where the '0'
4356 has the same exponent as the operand.
4357
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004358 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004359 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004360 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004361 Decimal("-1.3")
4362 """
4363 return a.__pos__(context=self)
4364
4365 def power(self, a, b, modulo=None):
4366 """Raises a to the power of b, to modulo if given.
4367
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004368 With two arguments, compute a**b. If a is negative then b
4369 must be integral. The result will be inexact unless b is
4370 integral and the result is finite and can be expressed exactly
4371 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004372
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004373 With three arguments, compute (a**b) % modulo. For the
4374 three argument form, the following restrictions on the
4375 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004376
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004377 - all three arguments must be integral
4378 - b must be nonnegative
4379 - at least one of a or b must be nonzero
4380 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004381
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004382 The result of pow(a, b, modulo) is identical to the result
4383 that would be obtained by computing (a**b) % modulo with
4384 unbounded precision, but is computed more efficiently. It is
4385 always exact.
4386
4387 >>> c = ExtendedContext.copy()
4388 >>> c.Emin = -999
4389 >>> c.Emax = 999
4390 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004391 Decimal("8")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004392 >>> c.power(Decimal('-2'), Decimal('3'))
4393 Decimal("-8")
4394 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004395 Decimal("0.125")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004396 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004397 Decimal("69.7575744")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004398 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4399 Decimal("2.00000000")
4400 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004401 Decimal("0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004402 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004403 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004404 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004405 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004406 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004407 Decimal("-0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004408 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004409 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004410 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004411 Decimal("-Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004412 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004413 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004414 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004415 Decimal("NaN")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004416
4417 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4418 Decimal("11")
4419 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4420 Decimal("-11")
4421 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4422 Decimal("1")
4423 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4424 Decimal("11")
4425 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4426 Decimal("11729830")
4427 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4428 Decimal("-0")
4429 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4430 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004431 """
4432 return a.__pow__(b, modulo, context=self)
4433
4434 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004435 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004436
4437 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004438 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004439 exponent is being increased), multiplied by a positive power of ten (if
4440 the exponent is being decreased), or is unchanged (if the exponent is
4441 already equal to that of the right-hand operand).
4442
4443 Unlike other operations, if the length of the coefficient after the
4444 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004445 operation condition is raised. This guarantees that, unless there is
4446 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004447 equal to that of the right-hand operand.
4448
4449 Also unlike other operations, quantize will never raise Underflow, even
4450 if the result is subnormal and inexact.
4451
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004452 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004453 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004454 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004455 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004456 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004457 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004458 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004459 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004460 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004461 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004462 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004463 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004464 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004465 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004466 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004467 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004468 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004469 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004470 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004471 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004472 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004473 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004474 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004475 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004476 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004477 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004478 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004479 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004480 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004481 Decimal("2E+2")
4482 """
4483 return a.quantize(b, context=self)
4484
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004485 def radix(self):
4486 """Just returns 10, as this is Decimal, :)
4487
4488 >>> ExtendedContext.radix()
4489 Decimal("10")
4490 """
4491 return Decimal(10)
4492
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004493 def remainder(self, a, b):
4494 """Returns the remainder from integer division.
4495
4496 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004497 calculating integer division as described for divide-integer, rounded
4498 to precision digits if necessary. The sign of the result, if
4499 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004500
4501 This operation will fail under the same conditions as integer division
4502 (that is, if integer division on the same two operands would fail, the
4503 remainder cannot be calculated).
4504
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004505 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004506 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004507 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004508 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004509 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004510 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004511 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004512 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004513 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004514 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004515 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004516 Decimal("1.0")
4517 """
4518 return a.__mod__(b, context=self)
4519
4520 def remainder_near(self, a, b):
4521 """Returns to be "a - b * n", where n is the integer nearest the exact
4522 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004523 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004524 sign of a.
4525
4526 This operation will fail under the same conditions as integer division
4527 (that is, if integer division on the same two operands would fail, the
4528 remainder cannot be calculated).
4529
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004530 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004531 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004532 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004533 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004534 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004535 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004536 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004537 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004538 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004539 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004540 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004541 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004542 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004543 Decimal("-0.3")
4544 """
4545 return a.remainder_near(b, context=self)
4546
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004547 def rotate(self, a, b):
4548 """Returns a rotated copy of a, b times.
4549
4550 The coefficient of the result is a rotated copy of the digits in
4551 the coefficient of the first operand. The number of places of
4552 rotation is taken from the absolute value of the second operand,
4553 with the rotation being to the left if the second operand is
4554 positive or to the right otherwise.
4555
4556 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4557 Decimal("400000003")
4558 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4559 Decimal("12")
4560 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4561 Decimal("891234567")
4562 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4563 Decimal("123456789")
4564 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4565 Decimal("345678912")
4566 """
4567 return a.rotate(b, context=self)
4568
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004569 def same_quantum(self, a, b):
4570 """Returns True if the two operands have the same exponent.
4571
4572 The result is never affected by either the sign or the coefficient of
4573 either operand.
4574
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004575 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004576 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004577 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004578 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004579 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004580 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004581 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004582 True
4583 """
4584 return a.same_quantum(b)
4585
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004586 def scaleb (self, a, b):
4587 """Returns the first operand after adding the second value its exp.
4588
4589 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4590 Decimal("0.0750")
4591 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4592 Decimal("7.50")
4593 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4594 Decimal("7.50E+3")
4595 """
4596 return a.scaleb (b, context=self)
4597
4598 def shift(self, a, b):
4599 """Returns a shifted copy of a, b times.
4600
4601 The coefficient of the result is a shifted copy of the digits
4602 in the coefficient of the first operand. The number of places
4603 to shift is taken from the absolute value of the second operand,
4604 with the shift being to the left if the second operand is
4605 positive or to the right otherwise. Digits shifted into the
4606 coefficient are zeros.
4607
4608 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4609 Decimal("400000000")
4610 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4611 Decimal("0")
4612 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4613 Decimal("1234567")
4614 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4615 Decimal("123456789")
4616 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4617 Decimal("345678900")
4618 """
4619 return a.shift(b, context=self)
4620
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004621 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004622 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004623
4624 If the result must be inexact, it is rounded using the round-half-even
4625 algorithm.
4626
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004627 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004628 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004629 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004630 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004631 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004632 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004633 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004634 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004635 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004636 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004637 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004638 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004639 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004640 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004641 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004642 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004643 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004644 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004645 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004646 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004647 """
4648 return a.sqrt(context=self)
4649
4650 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004651 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004652
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004653 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004654 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004655 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004656 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004657 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004658 Decimal("-0.77")
4659 """
4660 return a.__sub__(b, context=self)
4661
4662 def to_eng_string(self, a):
4663 """Converts a number to a string, using scientific notation.
4664
4665 The operation is not affected by the context.
4666 """
4667 return a.to_eng_string(context=self)
4668
4669 def to_sci_string(self, a):
4670 """Converts a number to a string, using scientific notation.
4671
4672 The operation is not affected by the context.
4673 """
4674 return a.__str__(context=self)
4675
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004676 def to_integral_exact(self, a):
4677 """Rounds to an integer.
4678
4679 When the operand has a negative exponent, the result is the same
4680 as using the quantize() operation using the given operand as the
4681 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4682 of the operand as the precision setting; Inexact and Rounded flags
4683 are allowed in this operation. The rounding mode is taken from the
4684 context.
4685
4686 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4687 Decimal("2")
4688 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4689 Decimal("100")
4690 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4691 Decimal("100")
4692 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4693 Decimal("102")
4694 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4695 Decimal("-102")
4696 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4697 Decimal("1.0E+6")
4698 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4699 Decimal("7.89E+77")
4700 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4701 Decimal("-Infinity")
4702 """
4703 return a.to_integral_exact(context=self)
4704
4705 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004706 """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, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004712 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004713
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004714 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004715 Decimal("2")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004716 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004717 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004718 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004719 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004720 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004721 Decimal("102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004722 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004723 Decimal("-102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004724 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004725 Decimal("1.0E+6")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004726 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004727 Decimal("7.89E+77")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004728 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004729 Decimal("-Infinity")
4730 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004731 return a.to_integral_value(context=self)
4732
4733 # the method name changed, but we provide also the old one, for compatibility
4734 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004735
4736class _WorkRep(object):
4737 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004738 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004739 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004740 # exp: None, int, or string
4741
4742 def __init__(self, value=None):
4743 if value is None:
4744 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004745 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004746 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004747 elif isinstance(value, Decimal):
4748 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00004749 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004750 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004751 else:
4752 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004753 self.sign = value[0]
4754 self.int = value[1]
4755 self.exp = value[2]
4756
4757 def __repr__(self):
4758 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4759
4760 __str__ = __repr__
4761
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004762
4763
4764def _normalize(op1, op2, shouldround = 0, prec = 0):
4765 """Normalizes op1, op2 to have the same exp and length of coefficient.
4766
4767 Done during addition.
4768 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004769 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004770 tmp = op2
4771 other = op1
4772 else:
4773 tmp = op1
4774 other = op2
4775
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004776 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4777 # Then adding 10**exp to tmp has the same effect (after rounding)
4778 # as adding any positive quantity smaller than 10**exp; similarly
4779 # for subtraction. So if other is smaller than 10**exp we replace
4780 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4781 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004782 tmp_len = len(str(tmp.int))
4783 other_len = len(str(other.int))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004784 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4785 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004786 other.int = 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004787 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004788
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004789 tmp.int *= 10 ** (tmp.exp - other.exp)
4790 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004791 return op1, op2
4792
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004793##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004794
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004795# This function from Tim Peters was taken from here:
4796# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4797# The correction being in the function definition is for speed, and
4798# the whole function is not resolved with math.log because of avoiding
4799# the use of floats.
4800def _nbits(n, correction = {
4801 '0': 4, '1': 3, '2': 2, '3': 2,
4802 '4': 1, '5': 1, '6': 1, '7': 1,
4803 '8': 0, '9': 0, 'a': 0, 'b': 0,
4804 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4805 """Number of bits in binary representation of the positive integer n,
4806 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004807 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004808 if n < 0:
4809 raise ValueError("The argument to _nbits should be nonnegative.")
4810 hex_n = "%x" % n
4811 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004812
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004813def _sqrt_nearest(n, a):
4814 """Closest integer to the square root of the positive integer n. a is
4815 an initial approximation to the square root. Any positive integer
4816 will do for a, but the closer a is to the square root of n the
4817 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004818
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004819 """
4820 if n <= 0 or a <= 0:
4821 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4822
4823 b=0
4824 while a != b:
4825 b, a = a, a--n//a>>1
4826 return a
4827
4828def _rshift_nearest(x, shift):
4829 """Given an integer x and a nonnegative integer shift, return closest
4830 integer to x / 2**shift; use round-to-even in case of a tie.
4831
4832 """
4833 b, q = 1 << shift, x >> shift
4834 return q + (2*(x & (b-1)) + (q&1) > b)
4835
4836def _div_nearest(a, b):
4837 """Closest integer to a/b, a and b positive integers; rounds to even
4838 in the case of a tie.
4839
4840 """
4841 q, r = divmod(a, b)
4842 return q + (2*r + (q&1) > b)
4843
4844def _ilog(x, M, L = 8):
4845 """Integer approximation to M*log(x/M), with absolute error boundable
4846 in terms only of x/M.
4847
4848 Given positive integers x and M, return an integer approximation to
4849 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4850 between the approximation and the exact result is at most 22. For
4851 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4852 both cases these are upper bounds on the error; it will usually be
4853 much smaller."""
4854
4855 # The basic algorithm is the following: let log1p be the function
4856 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4857 # the reduction
4858 #
4859 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4860 #
4861 # repeatedly until the argument to log1p is small (< 2**-L in
4862 # absolute value). For small y we can use the Taylor series
4863 # expansion
4864 #
4865 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4866 #
4867 # truncating at T such that y**T is small enough. The whole
4868 # computation is carried out in a form of fixed-point arithmetic,
4869 # with a real number z being represented by an integer
4870 # approximation to z*M. To avoid loss of precision, the y below
4871 # is actually an integer approximation to 2**R*y*M, where R is the
4872 # number of reductions performed so far.
4873
4874 y = x-M
4875 # argument reduction; R = number of reductions performed
4876 R = 0
4877 while (R <= L and abs(y) << L-R >= M or
4878 R > L and abs(y) >> R-L >= M):
4879 y = _div_nearest((M*y) << 1,
4880 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4881 R += 1
4882
4883 # Taylor series with T terms
4884 T = -int(-10*len(str(M))//(3*L))
4885 yshift = _rshift_nearest(y, R)
4886 w = _div_nearest(M, T)
4887 for k in range(T-1, 0, -1):
4888 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4889
4890 return _div_nearest(w*y, M)
4891
4892def _dlog10(c, e, p):
4893 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4894 approximation to 10**p * log10(c*10**e), with an absolute error of
4895 at most 1. Assumes that c*10**e is not exactly 1."""
4896
4897 # increase precision by 2; compensate for this by dividing
4898 # final result by 100
4899 p += 2
4900
4901 # write c*10**e as d*10**f with either:
4902 # f >= 0 and 1 <= d <= 10, or
4903 # f <= 0 and 0.1 <= d <= 1.
4904 # Thus for c*10**e close to 1, f = 0
4905 l = len(str(c))
4906 f = e+l - (e+l >= 1)
4907
4908 if p > 0:
4909 M = 10**p
4910 k = e+p-f
4911 if k >= 0:
4912 c *= 10**k
4913 else:
4914 c = _div_nearest(c, 10**-k)
4915
4916 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004917 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004918 log_d = _div_nearest(log_d*M, log_10)
4919 log_tenpower = f*M # exact
4920 else:
4921 log_d = 0 # error < 2.31
4922 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4923
4924 return _div_nearest(log_tenpower+log_d, 100)
4925
4926def _dlog(c, e, p):
4927 """Given integers c, e and p with c > 0, compute an integer
4928 approximation to 10**p * log(c*10**e), with an absolute error of
4929 at most 1. Assumes that c*10**e is not exactly 1."""
4930
4931 # Increase precision by 2. The precision increase is compensated
4932 # for at the end with a division by 100.
4933 p += 2
4934
4935 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4936 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4937 # as 10**p * log(d) + 10**p*f * log(10).
4938 l = len(str(c))
4939 f = e+l - (e+l >= 1)
4940
4941 # compute approximation to 10**p*log(d), with error < 27
4942 if p > 0:
4943 k = e+p-f
4944 if k >= 0:
4945 c *= 10**k
4946 else:
4947 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4948
4949 # _ilog magnifies existing error in c by a factor of at most 10
4950 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4951 else:
4952 # p <= 0: just approximate the whole thing by 0; error < 2.31
4953 log_d = 0
4954
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004955 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004956 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004957 extra = len(str(abs(f)))-1
4958 if p + extra >= 0:
4959 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4960 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4961 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004962 else:
4963 f_log_ten = 0
4964 else:
4965 f_log_ten = 0
4966
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004967 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004968 return _div_nearest(f_log_ten + log_d, 100)
4969
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004970class _Log10Memoize(object):
4971 """Class to compute, store, and allow retrieval of, digits of the
4972 constant log(10) = 2.302585.... This constant is needed by
4973 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4974 def __init__(self):
4975 self.digits = "23025850929940456840179914546843642076011014886"
4976
4977 def getdigits(self, p):
4978 """Given an integer p >= 0, return floor(10**p)*log(10).
4979
4980 For example, self.getdigits(3) returns 2302.
4981 """
4982 # digits are stored as a string, for quick conversion to
4983 # integer in the case that we've already computed enough
4984 # digits; the stored digits should always be correct
4985 # (truncated, not rounded to nearest).
4986 if p < 0:
4987 raise ValueError("p should be nonnegative")
4988
4989 if p >= len(self.digits):
4990 # compute p+3, p+6, p+9, ... digits; continue until at
4991 # least one of the extra digits is nonzero
4992 extra = 3
4993 while True:
4994 # compute p+extra digits, correct to within 1ulp
4995 M = 10**(p+extra+2)
4996 digits = str(_div_nearest(_ilog(10*M, M), 100))
4997 if digits[-extra:] != '0'*extra:
4998 break
4999 extra += 3
5000 # keep all reliable digits so far; remove trailing zeros
5001 # and next nonzero digit
5002 self.digits = digits.rstrip('0')[:-1]
5003 return int(self.digits[:p+1])
5004
5005_log10_digits = _Log10Memoize().getdigits
5006
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005007def _iexp(x, M, L=8):
5008 """Given integers x and M, M > 0, such that x/M is small in absolute
5009 value, compute an integer approximation to M*exp(x/M). For 0 <=
5010 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5011 is usually much smaller)."""
5012
5013 # Algorithm: to compute exp(z) for a real number z, first divide z
5014 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5015 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5016 # series
5017 #
5018 # expm1(x) = x + x**2/2! + x**3/3! + ...
5019 #
5020 # Now use the identity
5021 #
5022 # expm1(2x) = expm1(x)*(expm1(x)+2)
5023 #
5024 # R times to compute the sequence expm1(z/2**R),
5025 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5026
5027 # Find R such that x/2**R/M <= 2**-L
5028 R = _nbits((x<<L)//M)
5029
5030 # Taylor series. (2**L)**T > M
5031 T = -int(-10*len(str(M))//(3*L))
5032 y = _div_nearest(x, T)
5033 Mshift = M<<R
5034 for i in range(T-1, 0, -1):
5035 y = _div_nearest(x*(Mshift + y), Mshift * i)
5036
5037 # Expansion
5038 for k in range(R-1, -1, -1):
5039 Mshift = M<<(k+2)
5040 y = _div_nearest(y*(y+Mshift), Mshift)
5041
5042 return M+y
5043
5044def _dexp(c, e, p):
5045 """Compute an approximation to exp(c*10**e), with p decimal places of
5046 precision.
5047
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005048 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005049
5050 10**(p-1) <= d <= 10**p, and
5051 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5052
5053 In other words, d*10**f is an approximation to exp(c*10**e) with p
5054 digits of precision, and with an error in d of at most 1. This is
5055 almost, but not quite, the same as the error being < 1ulp: when d
5056 = 10**(p-1) the error could be up to 10 ulp."""
5057
5058 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5059 p += 2
5060
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005061 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005062 extra = max(0, e + len(str(c)) - 1)
5063 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005064
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005065 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005066 # rounding down
5067 shift = e+q
5068 if shift >= 0:
5069 cshift = c*10**shift
5070 else:
5071 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005072 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005073
5074 # reduce remainder back to original precision
5075 rem = _div_nearest(rem, 10**extra)
5076
5077 # error in result of _iexp < 120; error after division < 0.62
5078 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5079
5080def _dpower(xc, xe, yc, ye, p):
5081 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5082 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5083
5084 10**(p-1) <= c <= 10**p, and
5085 (c-1)*10**e < x**y < (c+1)*10**e
5086
5087 in other words, c*10**e is an approximation to x**y with p digits
5088 of precision, and with an error in c of at most 1. (This is
5089 almost, but not quite, the same as the error being < 1ulp: when c
5090 == 10**(p-1) we can only guarantee error < 10ulp.)
5091
5092 We assume that: x is positive and not equal to 1, and y is nonzero.
5093 """
5094
5095 # Find b such that 10**(b-1) <= |y| <= 10**b
5096 b = len(str(abs(yc))) + ye
5097
5098 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5099 lxc = _dlog(xc, xe, p+b+1)
5100
5101 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5102 shift = ye-b
5103 if shift >= 0:
5104 pc = lxc*yc*10**shift
5105 else:
5106 pc = _div_nearest(lxc*yc, 10**-shift)
5107
5108 if pc == 0:
5109 # we prefer a result that isn't exactly 1; this makes it
5110 # easier to compute a correctly rounded result in __pow__
5111 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5112 coeff, exp = 10**(p-1)+1, 1-p
5113 else:
5114 coeff, exp = 10**p-1, -p
5115 else:
5116 coeff, exp = _dexp(pc, -(p+1), p+1)
5117 coeff = _div_nearest(coeff, 10)
5118 exp += 1
5119
5120 return coeff, exp
5121
5122def _log10_lb(c, correction = {
5123 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5124 '6': 23, '7': 16, '8': 10, '9': 5}):
5125 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5126 if c <= 0:
5127 raise ValueError("The argument to _log10_lb should be nonnegative.")
5128 str_c = str(c)
5129 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005130
Guido van Rossumd8faa362007-04-27 19:54:29 +00005131##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005132
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005133def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005134 """Convert other to Decimal.
5135
5136 Verifies that it's ok to use in an implicit construction.
5137 """
5138 if isinstance(other, Decimal):
5139 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005140 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005141 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005142 if raiseit:
5143 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005144 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005145
Guido van Rossumd8faa362007-04-27 19:54:29 +00005146##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005147
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005148# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005149# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005150
5151DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005152 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005153 traps=[DivisionByZero, Overflow, InvalidOperation],
5154 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005155 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005156 Emax=999999999,
5157 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005158 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005159)
5160
5161# Pre-made alternate contexts offered by the specification
5162# Don't change these; the user should be able to select these
5163# contexts and be able to reproduce results from other implementations
5164# of the spec.
5165
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005166BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005167 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005168 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5169 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005170)
5171
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005172ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005173 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005174 traps=[],
5175 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005176)
5177
5178
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005179##### crud for parsing strings #############################################
5180import re
5181
5182# Regular expression used for parsing numeric strings. Additional
5183# comments:
5184#
5185# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5186# whitespace. But note that the specification disallows whitespace in
5187# a numeric string.
5188#
5189# 2. For finite numbers (not infinities and NaNs) the body of the
5190# number between the optional sign and the optional exponent must have
5191# at least one decimal digit, possibly after the decimal point. The
5192# lookahead expression '(?=\d|\.\d)' checks this.
5193#
5194# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5195# other meaning for \d than the numbers [0-9].
5196
5197import re
5198_parser = re.compile(r""" # A numeric string consists of:
5199# \s*
5200 (?P<sign>[-+])? # an optional sign, followed by either...
5201 (
5202 (?=\d|\.\d) # ...a number (with at least one digit)
5203 (?P<int>\d*) # consisting of a (possibly empty) integer part
5204 (\.(?P<frac>\d*))? # followed by an optional fractional part
5205 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5206 |
5207 Inf(inity)? # ...an infinity, or...
5208 |
5209 (?P<signal>s)? # ...an (optionally signaling)
5210 NaN # NaN
5211 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5212 )
5213# \s*
5214 $
5215""", re.VERBOSE | re.IGNORECASE).match
5216
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005217_all_zeros = re.compile('0*$').match
5218_exact_half = re.compile('50*$').match
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005219del re
5220
5221
Guido van Rossumd8faa362007-04-27 19:54:29 +00005222##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005223
Guido van Rossumd8faa362007-04-27 19:54:29 +00005224# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005225Inf = Decimal('Inf')
5226negInf = Decimal('-Inf')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005227NaN = Decimal('NaN')
5228Dec_0 = Decimal(0)
5229Dec_p1 = Decimal(1)
5230Dec_n1 = Decimal(-1)
5231Dec_p2 = Decimal(2)
5232Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005233
Guido van Rossumd8faa362007-04-27 19:54:29 +00005234# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005235Infsign = (Inf, negInf)
5236
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005237
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005238
5239if __name__ == '__main__':
5240 import doctest, sys
5241 doctest.testmod(sys.modules[__name__])