blob: 39ce5828f8ed1de46bc23a291404bafbdeabe19e [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)
1649 third = _convert_other(third, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001650
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001651 if context is None:
1652 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001653
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001654 # do self*other in fresh context with no traps and no rounding
1655 mul_context = Context(traps=[], flags=[],
1656 _rounding_decision=NEVER_ROUND)
1657 product = self.__mul__(other, mul_context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001658
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001659 if mul_context.flags[InvalidOperation]:
1660 # reraise in current context
1661 return context._raise_error(InvalidOperation,
1662 'invalid multiplication in fma',
1663 1, product)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001664
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001665 ans = product.__add__(third, context)
1666 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001667
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001668 def _power_modulo(self, other, modulo, context=None):
1669 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001670
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001671 # if can't convert other and modulo to Decimal, raise
1672 # TypeError; there's no point returning NotImplemented (no
1673 # equivalent of __rpow__ for three argument pow)
1674 other = _convert_other(other, raiseit=True)
1675 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001676
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001677 if context is None:
1678 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001679
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001680 # deal with NaNs: if there are any sNaNs then first one wins,
1681 # (i.e. behaviour for NaNs is identical to that of fma)
1682 self_is_nan = self._isnan()
1683 other_is_nan = other._isnan()
1684 modulo_is_nan = modulo._isnan()
1685 if self_is_nan or other_is_nan or modulo_is_nan:
1686 if self_is_nan == 2:
1687 return context._raise_error(InvalidOperation, 'sNaN',
1688 1, self)
1689 if other_is_nan == 2:
1690 return context._raise_error(InvalidOperation, 'sNaN',
1691 1, other)
1692 if modulo_is_nan == 2:
1693 return context._raise_error(InvalidOperation, 'sNaN',
1694 1, modulo)
1695 if self_is_nan:
1696 return self._fix_nan(context)
1697 if other_is_nan:
1698 return other._fix_nan(context)
1699 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001700
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001701 # check inputs: we apply same restrictions as Python's pow()
1702 if not (self._isinteger() and
1703 other._isinteger() and
1704 modulo._isinteger()):
1705 return context._raise_error(InvalidOperation,
1706 'pow() 3rd argument not allowed '
1707 'unless all arguments are integers')
1708 if other < 0:
1709 return context._raise_error(InvalidOperation,
1710 'pow() 2nd argument cannot be '
1711 'negative when 3rd argument specified')
1712 if not modulo:
1713 return context._raise_error(InvalidOperation,
1714 'pow() 3rd argument cannot be 0')
1715
1716 # additional restriction for decimal: the modulus must be less
1717 # than 10**prec in absolute value
1718 if modulo.adjusted() >= context.prec:
1719 return context._raise_error(InvalidOperation,
1720 'insufficient precision: pow() 3rd '
1721 'argument must not have more than '
1722 'precision digits')
1723
1724 # define 0**0 == NaN, for consistency with two-argument pow
1725 # (even though it hurts!)
1726 if not other and not self:
1727 return context._raise_error(InvalidOperation,
1728 'at least one of pow() 1st argument '
1729 'and 2nd argument must be nonzero ;'
1730 '0**0 is not defined')
1731
1732 # compute sign of result
1733 if other._iseven():
1734 sign = 0
1735 else:
1736 sign = self._sign
1737
1738 # convert modulo to a Python integer, and self and other to
1739 # Decimal integers (i.e. force their exponents to be >= 0)
1740 modulo = abs(int(modulo))
1741 base = _WorkRep(self.to_integral_value())
1742 exponent = _WorkRep(other.to_integral_value())
1743
1744 # compute result using integer pow()
1745 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1746 for i in range(exponent.exp):
1747 base = pow(base, 10, modulo)
1748 base = pow(base, exponent.int, modulo)
1749
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001750 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001751
1752 def _power_exact(self, other, p):
1753 """Attempt to compute self**other exactly.
1754
1755 Given Decimals self and other and an integer p, attempt to
1756 compute an exact result for the power self**other, with p
1757 digits of precision. Return None if self**other is not
1758 exactly representable in p digits.
1759
1760 Assumes that elimination of special cases has already been
1761 performed: self and other must both be nonspecial; self must
1762 be positive and not numerically equal to 1; other must be
1763 nonzero. For efficiency, other._exp should not be too large,
1764 so that 10**abs(other._exp) is a feasible calculation."""
1765
1766 # In the comments below, we write x for the value of self and
1767 # y for the value of other. Write x = xc*10**xe and y =
1768 # yc*10**ye.
1769
1770 # The main purpose of this method is to identify the *failure*
1771 # of x**y to be exactly representable with as little effort as
1772 # possible. So we look for cheap and easy tests that
1773 # eliminate the possibility of x**y being exact. Only if all
1774 # these tests are passed do we go on to actually compute x**y.
1775
1776 # Here's the main idea. First normalize both x and y. We
1777 # express y as a rational m/n, with m and n relatively prime
1778 # and n>0. Then for x**y to be exactly representable (at
1779 # *any* precision), xc must be the nth power of a positive
1780 # integer and xe must be divisible by n. If m is negative
1781 # then additionally xc must be a power of either 2 or 5, hence
1782 # a power of 2**n or 5**n.
1783 #
1784 # There's a limit to how small |y| can be: if y=m/n as above
1785 # then:
1786 #
1787 # (1) if xc != 1 then for the result to be representable we
1788 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1789 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1790 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1791 # representable.
1792 #
1793 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1794 # |y| < 1/|xe| then the result is not representable.
1795 #
1796 # Note that since x is not equal to 1, at least one of (1) and
1797 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1798 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1799 #
1800 # There's also a limit to how large y can be, at least if it's
1801 # positive: the normalized result will have coefficient xc**y,
1802 # so if it's representable then xc**y < 10**p, and y <
1803 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1804 # not exactly representable.
1805
1806 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1807 # so |y| < 1/xe and the result is not representable.
1808 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1809 # < 1/nbits(xc).
1810
1811 x = _WorkRep(self)
1812 xc, xe = x.int, x.exp
1813 while xc % 10 == 0:
1814 xc //= 10
1815 xe += 1
1816
1817 y = _WorkRep(other)
1818 yc, ye = y.int, y.exp
1819 while yc % 10 == 0:
1820 yc //= 10
1821 ye += 1
1822
1823 # case where xc == 1: result is 10**(xe*y), with xe*y
1824 # required to be an integer
1825 if xc == 1:
1826 if ye >= 0:
1827 exponent = xe*yc*10**ye
1828 else:
1829 exponent, remainder = divmod(xe*yc, 10**-ye)
1830 if remainder:
1831 return None
1832 if y.sign == 1:
1833 exponent = -exponent
1834 # if other is a nonnegative integer, use ideal exponent
1835 if other._isinteger() and other._sign == 0:
1836 ideal_exponent = self._exp*int(other)
1837 zeros = min(exponent-ideal_exponent, p-1)
1838 else:
1839 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001840 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001841
1842 # case where y is negative: xc must be either a power
1843 # of 2 or a power of 5.
1844 if y.sign == 1:
1845 last_digit = xc % 10
1846 if last_digit in (2,4,6,8):
1847 # quick test for power of 2
1848 if xc & -xc != xc:
1849 return None
1850 # now xc is a power of 2; e is its exponent
1851 e = _nbits(xc)-1
1852 # find e*y and xe*y; both must be integers
1853 if ye >= 0:
1854 y_as_int = yc*10**ye
1855 e = e*y_as_int
1856 xe = xe*y_as_int
1857 else:
1858 ten_pow = 10**-ye
1859 e, remainder = divmod(e*yc, ten_pow)
1860 if remainder:
1861 return None
1862 xe, remainder = divmod(xe*yc, ten_pow)
1863 if remainder:
1864 return None
1865
1866 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1867 return None
1868 xc = 5**e
1869
1870 elif last_digit == 5:
1871 # e >= log_5(xc) if xc is a power of 5; we have
1872 # equality all the way up to xc=5**2658
1873 e = _nbits(xc)*28//65
1874 xc, remainder = divmod(5**e, xc)
1875 if remainder:
1876 return None
1877 while xc % 5 == 0:
1878 xc //= 5
1879 e -= 1
1880 if ye >= 0:
1881 y_as_integer = yc*10**ye
1882 e = e*y_as_integer
1883 xe = xe*y_as_integer
1884 else:
1885 ten_pow = 10**-ye
1886 e, remainder = divmod(e*yc, ten_pow)
1887 if remainder:
1888 return None
1889 xe, remainder = divmod(xe*yc, ten_pow)
1890 if remainder:
1891 return None
1892 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1893 return None
1894 xc = 2**e
1895 else:
1896 return None
1897
1898 if xc >= 10**p:
1899 return None
1900 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001901 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001902
1903 # now y is positive; find m and n such that y = m/n
1904 if ye >= 0:
1905 m, n = yc*10**ye, 1
1906 else:
1907 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1908 return None
1909 xc_bits = _nbits(xc)
1910 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1911 return None
1912 m, n = yc, 10**(-ye)
1913 while m % 2 == n % 2 == 0:
1914 m //= 2
1915 n //= 2
1916 while m % 5 == n % 5 == 0:
1917 m //= 5
1918 n //= 5
1919
1920 # compute nth root of xc*10**xe
1921 if n > 1:
1922 # if 1 < xc < 2**n then xc isn't an nth power
1923 if xc != 1 and xc_bits <= n:
1924 return None
1925
1926 xe, rem = divmod(xe, n)
1927 if rem != 0:
1928 return None
1929
1930 # compute nth root of xc using Newton's method
1931 a = 1 << -(-_nbits(xc)//n) # initial estimate
1932 while True:
1933 q, r = divmod(xc, a**(n-1))
1934 if a <= q:
1935 break
1936 else:
1937 a = (a*(n-1) + q)//n
1938 if not (a == q and r == 0):
1939 return None
1940 xc = a
1941
1942 # now xc*10**xe is the nth root of the original xc*10**xe
1943 # compute mth power of xc*10**xe
1944
1945 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1946 # 10**p and the result is not representable.
1947 if xc > 1 and m > p*100//_log10_lb(xc):
1948 return None
1949 xc = xc**m
1950 xe *= m
1951 if xc > 10**p:
1952 return None
1953
1954 # by this point the result *is* exactly representable
1955 # adjust the exponent to get as close as possible to the ideal
1956 # exponent, if necessary
1957 str_xc = str(xc)
1958 if other._isinteger() and other._sign == 0:
1959 ideal_exponent = self._exp*int(other)
1960 zeros = min(xe-ideal_exponent, p-len(str_xc))
1961 else:
1962 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001963 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001964
1965 def __pow__(self, other, modulo=None, context=None):
1966 """Return self ** other [ % modulo].
1967
1968 With two arguments, compute self**other.
1969
1970 With three arguments, compute (self**other) % modulo. For the
1971 three argument form, the following restrictions on the
1972 arguments hold:
1973
1974 - all three arguments must be integral
1975 - other must be nonnegative
1976 - either self or other (or both) must be nonzero
1977 - modulo must be nonzero and must have at most p digits,
1978 where p is the context precision.
1979
1980 If any of these restrictions is violated the InvalidOperation
1981 flag is raised.
1982
1983 The result of pow(self, other, modulo) is identical to the
1984 result that would be obtained by computing (self**other) %
1985 modulo with unbounded precision, but is computed more
1986 efficiently. It is always exact.
1987 """
1988
1989 if modulo is not None:
1990 return self._power_modulo(other, modulo, context)
1991
1992 other = _convert_other(other)
1993 if other is NotImplemented:
1994 return other
1995
1996 if context is None:
1997 context = getcontext()
1998
1999 # either argument is a NaN => result is NaN
2000 ans = self._check_nans(other, context)
2001 if ans:
2002 return ans
2003
2004 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2005 if not other:
2006 if not self:
2007 return context._raise_error(InvalidOperation, '0 ** 0')
2008 else:
2009 return Dec_p1
2010
2011 # result has sign 1 iff self._sign is 1 and other is an odd integer
2012 result_sign = 0
2013 if self._sign == 1:
2014 if other._isinteger():
2015 if not other._iseven():
2016 result_sign = 1
2017 else:
2018 # -ve**noninteger = NaN
2019 # (-0)**noninteger = 0**noninteger
2020 if self:
2021 return context._raise_error(InvalidOperation,
2022 'x ** y with x negative and y not an integer')
2023 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002024 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002025
2026 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2027 if not self:
2028 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002029 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002030 else:
2031 return Infsign[result_sign]
2032
2033 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002034 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002035 if other._sign == 0:
2036 return Infsign[result_sign]
2037 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002038 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002039
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002040 # 1**other = 1, but the choice of exponent and the flags
2041 # depend on the exponent of self, and on whether other is a
2042 # positive integer, a negative integer, or neither
2043 if self == Dec_p1:
2044 if other._isinteger():
2045 # exp = max(self._exp*max(int(other), 0),
2046 # 1-context.prec) but evaluating int(other) directly
2047 # is dangerous until we know other is small (other
2048 # could be 1e999999999)
2049 if other._sign == 1:
2050 multiplier = 0
2051 elif other > context.prec:
2052 multiplier = context.prec
2053 else:
2054 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002055
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002056 exp = self._exp * multiplier
2057 if exp < 1-context.prec:
2058 exp = 1-context.prec
2059 context._raise_error(Rounded)
2060 else:
2061 context._raise_error(Inexact)
2062 context._raise_error(Rounded)
2063 exp = 1-context.prec
2064
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002065 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002066
2067 # compute adjusted exponent of self
2068 self_adj = self.adjusted()
2069
2070 # self ** infinity is infinity if self > 1, 0 if self < 1
2071 # self ** -infinity is infinity if self < 1, 0 if self > 1
2072 if other._isinfinity():
2073 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002074 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002075 else:
2076 return Infsign[result_sign]
2077
2078 # from here on, the result always goes through the call
2079 # to _fix at the end of this function.
2080 ans = None
2081
2082 # crude test to catch cases of extreme overflow/underflow. If
2083 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2084 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2085 # self**other >= 10**(Emax+1), so overflow occurs. The test
2086 # for underflow is similar.
2087 bound = self._log10_exp_bound() + other.adjusted()
2088 if (self_adj >= 0) == (other._sign == 0):
2089 # self > 1 and other +ve, or self < 1 and other -ve
2090 # possibility of overflow
2091 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002092 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002093 else:
2094 # self > 1 and other -ve, or self < 1 and other +ve
2095 # possibility of underflow to 0
2096 Etiny = context.Etiny()
2097 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002098 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002099
2100 # try for an exact result with precision +1
2101 if ans is None:
2102 ans = self._power_exact(other, context.prec + 1)
2103 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002104 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002105
2106 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2107 if ans is None:
2108 p = context.prec
2109 x = _WorkRep(self)
2110 xc, xe = x.int, x.exp
2111 y = _WorkRep(other)
2112 yc, ye = y.int, y.exp
2113 if y.sign == 1:
2114 yc = -yc
2115
2116 # compute correctly rounded result: start with precision +3,
2117 # then increase precision until result is unambiguously roundable
2118 extra = 3
2119 while True:
2120 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2121 if coeff % (5*10**(len(str(coeff))-p-1)):
2122 break
2123 extra += 3
2124
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002125 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002126
2127 # the specification says that for non-integer other we need to
2128 # raise Inexact, even when the result is actually exact. In
2129 # the same way, we need to raise Underflow here if the result
2130 # is subnormal. (The call to _fix will take care of raising
2131 # Rounded and Subnormal, as usual.)
2132 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002133 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002134 # pad with zeros up to length context.prec+1 if necessary
2135 if len(ans._int) <= context.prec:
2136 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002137 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2138 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002139 if ans.adjusted() < context.Emin:
2140 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002141
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002142 # unlike exp, ln and log10, the power function respects the
2143 # rounding mode; no need to use ROUND_HALF_EVEN here
2144 ans = ans._fix(context)
2145 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002146
2147 def __rpow__(self, other, context=None):
2148 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002149 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002150 if other is NotImplemented:
2151 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002152 return other.__pow__(self, context=context)
2153
2154 def normalize(self, context=None):
2155 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002156
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002157 if context is None:
2158 context = getcontext()
2159
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002160 if self._is_special:
2161 ans = self._check_nans(context=context)
2162 if ans:
2163 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002164
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002165 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002166 if dup._isinfinity():
2167 return dup
2168
2169 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002170 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002171 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002172 end = len(dup._int)
2173 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002174 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002175 exp += 1
2176 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002177 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002178
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002179 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002180 """Quantize self so its exponent is the same as that of exp.
2181
2182 Similar to self._rescale(exp._exp) but with error checking.
2183 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002184 exp = _convert_other(exp, raiseit=True)
2185
2186 if context is None:
2187 context = getcontext()
2188 if rounding is None:
2189 rounding = context.rounding
2190
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002191 if self._is_special or exp._is_special:
2192 ans = self._check_nans(exp, context)
2193 if ans:
2194 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002195
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002196 if exp._isinfinity() or self._isinfinity():
2197 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002198 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002199 return context._raise_error(InvalidOperation,
2200 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002201
2202 # if we're not watching exponents, do a simple rescale
2203 if not watchexp:
2204 ans = self._rescale(exp._exp, rounding)
2205 # raise Inexact and Rounded where appropriate
2206 if ans._exp > self._exp:
2207 context._raise_error(Rounded)
2208 if ans != self:
2209 context._raise_error(Inexact)
2210 return ans
2211
2212 # exp._exp should be between Etiny and Emax
2213 if not (context.Etiny() <= exp._exp <= context.Emax):
2214 return context._raise_error(InvalidOperation,
2215 'target exponent out of bounds in quantize')
2216
2217 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002218 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002219 return ans._fix(context)
2220
2221 self_adjusted = self.adjusted()
2222 if self_adjusted > context.Emax:
2223 return context._raise_error(InvalidOperation,
2224 'exponent of quantize result too large for current context')
2225 if self_adjusted - exp._exp + 1 > context.prec:
2226 return context._raise_error(InvalidOperation,
2227 'quantize result has too many digits for current context')
2228
2229 ans = self._rescale(exp._exp, rounding)
2230 if ans.adjusted() > context.Emax:
2231 return context._raise_error(InvalidOperation,
2232 'exponent of quantize result too large for current context')
2233 if len(ans._int) > context.prec:
2234 return context._raise_error(InvalidOperation,
2235 'quantize result has too many digits for current context')
2236
2237 # raise appropriate flags
2238 if ans._exp > self._exp:
2239 context._raise_error(Rounded)
2240 if ans != self:
2241 context._raise_error(Inexact)
2242 if ans and ans.adjusted() < context.Emin:
2243 context._raise_error(Subnormal)
2244
2245 # call to fix takes care of any necessary folddown
2246 ans = ans._fix(context)
2247 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002248
2249 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002250 """Return True if self and other have the same exponent; otherwise
2251 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002252
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002253 If either operand is a special value, the following rules are used:
2254 * return True if both operands are infinities
2255 * return True if both operands are NaNs
2256 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002257 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002258 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002259 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002260 return (self.is_nan() and other.is_nan() or
2261 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002262 return self._exp == other._exp
2263
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002264 def _rescale(self, exp, rounding):
2265 """Rescale self so that the exponent is exp, either by padding with zeros
2266 or by truncating digits, using the given rounding mode.
2267
2268 Specials are returned without change. This operation is
2269 quiet: it raises no flags, and uses no information from the
2270 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002271
2272 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002273 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002274 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002275 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002276 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002277 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002278 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002279
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002280 if self._exp >= exp:
2281 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002282 return _dec_from_triple(self._sign,
2283 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002284
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002285 # too many digits; round and lose data. If self.adjusted() <
2286 # exp-1, replace self by 10**(exp-1) before rounding
2287 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002288 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002289 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002290 digits = 0
2291 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002292 changed = this_function(digits)
2293 coeff = self._int[:digits] or '0'
2294 if changed == 1:
2295 coeff = str(int(coeff)+1)
2296 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002297
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002298 def to_integral_exact(self, rounding=None, context=None):
2299 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002300
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002301 If no rounding mode is specified, take the rounding mode from
2302 the context. This method raises the Rounded and Inexact flags
2303 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002304
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002305 See also: to_integral_value, which does exactly the same as
2306 this method except that it doesn't raise Inexact or Rounded.
2307 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002308 if self._is_special:
2309 ans = self._check_nans(context=context)
2310 if ans:
2311 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002312 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002313 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002314 return Decimal(self)
2315 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002316 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002317 if context is None:
2318 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002319 if rounding is None:
2320 rounding = context.rounding
2321 context._raise_error(Rounded)
2322 ans = self._rescale(0, rounding)
2323 if ans != self:
2324 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002325 return ans
2326
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002327 def to_integral_value(self, rounding=None, context=None):
2328 """Rounds to the nearest integer, without raising inexact, rounded."""
2329 if context is None:
2330 context = getcontext()
2331 if rounding is None:
2332 rounding = context.rounding
2333 if self._is_special:
2334 ans = self._check_nans(context=context)
2335 if ans:
2336 return ans
2337 return Decimal(self)
2338 if self._exp >= 0:
2339 return Decimal(self)
2340 else:
2341 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002342
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002343 # the method name changed, but we provide also the old one, for compatibility
2344 to_integral = to_integral_value
2345
2346 def sqrt(self, context=None):
2347 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002348 if self._is_special:
2349 ans = self._check_nans(context=context)
2350 if ans:
2351 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002352
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002353 if self._isinfinity() and self._sign == 0:
2354 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002355
2356 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002357 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002358 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002359 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002360
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002361 if context is None:
2362 context = getcontext()
2363
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002364 if self._sign == 1:
2365 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2366
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002367 # At this point self represents a positive number. Let p be
2368 # the desired precision and express self in the form c*100**e
2369 # with c a positive real number and e an integer, c and e
2370 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2371 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2372 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2373 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2374 # the closest integer to sqrt(c) with the even integer chosen
2375 # in the case of a tie.
2376 #
2377 # To ensure correct rounding in all cases, we use the
2378 # following trick: we compute the square root to an extra
2379 # place (precision p+1 instead of precision p), rounding down.
2380 # Then, if the result is inexact and its last digit is 0 or 5,
2381 # we increase the last digit to 1 or 6 respectively; if it's
2382 # exact we leave the last digit alone. Now the final round to
2383 # p places (or fewer in the case of underflow) will round
2384 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002385
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002386 # use an extra digit of precision
2387 prec = context.prec+1
2388
2389 # write argument in the form c*100**e where e = self._exp//2
2390 # is the 'ideal' exponent, to be used if the square root is
2391 # exactly representable. l is the number of 'digits' of c in
2392 # base 100, so that 100**(l-1) <= c < 100**l.
2393 op = _WorkRep(self)
2394 e = op.exp >> 1
2395 if op.exp & 1:
2396 c = op.int * 10
2397 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002398 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002399 c = op.int
2400 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002401
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002402 # rescale so that c has exactly prec base 100 'digits'
2403 shift = prec-l
2404 if shift >= 0:
2405 c *= 100**shift
2406 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002407 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002408 c, remainder = divmod(c, 100**-shift)
2409 exact = not remainder
2410 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002411
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002412 # find n = floor(sqrt(c)) using Newton's method
2413 n = 10**prec
2414 while True:
2415 q = c//n
2416 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002417 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002418 else:
2419 n = n + q >> 1
2420 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002421
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002422 if exact:
2423 # result is exact; rescale to use ideal exponent e
2424 if shift >= 0:
2425 # assert n % 10**shift == 0
2426 n //= 10**shift
2427 else:
2428 n *= 10**-shift
2429 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002430 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002431 # result is not exact; fix last digit as described above
2432 if n % 5 == 0:
2433 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002434
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002435 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002436
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002437 # round, and fit to current context
2438 context = context._shallow_copy()
2439 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002440 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002441 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002442
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002443 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002444
2445 def max(self, other, context=None):
2446 """Returns the larger value.
2447
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002448 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002449 NaN (and signals if one is sNaN). Also rounds.
2450 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002451 other = _convert_other(other, raiseit=True)
2452
2453 if context is None:
2454 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002455
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002456 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002457 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002458 # number is always returned
2459 sn = self._isnan()
2460 on = other._isnan()
2461 if sn or on:
2462 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002463 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002464 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002465 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002466 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002467
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002468 c = self.__cmp__(other)
2469 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002470 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002471 # then an ordering is applied:
2472 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002473 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002474 # positive sign and min returns the operand with the negative sign
2475 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002476 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002477 # the result. This is exactly the ordering used in compare_total.
2478 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002479
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002480 if c == -1:
2481 ans = other
2482 else:
2483 ans = self
2484
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002485 if context._rounding_decision == ALWAYS_ROUND:
2486 return ans._fix(context)
2487 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002488
2489 def min(self, other, context=None):
2490 """Returns the smaller value.
2491
Guido van Rossumd8faa362007-04-27 19:54:29 +00002492 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002493 NaN (and signals if one is sNaN). Also rounds.
2494 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002495 other = _convert_other(other, raiseit=True)
2496
2497 if context is None:
2498 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002499
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002500 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002501 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002502 # number is always returned
2503 sn = self._isnan()
2504 on = other._isnan()
2505 if sn or on:
2506 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002507 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002508 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002509 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002510 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002511
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002512 c = self.__cmp__(other)
2513 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002514 c = self.compare_total(other)
2515
2516 if c == -1:
2517 ans = self
2518 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002519 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002520
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002521 if context._rounding_decision == ALWAYS_ROUND:
2522 return ans._fix(context)
2523 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002524
2525 def _isinteger(self):
2526 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002527 if self._is_special:
2528 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002529 if self._exp >= 0:
2530 return True
2531 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002532 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002533
2534 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002535 """Returns True if self is even. Assumes self is an integer."""
2536 if not self or self._exp > 0:
2537 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002538 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002539
2540 def adjusted(self):
2541 """Return the adjusted exponent of self"""
2542 try:
2543 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002544 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002545 except TypeError:
2546 return 0
2547
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002548 def canonical(self, context=None):
2549 """Returns the same Decimal object.
2550
2551 As we do not have different encodings for the same number, the
2552 received object already is in its canonical form.
2553 """
2554 return self
2555
2556 def compare_signal(self, other, context=None):
2557 """Compares self to the other operand numerically.
2558
2559 It's pretty much like compare(), but all NaNs signal, with signaling
2560 NaNs taking precedence over quiet NaNs.
2561 """
2562 if context is None:
2563 context = getcontext()
2564
2565 self_is_nan = self._isnan()
2566 other_is_nan = other._isnan()
2567 if self_is_nan == 2:
2568 return context._raise_error(InvalidOperation, 'sNaN',
2569 1, self)
2570 if other_is_nan == 2:
2571 return context._raise_error(InvalidOperation, 'sNaN',
2572 1, other)
2573 if self_is_nan:
2574 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2575 1, self)
2576 if other_is_nan:
2577 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2578 1, other)
2579 return self.compare(other, context=context)
2580
2581 def compare_total(self, other):
2582 """Compares self to other using the abstract representations.
2583
2584 This is not like the standard compare, which use their numerical
2585 value. Note that a total ordering is defined for all possible abstract
2586 representations.
2587 """
2588 # if one is negative and the other is positive, it's easy
2589 if self._sign and not other._sign:
2590 return Dec_n1
2591 if not self._sign and other._sign:
2592 return Dec_p1
2593 sign = self._sign
2594
2595 # let's handle both NaN types
2596 self_nan = self._isnan()
2597 other_nan = other._isnan()
2598 if self_nan or other_nan:
2599 if self_nan == other_nan:
2600 if self._int < other._int:
2601 if sign:
2602 return Dec_p1
2603 else:
2604 return Dec_n1
2605 if self._int > other._int:
2606 if sign:
2607 return Dec_n1
2608 else:
2609 return Dec_p1
2610 return Dec_0
2611
2612 if sign:
2613 if self_nan == 1:
2614 return Dec_n1
2615 if other_nan == 1:
2616 return Dec_p1
2617 if self_nan == 2:
2618 return Dec_n1
2619 if other_nan == 2:
2620 return Dec_p1
2621 else:
2622 if self_nan == 1:
2623 return Dec_p1
2624 if other_nan == 1:
2625 return Dec_n1
2626 if self_nan == 2:
2627 return Dec_p1
2628 if other_nan == 2:
2629 return Dec_n1
2630
2631 if self < other:
2632 return Dec_n1
2633 if self > other:
2634 return Dec_p1
2635
2636 if self._exp < other._exp:
2637 if sign:
2638 return Dec_p1
2639 else:
2640 return Dec_n1
2641 if self._exp > other._exp:
2642 if sign:
2643 return Dec_n1
2644 else:
2645 return Dec_p1
2646 return Dec_0
2647
2648
2649 def compare_total_mag(self, other):
2650 """Compares self to other using abstract repr., ignoring sign.
2651
2652 Like compare_total, but with operand's sign ignored and assumed to be 0.
2653 """
2654 s = self.copy_abs()
2655 o = other.copy_abs()
2656 return s.compare_total(o)
2657
2658 def copy_abs(self):
2659 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002660 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002661
2662 def copy_negate(self):
2663 """Returns a copy with the sign inverted."""
2664 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002665 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002666 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002667 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002668
2669 def copy_sign(self, other):
2670 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002671 return _dec_from_triple(other._sign, self._int,
2672 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002673
2674 def exp(self, context=None):
2675 """Returns e ** self."""
2676
2677 if context is None:
2678 context = getcontext()
2679
2680 # exp(NaN) = NaN
2681 ans = self._check_nans(context=context)
2682 if ans:
2683 return ans
2684
2685 # exp(-Infinity) = 0
2686 if self._isinfinity() == -1:
2687 return Dec_0
2688
2689 # exp(0) = 1
2690 if not self:
2691 return Dec_p1
2692
2693 # exp(Infinity) = Infinity
2694 if self._isinfinity() == 1:
2695 return Decimal(self)
2696
2697 # the result is now guaranteed to be inexact (the true
2698 # mathematical result is transcendental). There's no need to
2699 # raise Rounded and Inexact here---they'll always be raised as
2700 # a result of the call to _fix.
2701 p = context.prec
2702 adj = self.adjusted()
2703
2704 # we only need to do any computation for quite a small range
2705 # of adjusted exponents---for example, -29 <= adj <= 10 for
2706 # the default context. For smaller exponent the result is
2707 # indistinguishable from 1 at the given precision, while for
2708 # larger exponent the result either overflows or underflows.
2709 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2710 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002711 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002712 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2713 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002714 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002715 elif self._sign == 0 and adj < -p:
2716 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002717 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002718 elif self._sign == 1 and adj < -p-1:
2719 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002720 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002721 # general case
2722 else:
2723 op = _WorkRep(self)
2724 c, e = op.int, op.exp
2725 if op.sign == 1:
2726 c = -c
2727
2728 # compute correctly rounded result: increase precision by
2729 # 3 digits at a time until we get an unambiguously
2730 # roundable result
2731 extra = 3
2732 while True:
2733 coeff, exp = _dexp(c, e, p+extra)
2734 if coeff % (5*10**(len(str(coeff))-p-1)):
2735 break
2736 extra += 3
2737
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002738 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002739
2740 # at this stage, ans should round correctly with *any*
2741 # rounding mode, not just with ROUND_HALF_EVEN
2742 context = context._shallow_copy()
2743 rounding = context._set_rounding(ROUND_HALF_EVEN)
2744 ans = ans._fix(context)
2745 context.rounding = rounding
2746
2747 return ans
2748
2749 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002750 """Return True if self is canonical; otherwise return False.
2751
2752 Currently, the encoding of a Decimal instance is always
2753 canonical, so this method returns True for any Decimal.
2754 """
2755 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002756
2757 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002758 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002759
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002760 A Decimal instance is considered finite if it is neither
2761 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002762 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002763 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002764
2765 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002766 """Return True if self is infinite; otherwise return False."""
2767 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002768
2769 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002770 """Return True if self is a qNaN or sNaN; otherwise return False."""
2771 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002772
2773 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002774 """Return True if self is a normal number; otherwise return False."""
2775 if self._is_special or not self:
2776 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002777 if context is None:
2778 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002779 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002780
2781 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002782 """Return True if self is a quiet NaN; otherwise return False."""
2783 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002784
2785 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002786 """Return True if self is negative; otherwise return False."""
2787 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002788
2789 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002790 """Return True if self is a signaling NaN; otherwise return False."""
2791 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002792
2793 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002794 """Return True if self is subnormal; otherwise return False."""
2795 if self._is_special or not self:
2796 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002797 if context is None:
2798 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002799 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002800
2801 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002802 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002803 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002804
2805 def _ln_exp_bound(self):
2806 """Compute a lower bound for the adjusted exponent of self.ln().
2807 In other words, compute r such that self.ln() >= 10**r. Assumes
2808 that self is finite and positive and that self != 1.
2809 """
2810
2811 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2812 adj = self._exp + len(self._int) - 1
2813 if adj >= 1:
2814 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2815 return len(str(adj*23//10)) - 1
2816 if adj <= -2:
2817 # argument <= 0.1
2818 return len(str((-1-adj)*23//10)) - 1
2819 op = _WorkRep(self)
2820 c, e = op.int, op.exp
2821 if adj == 0:
2822 # 1 < self < 10
2823 num = str(c-10**-e)
2824 den = str(c)
2825 return len(num) - len(den) - (num < den)
2826 # adj == -1, 0.1 <= self < 1
2827 return e + len(str(10**-e - c)) - 1
2828
2829
2830 def ln(self, context=None):
2831 """Returns the natural (base e) logarithm of self."""
2832
2833 if context is None:
2834 context = getcontext()
2835
2836 # ln(NaN) = NaN
2837 ans = self._check_nans(context=context)
2838 if ans:
2839 return ans
2840
2841 # ln(0.0) == -Infinity
2842 if not self:
2843 return negInf
2844
2845 # ln(Infinity) = Infinity
2846 if self._isinfinity() == 1:
2847 return Inf
2848
2849 # ln(1.0) == 0.0
2850 if self == Dec_p1:
2851 return Dec_0
2852
2853 # ln(negative) raises InvalidOperation
2854 if self._sign == 1:
2855 return context._raise_error(InvalidOperation,
2856 'ln of a negative value')
2857
2858 # result is irrational, so necessarily inexact
2859 op = _WorkRep(self)
2860 c, e = op.int, op.exp
2861 p = context.prec
2862
2863 # correctly rounded result: repeatedly increase precision by 3
2864 # until we get an unambiguously roundable result
2865 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2866 while True:
2867 coeff = _dlog(c, e, places)
2868 # assert len(str(abs(coeff)))-p >= 1
2869 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2870 break
2871 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002872 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002873
2874 context = context._shallow_copy()
2875 rounding = context._set_rounding(ROUND_HALF_EVEN)
2876 ans = ans._fix(context)
2877 context.rounding = rounding
2878 return ans
2879
2880 def _log10_exp_bound(self):
2881 """Compute a lower bound for the adjusted exponent of self.log10().
2882 In other words, find r such that self.log10() >= 10**r.
2883 Assumes that self is finite and positive and that self != 1.
2884 """
2885
2886 # For x >= 10 or x < 0.1 we only need a bound on the integer
2887 # part of log10(self), and this comes directly from the
2888 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2889 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2890 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2891
2892 adj = self._exp + len(self._int) - 1
2893 if adj >= 1:
2894 # self >= 10
2895 return len(str(adj))-1
2896 if adj <= -2:
2897 # self < 0.1
2898 return len(str(-1-adj))-1
2899 op = _WorkRep(self)
2900 c, e = op.int, op.exp
2901 if adj == 0:
2902 # 1 < self < 10
2903 num = str(c-10**-e)
2904 den = str(231*c)
2905 return len(num) - len(den) - (num < den) + 2
2906 # adj == -1, 0.1 <= self < 1
2907 num = str(10**-e-c)
2908 return len(num) + e - (num < "231") - 1
2909
2910 def log10(self, context=None):
2911 """Returns the base 10 logarithm of self."""
2912
2913 if context is None:
2914 context = getcontext()
2915
2916 # log10(NaN) = NaN
2917 ans = self._check_nans(context=context)
2918 if ans:
2919 return ans
2920
2921 # log10(0.0) == -Infinity
2922 if not self:
2923 return negInf
2924
2925 # log10(Infinity) = Infinity
2926 if self._isinfinity() == 1:
2927 return Inf
2928
2929 # log10(negative or -Infinity) raises InvalidOperation
2930 if self._sign == 1:
2931 return context._raise_error(InvalidOperation,
2932 'log10 of a negative value')
2933
2934 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002935 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002936 # answer may need rounding
2937 ans = Decimal(self._exp + len(self._int) - 1)
2938 else:
2939 # result is irrational, so necessarily inexact
2940 op = _WorkRep(self)
2941 c, e = op.int, op.exp
2942 p = context.prec
2943
2944 # correctly rounded result: repeatedly increase precision
2945 # until result is unambiguously roundable
2946 places = p-self._log10_exp_bound()+2
2947 while True:
2948 coeff = _dlog10(c, e, places)
2949 # assert len(str(abs(coeff)))-p >= 1
2950 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2951 break
2952 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002953 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002954
2955 context = context._shallow_copy()
2956 rounding = context._set_rounding(ROUND_HALF_EVEN)
2957 ans = ans._fix(context)
2958 context.rounding = rounding
2959 return ans
2960
2961 def logb(self, context=None):
2962 """ Returns the exponent of the magnitude of self's MSD.
2963
2964 The result is the integer which is the exponent of the magnitude
2965 of the most significant digit of self (as though it were truncated
2966 to a single digit while maintaining the value of that digit and
2967 without limiting the resulting exponent).
2968 """
2969 # logb(NaN) = NaN
2970 ans = self._check_nans(context=context)
2971 if ans:
2972 return ans
2973
2974 if context is None:
2975 context = getcontext()
2976
2977 # logb(+/-Inf) = +Inf
2978 if self._isinfinity():
2979 return Inf
2980
2981 # logb(0) = -Inf, DivisionByZero
2982 if not self:
2983 return context._raise_error(DivisionByZero, 'logb(0)', 1)
2984
2985 # otherwise, simply return the adjusted exponent of self, as a
2986 # Decimal. Note that no attempt is made to fit the result
2987 # into the current context.
2988 return Decimal(self.adjusted())
2989
2990 def _islogical(self):
2991 """Return True if self is a logical operand.
2992
2993 For being logical, it must be a finite numbers with a sign of 0,
2994 an exponent of 0, and a coefficient whose digits must all be
2995 either 0 or 1.
2996 """
2997 if self._sign != 0 or self._exp != 0:
2998 return False
2999 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003000 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003001 return False
3002 return True
3003
3004 def _fill_logical(self, context, opa, opb):
3005 dif = context.prec - len(opa)
3006 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003007 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003008 elif dif < 0:
3009 opa = opa[-context.prec:]
3010 dif = context.prec - len(opb)
3011 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003012 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003013 elif dif < 0:
3014 opb = opb[-context.prec:]
3015 return opa, opb
3016
3017 def logical_and(self, other, context=None):
3018 """Applies an 'and' operation between self and other's digits."""
3019 if context is None:
3020 context = getcontext()
3021 if not self._islogical() or not other._islogical():
3022 return context._raise_error(InvalidOperation)
3023
3024 # fill to context.prec
3025 (opa, opb) = self._fill_logical(context, self._int, other._int)
3026
3027 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003028 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3029 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003030
3031 def logical_invert(self, context=None):
3032 """Invert all its digits."""
3033 if context is None:
3034 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003035 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3036 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003037
3038 def logical_or(self, other, context=None):
3039 """Applies an 'or' operation between self and other's digits."""
3040 if context is None:
3041 context = getcontext()
3042 if not self._islogical() or not other._islogical():
3043 return context._raise_error(InvalidOperation)
3044
3045 # fill to context.prec
3046 (opa, opb) = self._fill_logical(context, self._int, other._int)
3047
3048 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003049 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3050 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003051
3052 def logical_xor(self, other, context=None):
3053 """Applies an 'xor' operation between self and other's digits."""
3054 if context is None:
3055 context = getcontext()
3056 if not self._islogical() or not other._islogical():
3057 return context._raise_error(InvalidOperation)
3058
3059 # fill to context.prec
3060 (opa, opb) = self._fill_logical(context, self._int, other._int)
3061
3062 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003063 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3064 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003065
3066 def max_mag(self, other, context=None):
3067 """Compares the values numerically with their sign ignored."""
3068 other = _convert_other(other, raiseit=True)
3069
3070 if context is None:
3071 context = getcontext()
3072
3073 if self._is_special or other._is_special:
3074 # If one operand is a quiet NaN and the other is number, then the
3075 # number is always returned
3076 sn = self._isnan()
3077 on = other._isnan()
3078 if sn or on:
3079 if on == 1 and sn != 2:
3080 return self._fix_nan(context)
3081 if sn == 1 and on != 2:
3082 return other._fix_nan(context)
3083 return self._check_nans(other, context)
3084
3085 c = self.copy_abs().__cmp__(other.copy_abs())
3086 if c == 0:
3087 c = self.compare_total(other)
3088
3089 if c == -1:
3090 ans = other
3091 else:
3092 ans = self
3093
3094 if context._rounding_decision == ALWAYS_ROUND:
3095 return ans._fix(context)
3096 return ans
3097
3098 def min_mag(self, other, context=None):
3099 """Compares the values numerically with their sign ignored."""
3100 other = _convert_other(other, raiseit=True)
3101
3102 if context is None:
3103 context = getcontext()
3104
3105 if self._is_special or other._is_special:
3106 # If one operand is a quiet NaN and the other is number, then the
3107 # number is always returned
3108 sn = self._isnan()
3109 on = other._isnan()
3110 if sn or on:
3111 if on == 1 and sn != 2:
3112 return self._fix_nan(context)
3113 if sn == 1 and on != 2:
3114 return other._fix_nan(context)
3115 return self._check_nans(other, context)
3116
3117 c = self.copy_abs().__cmp__(other.copy_abs())
3118 if c == 0:
3119 c = self.compare_total(other)
3120
3121 if c == -1:
3122 ans = self
3123 else:
3124 ans = other
3125
3126 if context._rounding_decision == ALWAYS_ROUND:
3127 return ans._fix(context)
3128 return ans
3129
3130 def next_minus(self, context=None):
3131 """Returns the largest representable number smaller than itself."""
3132 if context is None:
3133 context = getcontext()
3134
3135 ans = self._check_nans(context=context)
3136 if ans:
3137 return ans
3138
3139 if self._isinfinity() == -1:
3140 return negInf
3141 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003142 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003143
3144 context = context.copy()
3145 context._set_rounding(ROUND_FLOOR)
3146 context._ignore_all_flags()
3147 new_self = self._fix(context)
3148 if new_self != self:
3149 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003150 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3151 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003152
3153 def next_plus(self, context=None):
3154 """Returns the smallest representable number larger than itself."""
3155 if context is None:
3156 context = getcontext()
3157
3158 ans = self._check_nans(context=context)
3159 if ans:
3160 return ans
3161
3162 if self._isinfinity() == 1:
3163 return Inf
3164 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003165 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003166
3167 context = context.copy()
3168 context._set_rounding(ROUND_CEILING)
3169 context._ignore_all_flags()
3170 new_self = self._fix(context)
3171 if new_self != self:
3172 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003173 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3174 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003175
3176 def next_toward(self, other, context=None):
3177 """Returns the number closest to self, in the direction towards other.
3178
3179 The result is the closest representable number to self
3180 (excluding self) that is in the direction towards other,
3181 unless both have the same value. If the two operands are
3182 numerically equal, then the result is a copy of self with the
3183 sign set to be the same as the sign of other.
3184 """
3185 other = _convert_other(other, raiseit=True)
3186
3187 if context is None:
3188 context = getcontext()
3189
3190 ans = self._check_nans(other, context)
3191 if ans:
3192 return ans
3193
3194 comparison = self.__cmp__(other)
3195 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003196 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003197
3198 if comparison == -1:
3199 ans = self.next_plus(context)
3200 else: # comparison == 1
3201 ans = self.next_minus(context)
3202
3203 # decide which flags to raise using value of ans
3204 if ans._isinfinity():
3205 context._raise_error(Overflow,
3206 'Infinite result from next_toward',
3207 ans._sign)
3208 context._raise_error(Rounded)
3209 context._raise_error(Inexact)
3210 elif ans.adjusted() < context.Emin:
3211 context._raise_error(Underflow)
3212 context._raise_error(Subnormal)
3213 context._raise_error(Rounded)
3214 context._raise_error(Inexact)
3215 # if precision == 1 then we don't raise Clamped for a
3216 # result 0E-Etiny.
3217 if not ans:
3218 context._raise_error(Clamped)
3219
3220 return ans
3221
3222 def number_class(self, context=None):
3223 """Returns an indication of the class of self.
3224
3225 The class is one of the following strings:
3226 -sNaN
3227 -NaN
3228 -Infinity
3229 -Normal
3230 -Subnormal
3231 -Zero
3232 +Zero
3233 +Subnormal
3234 +Normal
3235 +Infinity
3236 """
3237 if self.is_snan():
3238 return "sNaN"
3239 if self.is_qnan():
3240 return "NaN"
3241 inf = self._isinfinity()
3242 if inf == 1:
3243 return "+Infinity"
3244 if inf == -1:
3245 return "-Infinity"
3246 if self.is_zero():
3247 if self._sign:
3248 return "-Zero"
3249 else:
3250 return "+Zero"
3251 if context is None:
3252 context = getcontext()
3253 if self.is_subnormal(context=context):
3254 if self._sign:
3255 return "-Subnormal"
3256 else:
3257 return "+Subnormal"
3258 # just a normal, regular, boring number, :)
3259 if self._sign:
3260 return "-Normal"
3261 else:
3262 return "+Normal"
3263
3264 def radix(self):
3265 """Just returns 10, as this is Decimal, :)"""
3266 return Decimal(10)
3267
3268 def rotate(self, other, context=None):
3269 """Returns a rotated copy of self, value-of-other times."""
3270 if context is None:
3271 context = getcontext()
3272
3273 ans = self._check_nans(other, context)
3274 if ans:
3275 return ans
3276
3277 if other._exp != 0:
3278 return context._raise_error(InvalidOperation)
3279 if not (-context.prec <= int(other) <= context.prec):
3280 return context._raise_error(InvalidOperation)
3281
3282 if self._isinfinity():
3283 return Decimal(self)
3284
3285 # get values, pad if necessary
3286 torot = int(other)
3287 rotdig = self._int
3288 topad = context.prec - len(rotdig)
3289 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003290 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003291
3292 # let's rotate!
3293 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003294 return _dec_from_triple(self._sign,
3295 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003296
3297 def scaleb (self, other, context=None):
3298 """Returns self operand after adding the second value to its exp."""
3299 if context is None:
3300 context = getcontext()
3301
3302 ans = self._check_nans(other, context)
3303 if ans:
3304 return ans
3305
3306 if other._exp != 0:
3307 return context._raise_error(InvalidOperation)
3308 liminf = -2 * (context.Emax + context.prec)
3309 limsup = 2 * (context.Emax + context.prec)
3310 if not (liminf <= int(other) <= limsup):
3311 return context._raise_error(InvalidOperation)
3312
3313 if self._isinfinity():
3314 return Decimal(self)
3315
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003316 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003317 d = d._fix(context)
3318 return d
3319
3320 def shift(self, other, context=None):
3321 """Returns a shifted copy of self, value-of-other times."""
3322 if context is None:
3323 context = getcontext()
3324
3325 ans = self._check_nans(other, context)
3326 if ans:
3327 return ans
3328
3329 if other._exp != 0:
3330 return context._raise_error(InvalidOperation)
3331 if not (-context.prec <= int(other) <= context.prec):
3332 return context._raise_error(InvalidOperation)
3333
3334 if self._isinfinity():
3335 return Decimal(self)
3336
3337 # get values, pad if necessary
3338 torot = int(other)
3339 if not torot:
3340 return Decimal(self)
3341 rotdig = self._int
3342 topad = context.prec - len(rotdig)
3343 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003344 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003345
3346 # let's shift!
3347 if torot < 0:
3348 rotated = rotdig[:torot]
3349 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003350 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003351 rotated = rotated[-context.prec:]
3352
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003353 return _dec_from_triple(self._sign,
3354 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003355
Guido van Rossumd8faa362007-04-27 19:54:29 +00003356 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003357 def __reduce__(self):
3358 return (self.__class__, (str(self),))
3359
3360 def __copy__(self):
3361 if type(self) == Decimal:
3362 return self # I'm immutable; therefore I am my own clone
3363 return self.__class__(str(self))
3364
3365 def __deepcopy__(self, memo):
3366 if type(self) == Decimal:
3367 return self # My components are also immutable
3368 return self.__class__(str(self))
3369
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003370def _dec_from_triple(sign, coefficient, exponent, special=False):
3371 """Create a decimal instance directly, without any validation,
3372 normalization (e.g. removal of leading zeros) or argument
3373 conversion.
3374
3375 This function is for *internal use only*.
3376 """
3377
3378 self = object.__new__(Decimal)
3379 self._sign = sign
3380 self._int = coefficient
3381 self._exp = exponent
3382 self._is_special = special
3383
3384 return self
3385
Guido van Rossumd8faa362007-04-27 19:54:29 +00003386##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003387
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003388
3389# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003390rounding_functions = [name for name in Decimal.__dict__.keys()
3391 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003392for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003393 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003394 globalname = name[1:].upper()
3395 val = globals()[globalname]
3396 Decimal._pick_rounding_function[val] = name
3397
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003398del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003399
Thomas Wouters89f507f2006-12-13 04:49:30 +00003400class _ContextManager(object):
3401 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003402
Thomas Wouters89f507f2006-12-13 04:49:30 +00003403 Sets a copy of the supplied context in __enter__() and restores
3404 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003405 """
3406 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003407 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003408 def __enter__(self):
3409 self.saved_context = getcontext()
3410 setcontext(self.new_context)
3411 return self.new_context
3412 def __exit__(self, t, v, tb):
3413 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003414
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003415class Context(object):
3416 """Contains the context for a Decimal instance.
3417
3418 Contains:
3419 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003420 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003421 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003422 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003423 raised when it is caused. Otherwise, a value is
3424 substituted in.
3425 flags - When an exception is caused, flags[exception] is incremented.
3426 (Whether or not the trap_enabler is set)
3427 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003428 Emin - Minimum exponent
3429 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003430 capitals - If 1, 1*10^1 is printed as 1E+1.
3431 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003432 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003433 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003434
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003435 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003436 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003437 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003438 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003439 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003440 _ignored_flags=None):
3441 if flags is None:
3442 flags = []
3443 if _ignored_flags is None:
3444 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003445 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003446 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003447 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003448 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003449 for name, val in locals().items():
3450 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003451 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003452 else:
3453 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003454 del self.self
3455
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003456 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003457 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003458 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003459 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3460 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3461 % vars(self))
3462 names = [f.__name__ for f, v in self.flags.items() if v]
3463 s.append('flags=[' + ', '.join(names) + ']')
3464 names = [t.__name__ for t, v in self.traps.items() if v]
3465 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003466 return ', '.join(s) + ')'
3467
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003468 def clear_flags(self):
3469 """Reset all flags to zero"""
3470 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003471 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003472
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003473 def _shallow_copy(self):
3474 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003475 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003476 self._rounding_decision, self.Emin, self.Emax,
3477 self.capitals, self._clamp, self._ignored_flags)
3478 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003479
3480 def copy(self):
3481 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003482 nc = Context(self.prec, self.rounding, self.traps.copy(),
3483 self.flags.copy(), self._rounding_decision, self.Emin,
3484 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003485 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003486 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003487
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003488 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003489 """Handles an error
3490
3491 If the flag is in _ignored_flags, returns the default response.
3492 Otherwise, it increments the flag, then, if the corresponding
3493 trap_enabler is set, it reaises the exception. Otherwise, it returns
3494 the default value after incrementing the flag.
3495 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003496 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003497 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003498 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003499 return error().handle(self, *args)
3500
3501 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003502 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003503 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003504 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003505
3506 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003507 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003508 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003509
3510 def _ignore_all_flags(self):
3511 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003512 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003513
3514 def _ignore_flags(self, *flags):
3515 """Ignore the flags, if they are raised"""
3516 # Do not mutate-- This way, copies of a context leave the original
3517 # alone.
3518 self._ignored_flags = (self._ignored_flags + list(flags))
3519 return list(flags)
3520
3521 def _regard_flags(self, *flags):
3522 """Stop ignoring the flags, if they are raised"""
3523 if flags and isinstance(flags[0], (tuple,list)):
3524 flags = flags[0]
3525 for flag in flags:
3526 self._ignored_flags.remove(flag)
3527
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003528 def __hash__(self):
3529 """A Context cannot be hashed."""
3530 # We inherit object.__hash__, so we must deny this explicitly
Guido van Rossumd8faa362007-04-27 19:54:29 +00003531 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003532
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003533 def Etiny(self):
3534 """Returns Etiny (= Emin - prec + 1)"""
3535 return int(self.Emin - self.prec + 1)
3536
3537 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003538 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003539 return int(self.Emax - self.prec + 1)
3540
3541 def _set_rounding_decision(self, type):
3542 """Sets the rounding decision.
3543
3544 Sets the rounding decision, and returns the current (previous)
3545 rounding decision. Often used like:
3546
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003547 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003548 # That so you don't change the calling context
3549 # if an error occurs in the middle (say DivisionImpossible is raised).
3550
3551 rounding = context._set_rounding_decision(NEVER_ROUND)
3552 instance = instance / Decimal(2)
3553 context._set_rounding_decision(rounding)
3554
3555 This will make it not round for that operation.
3556 """
3557
3558 rounding = self._rounding_decision
3559 self._rounding_decision = type
3560 return rounding
3561
3562 def _set_rounding(self, type):
3563 """Sets the rounding type.
3564
3565 Sets the rounding type, and returns the current (previous)
3566 rounding type. Often used like:
3567
3568 context = context.copy()
3569 # so you don't change the calling context
3570 # if an error occurs in the middle.
3571 rounding = context._set_rounding(ROUND_UP)
3572 val = self.__sub__(other, context=context)
3573 context._set_rounding(rounding)
3574
3575 This will make it round up for that operation.
3576 """
3577 rounding = self.rounding
3578 self.rounding= type
3579 return rounding
3580
Raymond Hettingerfed52962004-07-14 15:41:57 +00003581 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003582 """Creates a new Decimal instance but using self as context."""
3583 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003584 if d._isnan() and len(d._int) > self.prec - self._clamp:
3585 return self._raise_error(ConversionSyntax,
3586 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003587 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003588
Guido van Rossumd8faa362007-04-27 19:54:29 +00003589 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003590 def abs(self, a):
3591 """Returns the absolute value of the operand.
3592
3593 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003594 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003595 the plus operation on the operand.
3596
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003597 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003598 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003599 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003600 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003601 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003602 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003603 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003604 Decimal("101.5")
3605 """
3606 return a.__abs__(context=self)
3607
3608 def add(self, a, b):
3609 """Return the sum of the two operands.
3610
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003611 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003612 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003613 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003614 Decimal("1.02E+4")
3615 """
3616 return a.__add__(b, context=self)
3617
3618 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003619 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003620
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003621 def canonical(self, a):
3622 """Returns the same Decimal object.
3623
3624 As we do not have different encodings for the same number, the
3625 received object already is in its canonical form.
3626
3627 >>> ExtendedContext.canonical(Decimal('2.50'))
3628 Decimal("2.50")
3629 """
3630 return a.canonical(context=self)
3631
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003632 def compare(self, a, b):
3633 """Compares values numerically.
3634
3635 If the signs of the operands differ, a value representing each operand
3636 ('-1' if the operand is less than zero, '0' if the operand is zero or
3637 negative zero, or '1' if the operand is greater than zero) is used in
3638 place of that operand for the comparison instead of the actual
3639 operand.
3640
3641 The comparison is then effected by subtracting the second operand from
3642 the first and then returning a value according to the result of the
3643 subtraction: '-1' if the result is less than zero, '0' if the result is
3644 zero or negative zero, or '1' if the result is greater than zero.
3645
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003646 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003647 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003648 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003649 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003650 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003651 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003652 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003653 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003654 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003655 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003656 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003657 Decimal("-1")
3658 """
3659 return a.compare(b, context=self)
3660
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003661 def compare_signal(self, a, b):
3662 """Compares the values of the two operands numerically.
3663
3664 It's pretty much like compare(), but all NaNs signal, with signaling
3665 NaNs taking precedence over quiet NaNs.
3666
3667 >>> c = ExtendedContext
3668 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3669 Decimal("-1")
3670 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3671 Decimal("0")
3672 >>> c.flags[InvalidOperation] = 0
3673 >>> print(c.flags[InvalidOperation])
3674 0
3675 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3676 Decimal("NaN")
3677 >>> print(c.flags[InvalidOperation])
3678 1
3679 >>> c.flags[InvalidOperation] = 0
3680 >>> print(c.flags[InvalidOperation])
3681 0
3682 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3683 Decimal("NaN")
3684 >>> print(c.flags[InvalidOperation])
3685 1
3686 """
3687 return a.compare_signal(b, context=self)
3688
3689 def compare_total(self, a, b):
3690 """Compares two operands using their abstract representation.
3691
3692 This is not like the standard compare, which use their numerical
3693 value. Note that a total ordering is defined for all possible abstract
3694 representations.
3695
3696 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3697 Decimal("-1")
3698 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3699 Decimal("-1")
3700 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3701 Decimal("-1")
3702 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3703 Decimal("0")
3704 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3705 Decimal("1")
3706 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3707 Decimal("-1")
3708 """
3709 return a.compare_total(b)
3710
3711 def compare_total_mag(self, a, b):
3712 """Compares two operands using their abstract representation ignoring sign.
3713
3714 Like compare_total, but with operand's sign ignored and assumed to be 0.
3715 """
3716 return a.compare_total_mag(b)
3717
3718 def copy_abs(self, a):
3719 """Returns a copy of the operand with the sign set to 0.
3720
3721 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3722 Decimal("2.1")
3723 >>> ExtendedContext.copy_abs(Decimal('-100'))
3724 Decimal("100")
3725 """
3726 return a.copy_abs()
3727
3728 def copy_decimal(self, a):
3729 """Returns a copy of the decimal objet.
3730
3731 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3732 Decimal("2.1")
3733 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3734 Decimal("-1.00")
3735 """
3736 return Decimal(a)
3737
3738 def copy_negate(self, a):
3739 """Returns a copy of the operand with the sign inverted.
3740
3741 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3742 Decimal("-101.5")
3743 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3744 Decimal("101.5")
3745 """
3746 return a.copy_negate()
3747
3748 def copy_sign(self, a, b):
3749 """Copies the second operand's sign to the first one.
3750
3751 In detail, it returns a copy of the first operand with the sign
3752 equal to the sign of the second operand.
3753
3754 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3755 Decimal("1.50")
3756 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3757 Decimal("1.50")
3758 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3759 Decimal("-1.50")
3760 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3761 Decimal("-1.50")
3762 """
3763 return a.copy_sign(b)
3764
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003765 def divide(self, a, b):
3766 """Decimal division in a specified context.
3767
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003768 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003769 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003770 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003771 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003772 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003773 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003774 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003775 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003776 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003777 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003778 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003779 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003780 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003781 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003782 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003783 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003784 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003785 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003786 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003787 Decimal("1.20E+6")
3788 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003789 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003790
3791 def divide_int(self, a, b):
3792 """Divides two numbers and returns the integer part of the result.
3793
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003794 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003795 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003796 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003797 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003798 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003799 Decimal("3")
3800 """
3801 return a.__floordiv__(b, context=self)
3802
3803 def divmod(self, a, b):
3804 return a.__divmod__(b, context=self)
3805
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003806 def exp(self, a):
3807 """Returns e ** a.
3808
3809 >>> c = ExtendedContext.copy()
3810 >>> c.Emin = -999
3811 >>> c.Emax = 999
3812 >>> c.exp(Decimal('-Infinity'))
3813 Decimal("0")
3814 >>> c.exp(Decimal('-1'))
3815 Decimal("0.367879441")
3816 >>> c.exp(Decimal('0'))
3817 Decimal("1")
3818 >>> c.exp(Decimal('1'))
3819 Decimal("2.71828183")
3820 >>> c.exp(Decimal('0.693147181'))
3821 Decimal("2.00000000")
3822 >>> c.exp(Decimal('+Infinity'))
3823 Decimal("Infinity")
3824 """
3825 return a.exp(context=self)
3826
3827 def fma(self, a, b, c):
3828 """Returns a multiplied by b, plus c.
3829
3830 The first two operands are multiplied together, using multiply,
3831 the third operand is then added to the result of that
3832 multiplication, using add, all with only one final rounding.
3833
3834 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3835 Decimal("22")
3836 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3837 Decimal("-8")
3838 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3839 Decimal("1.38435736E+12")
3840 """
3841 return a.fma(b, c, context=self)
3842
3843 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003844 """Return True if the operand is canonical; otherwise return False.
3845
3846 Currently, the encoding of a Decimal instance is always
3847 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003848
3849 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003850 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003851 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003852 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003853
3854 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003855 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003856
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003857 A Decimal instance is considered finite if it is neither
3858 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003859
3860 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003861 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003862 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003863 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003864 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003865 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003866 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003867 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003868 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003869 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003870 """
3871 return a.is_finite()
3872
3873 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003874 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003875
3876 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003877 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003878 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003879 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003880 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003881 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003882 """
3883 return a.is_infinite()
3884
3885 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003886 """Return True if the operand is a qNaN or sNaN;
3887 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003888
3889 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003890 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003891 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003892 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003893 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003894 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003895 """
3896 return a.is_nan()
3897
3898 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003899 """Return True if the operand is a normal number;
3900 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003901
3902 >>> c = ExtendedContext.copy()
3903 >>> c.Emin = -999
3904 >>> c.Emax = 999
3905 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003906 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003907 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003908 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003909 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003910 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003911 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003912 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003913 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003914 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003915 """
3916 return a.is_normal(context=self)
3917
3918 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003919 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003920
3921 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003922 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003923 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003924 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003925 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003926 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003927 """
3928 return a.is_qnan()
3929
3930 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003931 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003932
3933 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003934 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003935 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003936 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003937 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003938 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003939 """
3940 return a.is_signed()
3941
3942 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003943 """Return True if the operand is a signaling NaN;
3944 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003945
3946 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003947 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003948 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003949 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003950 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003951 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003952 """
3953 return a.is_snan()
3954
3955 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003956 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003957
3958 >>> c = ExtendedContext.copy()
3959 >>> c.Emin = -999
3960 >>> c.Emax = 999
3961 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003962 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003963 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003964 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003965 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003966 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003967 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003968 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003969 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003970 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003971 """
3972 return a.is_subnormal(context=self)
3973
3974 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003975 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003976
3977 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003978 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003979 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003980 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003981 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003982 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003983 """
3984 return a.is_zero()
3985
3986 def ln(self, a):
3987 """Returns the natural (base e) logarithm of the operand.
3988
3989 >>> c = ExtendedContext.copy()
3990 >>> c.Emin = -999
3991 >>> c.Emax = 999
3992 >>> c.ln(Decimal('0'))
3993 Decimal("-Infinity")
3994 >>> c.ln(Decimal('1.000'))
3995 Decimal("0")
3996 >>> c.ln(Decimal('2.71828183'))
3997 Decimal("1.00000000")
3998 >>> c.ln(Decimal('10'))
3999 Decimal("2.30258509")
4000 >>> c.ln(Decimal('+Infinity'))
4001 Decimal("Infinity")
4002 """
4003 return a.ln(context=self)
4004
4005 def log10(self, a):
4006 """Returns the base 10 logarithm of the operand.
4007
4008 >>> c = ExtendedContext.copy()
4009 >>> c.Emin = -999
4010 >>> c.Emax = 999
4011 >>> c.log10(Decimal('0'))
4012 Decimal("-Infinity")
4013 >>> c.log10(Decimal('0.001'))
4014 Decimal("-3")
4015 >>> c.log10(Decimal('1.000'))
4016 Decimal("0")
4017 >>> c.log10(Decimal('2'))
4018 Decimal("0.301029996")
4019 >>> c.log10(Decimal('10'))
4020 Decimal("1")
4021 >>> c.log10(Decimal('70'))
4022 Decimal("1.84509804")
4023 >>> c.log10(Decimal('+Infinity'))
4024 Decimal("Infinity")
4025 """
4026 return a.log10(context=self)
4027
4028 def logb(self, a):
4029 """ Returns the exponent of the magnitude of the operand's MSD.
4030
4031 The result is the integer which is the exponent of the magnitude
4032 of the most significant digit of the operand (as though the
4033 operand were truncated to a single digit while maintaining the
4034 value of that digit and without limiting the resulting exponent).
4035
4036 >>> ExtendedContext.logb(Decimal('250'))
4037 Decimal("2")
4038 >>> ExtendedContext.logb(Decimal('2.50'))
4039 Decimal("0")
4040 >>> ExtendedContext.logb(Decimal('0.03'))
4041 Decimal("-2")
4042 >>> ExtendedContext.logb(Decimal('0'))
4043 Decimal("-Infinity")
4044 """
4045 return a.logb(context=self)
4046
4047 def logical_and(self, a, b):
4048 """Applies the logical operation 'and' between each operand's digits.
4049
4050 The operands must be both logical numbers.
4051
4052 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4053 Decimal("0")
4054 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4055 Decimal("0")
4056 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4057 Decimal("0")
4058 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4059 Decimal("1")
4060 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4061 Decimal("1000")
4062 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4063 Decimal("10")
4064 """
4065 return a.logical_and(b, context=self)
4066
4067 def logical_invert(self, a):
4068 """Invert all the digits in the operand.
4069
4070 The operand must be a logical number.
4071
4072 >>> ExtendedContext.logical_invert(Decimal('0'))
4073 Decimal("111111111")
4074 >>> ExtendedContext.logical_invert(Decimal('1'))
4075 Decimal("111111110")
4076 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4077 Decimal("0")
4078 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4079 Decimal("10101010")
4080 """
4081 return a.logical_invert(context=self)
4082
4083 def logical_or(self, a, b):
4084 """Applies the logical operation 'or' between each operand's digits.
4085
4086 The operands must be both logical numbers.
4087
4088 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4089 Decimal("0")
4090 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4091 Decimal("1")
4092 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4093 Decimal("1")
4094 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4095 Decimal("1")
4096 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4097 Decimal("1110")
4098 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4099 Decimal("1110")
4100 """
4101 return a.logical_or(b, context=self)
4102
4103 def logical_xor(self, a, b):
4104 """Applies the logical operation 'xor' between each operand's digits.
4105
4106 The operands must be both logical numbers.
4107
4108 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4109 Decimal("0")
4110 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4111 Decimal("1")
4112 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4113 Decimal("1")
4114 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4115 Decimal("0")
4116 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4117 Decimal("110")
4118 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4119 Decimal("1101")
4120 """
4121 return a.logical_xor(b, context=self)
4122
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004123 def max(self, a,b):
4124 """max compares two values numerically and returns the maximum.
4125
4126 If either operand is a NaN then the general rules apply.
4127 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004128 operation. If they are numerically equal then the left-hand operand
4129 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004130 infinity) of the two operands is chosen as the result.
4131
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004132 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004133 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004134 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004135 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004136 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004137 Decimal("1")
4138 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4139 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004140 """
4141 return a.max(b, context=self)
4142
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004143 def max_mag(self, a, b):
4144 """Compares the values numerically with their sign ignored."""
4145 return a.max_mag(b, context=self)
4146
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004147 def min(self, a,b):
4148 """min compares two values numerically and returns the minimum.
4149
4150 If either operand is a NaN then the general rules apply.
4151 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004152 operation. If they are numerically equal then the left-hand operand
4153 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004154 infinity) of the two operands is chosen as the result.
4155
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004156 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004157 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004158 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004159 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004160 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004161 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004162 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4163 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004164 """
4165 return a.min(b, context=self)
4166
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004167 def min_mag(self, a, b):
4168 """Compares the values numerically with their sign ignored."""
4169 return a.min_mag(b, context=self)
4170
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004171 def minus(self, a):
4172 """Minus corresponds to unary prefix minus in Python.
4173
4174 The operation is evaluated using the same rules as subtract; the
4175 operation minus(a) is calculated as subtract('0', a) where the '0'
4176 has the same exponent as the operand.
4177
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004178 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004179 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004180 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004181 Decimal("1.3")
4182 """
4183 return a.__neg__(context=self)
4184
4185 def multiply(self, a, b):
4186 """multiply multiplies two operands.
4187
4188 If either operand is a special value then the general rules apply.
4189 Otherwise, the operands are multiplied together ('long multiplication'),
4190 resulting in a number which may be as long as the sum of the lengths
4191 of the two operands.
4192
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004193 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004194 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004195 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004196 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004197 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004198 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004199 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004200 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004201 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004202 Decimal("4.28135971E+11")
4203 """
4204 return a.__mul__(b, context=self)
4205
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004206 def next_minus(self, a):
4207 """Returns the largest representable number smaller than a.
4208
4209 >>> c = ExtendedContext.copy()
4210 >>> c.Emin = -999
4211 >>> c.Emax = 999
4212 >>> ExtendedContext.next_minus(Decimal('1'))
4213 Decimal("0.999999999")
4214 >>> c.next_minus(Decimal('1E-1007'))
4215 Decimal("0E-1007")
4216 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4217 Decimal("-1.00000004")
4218 >>> c.next_minus(Decimal('Infinity'))
4219 Decimal("9.99999999E+999")
4220 """
4221 return a.next_minus(context=self)
4222
4223 def next_plus(self, a):
4224 """Returns the smallest representable number larger than a.
4225
4226 >>> c = ExtendedContext.copy()
4227 >>> c.Emin = -999
4228 >>> c.Emax = 999
4229 >>> ExtendedContext.next_plus(Decimal('1'))
4230 Decimal("1.00000001")
4231 >>> c.next_plus(Decimal('-1E-1007'))
4232 Decimal("-0E-1007")
4233 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4234 Decimal("-1.00000002")
4235 >>> c.next_plus(Decimal('-Infinity'))
4236 Decimal("-9.99999999E+999")
4237 """
4238 return a.next_plus(context=self)
4239
4240 def next_toward(self, a, b):
4241 """Returns the number closest to a, in direction towards b.
4242
4243 The result is the closest representable number from the first
4244 operand (but not the first operand) that is in the direction
4245 towards the second operand, unless the operands have the same
4246 value.
4247
4248 >>> c = ExtendedContext.copy()
4249 >>> c.Emin = -999
4250 >>> c.Emax = 999
4251 >>> c.next_toward(Decimal('1'), Decimal('2'))
4252 Decimal("1.00000001")
4253 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4254 Decimal("-0E-1007")
4255 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4256 Decimal("-1.00000002")
4257 >>> c.next_toward(Decimal('1'), Decimal('0'))
4258 Decimal("0.999999999")
4259 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4260 Decimal("0E-1007")
4261 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4262 Decimal("-1.00000004")
4263 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4264 Decimal("-0.00")
4265 """
4266 return a.next_toward(b, context=self)
4267
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004268 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004269 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004270
4271 Essentially a plus operation with all trailing zeros removed from the
4272 result.
4273
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004274 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004275 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004276 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004277 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004278 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004279 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004280 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004281 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004282 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004283 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004284 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004285 Decimal("0")
4286 """
4287 return a.normalize(context=self)
4288
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004289 def number_class(self, a):
4290 """Returns an indication of the class of the operand.
4291
4292 The class is one of the following strings:
4293 -sNaN
4294 -NaN
4295 -Infinity
4296 -Normal
4297 -Subnormal
4298 -Zero
4299 +Zero
4300 +Subnormal
4301 +Normal
4302 +Infinity
4303
4304 >>> c = Context(ExtendedContext)
4305 >>> c.Emin = -999
4306 >>> c.Emax = 999
4307 >>> c.number_class(Decimal('Infinity'))
4308 '+Infinity'
4309 >>> c.number_class(Decimal('1E-10'))
4310 '+Normal'
4311 >>> c.number_class(Decimal('2.50'))
4312 '+Normal'
4313 >>> c.number_class(Decimal('0.1E-999'))
4314 '+Subnormal'
4315 >>> c.number_class(Decimal('0'))
4316 '+Zero'
4317 >>> c.number_class(Decimal('-0'))
4318 '-Zero'
4319 >>> c.number_class(Decimal('-0.1E-999'))
4320 '-Subnormal'
4321 >>> c.number_class(Decimal('-1E-10'))
4322 '-Normal'
4323 >>> c.number_class(Decimal('-2.50'))
4324 '-Normal'
4325 >>> c.number_class(Decimal('-Infinity'))
4326 '-Infinity'
4327 >>> c.number_class(Decimal('NaN'))
4328 'NaN'
4329 >>> c.number_class(Decimal('-NaN'))
4330 'NaN'
4331 >>> c.number_class(Decimal('sNaN'))
4332 'sNaN'
4333 """
4334 return a.number_class(context=self)
4335
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004336 def plus(self, a):
4337 """Plus corresponds to unary prefix plus in Python.
4338
4339 The operation is evaluated using the same rules as add; the
4340 operation plus(a) is calculated as add('0', a) where the '0'
4341 has the same exponent as the operand.
4342
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004343 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004344 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004345 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004346 Decimal("-1.3")
4347 """
4348 return a.__pos__(context=self)
4349
4350 def power(self, a, b, modulo=None):
4351 """Raises a to the power of b, to modulo if given.
4352
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004353 With two arguments, compute a**b. If a is negative then b
4354 must be integral. The result will be inexact unless b is
4355 integral and the result is finite and can be expressed exactly
4356 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004357
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004358 With three arguments, compute (a**b) % modulo. For the
4359 three argument form, the following restrictions on the
4360 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004361
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004362 - all three arguments must be integral
4363 - b must be nonnegative
4364 - at least one of a or b must be nonzero
4365 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004366
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004367 The result of pow(a, b, modulo) is identical to the result
4368 that would be obtained by computing (a**b) % modulo with
4369 unbounded precision, but is computed more efficiently. It is
4370 always exact.
4371
4372 >>> c = ExtendedContext.copy()
4373 >>> c.Emin = -999
4374 >>> c.Emax = 999
4375 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004376 Decimal("8")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004377 >>> c.power(Decimal('-2'), Decimal('3'))
4378 Decimal("-8")
4379 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004380 Decimal("0.125")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004381 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004382 Decimal("69.7575744")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004383 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4384 Decimal("2.00000000")
4385 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004386 Decimal("0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004387 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004388 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004389 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004390 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004391 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004392 Decimal("-0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004393 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004394 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004395 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004396 Decimal("-Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004397 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004398 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004399 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004400 Decimal("NaN")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004401
4402 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4403 Decimal("11")
4404 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4405 Decimal("-11")
4406 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4407 Decimal("1")
4408 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4409 Decimal("11")
4410 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4411 Decimal("11729830")
4412 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4413 Decimal("-0")
4414 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4415 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004416 """
4417 return a.__pow__(b, modulo, context=self)
4418
4419 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004420 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004421
4422 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004423 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004424 exponent is being increased), multiplied by a positive power of ten (if
4425 the exponent is being decreased), or is unchanged (if the exponent is
4426 already equal to that of the right-hand operand).
4427
4428 Unlike other operations, if the length of the coefficient after the
4429 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004430 operation condition is raised. This guarantees that, unless there is
4431 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004432 equal to that of the right-hand operand.
4433
4434 Also unlike other operations, quantize will never raise Underflow, even
4435 if the result is subnormal and inexact.
4436
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004437 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004438 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004439 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004440 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004441 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004442 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004443 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004444 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004445 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004446 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004447 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004448 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004449 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004450 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004451 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004452 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004453 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004454 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004455 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004456 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004457 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004458 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004459 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004460 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004461 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004462 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004463 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004464 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004465 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004466 Decimal("2E+2")
4467 """
4468 return a.quantize(b, context=self)
4469
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004470 def radix(self):
4471 """Just returns 10, as this is Decimal, :)
4472
4473 >>> ExtendedContext.radix()
4474 Decimal("10")
4475 """
4476 return Decimal(10)
4477
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004478 def remainder(self, a, b):
4479 """Returns the remainder from integer division.
4480
4481 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004482 calculating integer division as described for divide-integer, rounded
4483 to precision digits if necessary. The sign of the result, if
4484 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004485
4486 This operation will fail under the same conditions as integer division
4487 (that is, if integer division on the same two operands would fail, the
4488 remainder cannot be calculated).
4489
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004490 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004491 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004492 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004493 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004494 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004495 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004496 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004497 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004498 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004499 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004500 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004501 Decimal("1.0")
4502 """
4503 return a.__mod__(b, context=self)
4504
4505 def remainder_near(self, a, b):
4506 """Returns to be "a - b * n", where n is the integer nearest the exact
4507 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004508 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004509 sign of a.
4510
4511 This operation will fail under the same conditions as integer division
4512 (that is, if integer division on the same two operands would fail, the
4513 remainder cannot be calculated).
4514
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004515 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004516 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004517 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004518 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004519 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004520 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004521 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004522 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004523 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004524 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004525 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004526 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004527 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004528 Decimal("-0.3")
4529 """
4530 return a.remainder_near(b, context=self)
4531
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004532 def rotate(self, a, b):
4533 """Returns a rotated copy of a, b times.
4534
4535 The coefficient of the result is a rotated copy of the digits in
4536 the coefficient of the first operand. The number of places of
4537 rotation is taken from the absolute value of the second operand,
4538 with the rotation being to the left if the second operand is
4539 positive or to the right otherwise.
4540
4541 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4542 Decimal("400000003")
4543 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4544 Decimal("12")
4545 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4546 Decimal("891234567")
4547 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4548 Decimal("123456789")
4549 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4550 Decimal("345678912")
4551 """
4552 return a.rotate(b, context=self)
4553
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004554 def same_quantum(self, a, b):
4555 """Returns True if the two operands have the same exponent.
4556
4557 The result is never affected by either the sign or the coefficient of
4558 either operand.
4559
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004560 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004561 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004562 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004563 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004564 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004565 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004566 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004567 True
4568 """
4569 return a.same_quantum(b)
4570
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004571 def scaleb (self, a, b):
4572 """Returns the first operand after adding the second value its exp.
4573
4574 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4575 Decimal("0.0750")
4576 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4577 Decimal("7.50")
4578 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4579 Decimal("7.50E+3")
4580 """
4581 return a.scaleb (b, context=self)
4582
4583 def shift(self, a, b):
4584 """Returns a shifted copy of a, b times.
4585
4586 The coefficient of the result is a shifted copy of the digits
4587 in the coefficient of the first operand. The number of places
4588 to shift is taken from the absolute value of the second operand,
4589 with the shift being to the left if the second operand is
4590 positive or to the right otherwise. Digits shifted into the
4591 coefficient are zeros.
4592
4593 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4594 Decimal("400000000")
4595 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4596 Decimal("0")
4597 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4598 Decimal("1234567")
4599 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4600 Decimal("123456789")
4601 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4602 Decimal("345678900")
4603 """
4604 return a.shift(b, context=self)
4605
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004606 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004607 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004608
4609 If the result must be inexact, it is rounded using the round-half-even
4610 algorithm.
4611
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004612 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004613 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004614 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004615 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004616 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004617 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004618 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004619 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004620 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004621 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004622 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004623 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004624 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004625 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004626 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004627 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004628 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004629 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004630 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004631 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004632 """
4633 return a.sqrt(context=self)
4634
4635 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004636 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004637
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004638 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004639 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004640 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004641 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004642 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004643 Decimal("-0.77")
4644 """
4645 return a.__sub__(b, context=self)
4646
4647 def to_eng_string(self, a):
4648 """Converts a number to a string, using scientific notation.
4649
4650 The operation is not affected by the context.
4651 """
4652 return a.to_eng_string(context=self)
4653
4654 def to_sci_string(self, a):
4655 """Converts a number to a string, using scientific notation.
4656
4657 The operation is not affected by the context.
4658 """
4659 return a.__str__(context=self)
4660
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004661 def to_integral_exact(self, a):
4662 """Rounds to an integer.
4663
4664 When the operand has a negative exponent, the result is the same
4665 as using the quantize() operation using the given operand as the
4666 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4667 of the operand as the precision setting; Inexact and Rounded flags
4668 are allowed in this operation. The rounding mode is taken from the
4669 context.
4670
4671 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4672 Decimal("2")
4673 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4674 Decimal("100")
4675 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4676 Decimal("100")
4677 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4678 Decimal("102")
4679 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4680 Decimal("-102")
4681 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4682 Decimal("1.0E+6")
4683 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4684 Decimal("7.89E+77")
4685 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4686 Decimal("-Infinity")
4687 """
4688 return a.to_integral_exact(context=self)
4689
4690 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004691 """Rounds to an integer.
4692
4693 When the operand has a negative exponent, the result is the same
4694 as using the quantize() operation using the given operand as the
4695 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4696 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004697 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004698
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004699 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004700 Decimal("2")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004701 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004702 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004703 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004704 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004705 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004706 Decimal("102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004707 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004708 Decimal("-102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004709 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004710 Decimal("1.0E+6")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004711 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004712 Decimal("7.89E+77")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004713 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004714 Decimal("-Infinity")
4715 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004716 return a.to_integral_value(context=self)
4717
4718 # the method name changed, but we provide also the old one, for compatibility
4719 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004720
4721class _WorkRep(object):
4722 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004723 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004724 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004725 # exp: None, int, or string
4726
4727 def __init__(self, value=None):
4728 if value is None:
4729 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004730 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004731 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004732 elif isinstance(value, Decimal):
4733 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00004734 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004735 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004736 else:
4737 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004738 self.sign = value[0]
4739 self.int = value[1]
4740 self.exp = value[2]
4741
4742 def __repr__(self):
4743 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4744
4745 __str__ = __repr__
4746
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004747
4748
4749def _normalize(op1, op2, shouldround = 0, prec = 0):
4750 """Normalizes op1, op2 to have the same exp and length of coefficient.
4751
4752 Done during addition.
4753 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004754 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004755 tmp = op2
4756 other = op1
4757 else:
4758 tmp = op1
4759 other = op2
4760
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004761 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4762 # Then adding 10**exp to tmp has the same effect (after rounding)
4763 # as adding any positive quantity smaller than 10**exp; similarly
4764 # for subtraction. So if other is smaller than 10**exp we replace
4765 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4766 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004767 tmp_len = len(str(tmp.int))
4768 other_len = len(str(other.int))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004769 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4770 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004771 other.int = 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004772 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004773
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004774 tmp.int *= 10 ** (tmp.exp - other.exp)
4775 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004776 return op1, op2
4777
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004778##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004779
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004780# This function from Tim Peters was taken from here:
4781# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4782# The correction being in the function definition is for speed, and
4783# the whole function is not resolved with math.log because of avoiding
4784# the use of floats.
4785def _nbits(n, correction = {
4786 '0': 4, '1': 3, '2': 2, '3': 2,
4787 '4': 1, '5': 1, '6': 1, '7': 1,
4788 '8': 0, '9': 0, 'a': 0, 'b': 0,
4789 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4790 """Number of bits in binary representation of the positive integer n,
4791 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004792 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004793 if n < 0:
4794 raise ValueError("The argument to _nbits should be nonnegative.")
4795 hex_n = "%x" % n
4796 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004797
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004798def _sqrt_nearest(n, a):
4799 """Closest integer to the square root of the positive integer n. a is
4800 an initial approximation to the square root. Any positive integer
4801 will do for a, but the closer a is to the square root of n the
4802 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004803
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004804 """
4805 if n <= 0 or a <= 0:
4806 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4807
4808 b=0
4809 while a != b:
4810 b, a = a, a--n//a>>1
4811 return a
4812
4813def _rshift_nearest(x, shift):
4814 """Given an integer x and a nonnegative integer shift, return closest
4815 integer to x / 2**shift; use round-to-even in case of a tie.
4816
4817 """
4818 b, q = 1 << shift, x >> shift
4819 return q + (2*(x & (b-1)) + (q&1) > b)
4820
4821def _div_nearest(a, b):
4822 """Closest integer to a/b, a and b positive integers; rounds to even
4823 in the case of a tie.
4824
4825 """
4826 q, r = divmod(a, b)
4827 return q + (2*r + (q&1) > b)
4828
4829def _ilog(x, M, L = 8):
4830 """Integer approximation to M*log(x/M), with absolute error boundable
4831 in terms only of x/M.
4832
4833 Given positive integers x and M, return an integer approximation to
4834 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4835 between the approximation and the exact result is at most 22. For
4836 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4837 both cases these are upper bounds on the error; it will usually be
4838 much smaller."""
4839
4840 # The basic algorithm is the following: let log1p be the function
4841 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4842 # the reduction
4843 #
4844 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4845 #
4846 # repeatedly until the argument to log1p is small (< 2**-L in
4847 # absolute value). For small y we can use the Taylor series
4848 # expansion
4849 #
4850 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4851 #
4852 # truncating at T such that y**T is small enough. The whole
4853 # computation is carried out in a form of fixed-point arithmetic,
4854 # with a real number z being represented by an integer
4855 # approximation to z*M. To avoid loss of precision, the y below
4856 # is actually an integer approximation to 2**R*y*M, where R is the
4857 # number of reductions performed so far.
4858
4859 y = x-M
4860 # argument reduction; R = number of reductions performed
4861 R = 0
4862 while (R <= L and abs(y) << L-R >= M or
4863 R > L and abs(y) >> R-L >= M):
4864 y = _div_nearest((M*y) << 1,
4865 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4866 R += 1
4867
4868 # Taylor series with T terms
4869 T = -int(-10*len(str(M))//(3*L))
4870 yshift = _rshift_nearest(y, R)
4871 w = _div_nearest(M, T)
4872 for k in range(T-1, 0, -1):
4873 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4874
4875 return _div_nearest(w*y, M)
4876
4877def _dlog10(c, e, p):
4878 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4879 approximation to 10**p * log10(c*10**e), with an absolute error of
4880 at most 1. Assumes that c*10**e is not exactly 1."""
4881
4882 # increase precision by 2; compensate for this by dividing
4883 # final result by 100
4884 p += 2
4885
4886 # write c*10**e as d*10**f with either:
4887 # f >= 0 and 1 <= d <= 10, or
4888 # f <= 0 and 0.1 <= d <= 1.
4889 # Thus for c*10**e close to 1, f = 0
4890 l = len(str(c))
4891 f = e+l - (e+l >= 1)
4892
4893 if p > 0:
4894 M = 10**p
4895 k = e+p-f
4896 if k >= 0:
4897 c *= 10**k
4898 else:
4899 c = _div_nearest(c, 10**-k)
4900
4901 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004902 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004903 log_d = _div_nearest(log_d*M, log_10)
4904 log_tenpower = f*M # exact
4905 else:
4906 log_d = 0 # error < 2.31
4907 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4908
4909 return _div_nearest(log_tenpower+log_d, 100)
4910
4911def _dlog(c, e, p):
4912 """Given integers c, e and p with c > 0, compute an integer
4913 approximation to 10**p * log(c*10**e), with an absolute error of
4914 at most 1. Assumes that c*10**e is not exactly 1."""
4915
4916 # Increase precision by 2. The precision increase is compensated
4917 # for at the end with a division by 100.
4918 p += 2
4919
4920 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4921 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4922 # as 10**p * log(d) + 10**p*f * log(10).
4923 l = len(str(c))
4924 f = e+l - (e+l >= 1)
4925
4926 # compute approximation to 10**p*log(d), with error < 27
4927 if p > 0:
4928 k = e+p-f
4929 if k >= 0:
4930 c *= 10**k
4931 else:
4932 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4933
4934 # _ilog magnifies existing error in c by a factor of at most 10
4935 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4936 else:
4937 # p <= 0: just approximate the whole thing by 0; error < 2.31
4938 log_d = 0
4939
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004940 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004941 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004942 extra = len(str(abs(f)))-1
4943 if p + extra >= 0:
4944 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4945 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4946 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004947 else:
4948 f_log_ten = 0
4949 else:
4950 f_log_ten = 0
4951
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004952 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004953 return _div_nearest(f_log_ten + log_d, 100)
4954
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004955class _Log10Memoize(object):
4956 """Class to compute, store, and allow retrieval of, digits of the
4957 constant log(10) = 2.302585.... This constant is needed by
4958 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4959 def __init__(self):
4960 self.digits = "23025850929940456840179914546843642076011014886"
4961
4962 def getdigits(self, p):
4963 """Given an integer p >= 0, return floor(10**p)*log(10).
4964
4965 For example, self.getdigits(3) returns 2302.
4966 """
4967 # digits are stored as a string, for quick conversion to
4968 # integer in the case that we've already computed enough
4969 # digits; the stored digits should always be correct
4970 # (truncated, not rounded to nearest).
4971 if p < 0:
4972 raise ValueError("p should be nonnegative")
4973
4974 if p >= len(self.digits):
4975 # compute p+3, p+6, p+9, ... digits; continue until at
4976 # least one of the extra digits is nonzero
4977 extra = 3
4978 while True:
4979 # compute p+extra digits, correct to within 1ulp
4980 M = 10**(p+extra+2)
4981 digits = str(_div_nearest(_ilog(10*M, M), 100))
4982 if digits[-extra:] != '0'*extra:
4983 break
4984 extra += 3
4985 # keep all reliable digits so far; remove trailing zeros
4986 # and next nonzero digit
4987 self.digits = digits.rstrip('0')[:-1]
4988 return int(self.digits[:p+1])
4989
4990_log10_digits = _Log10Memoize().getdigits
4991
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004992def _iexp(x, M, L=8):
4993 """Given integers x and M, M > 0, such that x/M is small in absolute
4994 value, compute an integer approximation to M*exp(x/M). For 0 <=
4995 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4996 is usually much smaller)."""
4997
4998 # Algorithm: to compute exp(z) for a real number z, first divide z
4999 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5000 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5001 # series
5002 #
5003 # expm1(x) = x + x**2/2! + x**3/3! + ...
5004 #
5005 # Now use the identity
5006 #
5007 # expm1(2x) = expm1(x)*(expm1(x)+2)
5008 #
5009 # R times to compute the sequence expm1(z/2**R),
5010 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5011
5012 # Find R such that x/2**R/M <= 2**-L
5013 R = _nbits((x<<L)//M)
5014
5015 # Taylor series. (2**L)**T > M
5016 T = -int(-10*len(str(M))//(3*L))
5017 y = _div_nearest(x, T)
5018 Mshift = M<<R
5019 for i in range(T-1, 0, -1):
5020 y = _div_nearest(x*(Mshift + y), Mshift * i)
5021
5022 # Expansion
5023 for k in range(R-1, -1, -1):
5024 Mshift = M<<(k+2)
5025 y = _div_nearest(y*(y+Mshift), Mshift)
5026
5027 return M+y
5028
5029def _dexp(c, e, p):
5030 """Compute an approximation to exp(c*10**e), with p decimal places of
5031 precision.
5032
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005033 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005034
5035 10**(p-1) <= d <= 10**p, and
5036 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5037
5038 In other words, d*10**f is an approximation to exp(c*10**e) with p
5039 digits of precision, and with an error in d of at most 1. This is
5040 almost, but not quite, the same as the error being < 1ulp: when d
5041 = 10**(p-1) the error could be up to 10 ulp."""
5042
5043 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5044 p += 2
5045
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005046 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005047 extra = max(0, e + len(str(c)) - 1)
5048 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005049
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005050 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005051 # rounding down
5052 shift = e+q
5053 if shift >= 0:
5054 cshift = c*10**shift
5055 else:
5056 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005057 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005058
5059 # reduce remainder back to original precision
5060 rem = _div_nearest(rem, 10**extra)
5061
5062 # error in result of _iexp < 120; error after division < 0.62
5063 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5064
5065def _dpower(xc, xe, yc, ye, p):
5066 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5067 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5068
5069 10**(p-1) <= c <= 10**p, and
5070 (c-1)*10**e < x**y < (c+1)*10**e
5071
5072 in other words, c*10**e is an approximation to x**y with p digits
5073 of precision, and with an error in c of at most 1. (This is
5074 almost, but not quite, the same as the error being < 1ulp: when c
5075 == 10**(p-1) we can only guarantee error < 10ulp.)
5076
5077 We assume that: x is positive and not equal to 1, and y is nonzero.
5078 """
5079
5080 # Find b such that 10**(b-1) <= |y| <= 10**b
5081 b = len(str(abs(yc))) + ye
5082
5083 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5084 lxc = _dlog(xc, xe, p+b+1)
5085
5086 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5087 shift = ye-b
5088 if shift >= 0:
5089 pc = lxc*yc*10**shift
5090 else:
5091 pc = _div_nearest(lxc*yc, 10**-shift)
5092
5093 if pc == 0:
5094 # we prefer a result that isn't exactly 1; this makes it
5095 # easier to compute a correctly rounded result in __pow__
5096 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5097 coeff, exp = 10**(p-1)+1, 1-p
5098 else:
5099 coeff, exp = 10**p-1, -p
5100 else:
5101 coeff, exp = _dexp(pc, -(p+1), p+1)
5102 coeff = _div_nearest(coeff, 10)
5103 exp += 1
5104
5105 return coeff, exp
5106
5107def _log10_lb(c, correction = {
5108 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5109 '6': 23, '7': 16, '8': 10, '9': 5}):
5110 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5111 if c <= 0:
5112 raise ValueError("The argument to _log10_lb should be nonnegative.")
5113 str_c = str(c)
5114 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005115
Guido van Rossumd8faa362007-04-27 19:54:29 +00005116##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005117
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005118def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005119 """Convert other to Decimal.
5120
5121 Verifies that it's ok to use in an implicit construction.
5122 """
5123 if isinstance(other, Decimal):
5124 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005125 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005126 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005127 if raiseit:
5128 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005129 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005130
Guido van Rossumd8faa362007-04-27 19:54:29 +00005131##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005132
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005133# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005134# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005135
5136DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005137 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005138 traps=[DivisionByZero, Overflow, InvalidOperation],
5139 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005140 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005141 Emax=999999999,
5142 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005143 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005144)
5145
5146# Pre-made alternate contexts offered by the specification
5147# Don't change these; the user should be able to select these
5148# contexts and be able to reproduce results from other implementations
5149# of the spec.
5150
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005151BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005152 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005153 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5154 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005155)
5156
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005157ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005158 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005159 traps=[],
5160 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005161)
5162
5163
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005164##### crud for parsing strings #############################################
5165import re
5166
5167# Regular expression used for parsing numeric strings. Additional
5168# comments:
5169#
5170# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5171# whitespace. But note that the specification disallows whitespace in
5172# a numeric string.
5173#
5174# 2. For finite numbers (not infinities and NaNs) the body of the
5175# number between the optional sign and the optional exponent must have
5176# at least one decimal digit, possibly after the decimal point. The
5177# lookahead expression '(?=\d|\.\d)' checks this.
5178#
5179# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5180# other meaning for \d than the numbers [0-9].
5181
5182import re
5183_parser = re.compile(r""" # A numeric string consists of:
5184# \s*
5185 (?P<sign>[-+])? # an optional sign, followed by either...
5186 (
5187 (?=\d|\.\d) # ...a number (with at least one digit)
5188 (?P<int>\d*) # consisting of a (possibly empty) integer part
5189 (\.(?P<frac>\d*))? # followed by an optional fractional part
5190 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5191 |
5192 Inf(inity)? # ...an infinity, or...
5193 |
5194 (?P<signal>s)? # ...an (optionally signaling)
5195 NaN # NaN
5196 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5197 )
5198# \s*
5199 $
5200""", re.VERBOSE | re.IGNORECASE).match
5201
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005202_all_zeros = re.compile('0*$').match
5203_exact_half = re.compile('50*$').match
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005204del re
5205
5206
Guido van Rossumd8faa362007-04-27 19:54:29 +00005207##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005208
Guido van Rossumd8faa362007-04-27 19:54:29 +00005209# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005210Inf = Decimal('Inf')
5211negInf = Decimal('-Inf')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005212NaN = Decimal('NaN')
5213Dec_0 = Decimal(0)
5214Dec_p1 = Decimal(1)
5215Dec_n1 = Decimal(-1)
5216Dec_p2 = Decimal(2)
5217Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005218
Guido van Rossumd8faa362007-04-27 19:54:29 +00005219# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005220Infsign = (Inf, negInf)
5221
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005222
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005223
5224if __name__ == '__main__':
5225 import doctest, sys
5226 doctest.testmod(sys.modules[__name__])