blob: 7842cb25071358494ed6f6156c84b7f14e4f0688 [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)
543 self._is_special = False
544
545 # From an internal working value
546 if isinstance(value, _WorkRep):
Raymond Hettinger17931de2004-10-27 06:21:46 +0000547 self._sign = value.sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000548 self._int = str(value.int)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000549 self._exp = int(value.exp)
550 return self
551
552 # From another decimal
553 if isinstance(value, Decimal):
554 self._exp = value._exp
555 self._sign = value._sign
556 self._int = value._int
557 self._is_special = value._is_special
558 return self
559
560 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000561 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000562 if value >= 0:
563 self._sign = 0
564 else:
565 self._sign = 1
566 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000567 self._int = str(abs(value))
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000568 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000569
570 # tuple/list conversion (possibly from as_tuple())
571 if isinstance(value, (list,tuple)):
572 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000573 raise ValueError('Invalid tuple size in creation of Decimal '
574 'from list or tuple. The list or tuple '
575 'should have exactly three elements.')
576 # process sign. The isinstance test rejects floats
577 if not (isinstance(value[0], int) and value[0] in (0,1)):
578 raise ValueError("Invalid sign. The first value in the tuple "
579 "should be an integer; either 0 for a "
580 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000581 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000582 if value[2] == 'F':
583 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000584 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000585 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000586 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000587 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000588 # process and validate the digits in value[1]
589 digits = []
590 for digit in value[1]:
591 if isinstance(digit, int) and 0 <= digit <= 9:
592 # skip leading zeros
593 if digits or digit != 0:
594 digits.append(digit)
595 else:
596 raise ValueError("The second value in the tuple must "
597 "be composed of integers in the range "
598 "0 through 9.")
599 if value[2] in ('n', 'N'):
600 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000601 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000602 self._exp = value[2]
603 self._is_special = True
604 elif isinstance(value[2], int):
605 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000606 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000607 self._exp = value[2]
608 self._is_special = False
609 else:
610 raise ValueError("The third value in the tuple must "
611 "be an integer, or one of the "
612 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000613 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000614
Raymond Hettingerbf440692004-07-10 14:14:37 +0000615 if isinstance(value, float):
616 raise TypeError("Cannot convert float to Decimal. " +
617 "First convert the float to a string")
618
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000619 # From a string
620 # REs insist on real strings, so we can too.
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000621 if isinstance(value, str):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000622 m = _parser(value)
623 if m is None:
624 if context is None:
625 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000626 return context._raise_error(ConversionSyntax,
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000627 "Invalid literal for Decimal: %r" % value)
628
629 if m.group('sign') == "-":
630 self._sign = 1
631 else:
632 self._sign = 0
633 intpart = m.group('int')
634 if intpart is not None:
635 # finite number
636 fracpart = m.group('frac')
637 exp = int(m.group('exp') or '0')
638 if fracpart is not None:
639 self._int = (intpart+fracpart).lstrip('0') or '0'
640 self._exp = exp - len(fracpart)
641 else:
642 self._int = intpart.lstrip('0') or '0'
643 self._exp = exp
644 self._is_special = False
645 else:
646 diag = m.group('diag')
647 if diag is not None:
648 # NaN
649 self._int = diag.lstrip('0')
650 if m.group('signal'):
651 self._exp = 'N'
652 else:
653 self._exp = 'n'
654 else:
655 # infinity
656 self._int = '0'
657 self._exp = 'F'
658 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000659 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000660
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000661 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000662
663 def _isnan(self):
664 """Returns whether the number is not actually one.
665
666 0 if a number
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000667 1 if NaN (it could be a normal quiet NaN or a phantom one)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000668 2 if sNaN
669 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000670 if self._is_special:
671 exp = self._exp
672 if exp == 'n':
673 return 1
674 elif exp == 'N':
675 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000676 return 0
677
678 def _isinfinity(self):
679 """Returns whether the number is infinite
680
681 0 if finite or not a number
682 1 if +INF
683 -1 if -INF
684 """
685 if self._exp == 'F':
686 if self._sign:
687 return -1
688 return 1
689 return 0
690
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000691 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000692 """Returns whether the number is not actually one.
693
694 if self, other are sNaN, signal
695 if self, other are NaN return nan
696 return 0
697
698 Done before operations.
699 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000700
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000701 self_is_nan = self._isnan()
702 if other is None:
703 other_is_nan = False
704 else:
705 other_is_nan = other._isnan()
706
707 if self_is_nan or other_is_nan:
708 if context is None:
709 context = getcontext()
710
711 if self_is_nan == 2:
712 return context._raise_error(InvalidOperation, 'sNaN',
713 1, self)
714 if other_is_nan == 2:
715 return context._raise_error(InvalidOperation, 'sNaN',
716 1, other)
717 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000718 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000719
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000720 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000721 return 0
722
Jack Diederich4dafcc42006-11-28 19:15:13 +0000723 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000724 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000725
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000726 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000727 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000728 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000729
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000730 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000731 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000732 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000733 # Never return NotImplemented
734 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000735
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000736 if self._is_special or other._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000737 # check for nans, without raising on a signaling nan
738 if self._isnan() or other._isnan():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000739 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000740
741 # INF = INF
742 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000743
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000744 # check for zeros; note that cmp(0, -0) should return 0
745 if not self:
746 if not other:
747 return 0
748 else:
749 return -((-1)**other._sign)
750 if not other:
751 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000752
Guido van Rossumd8faa362007-04-27 19:54:29 +0000753 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000754 if other._sign < self._sign:
755 return -1
756 if self._sign < other._sign:
757 return 1
758
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000759 self_adjusted = self.adjusted()
760 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000761 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000762 self_padded = self._int + '0'*(self._exp - other._exp)
763 other_padded = other._int + '0'*(other._exp - self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000764 return cmp(self_padded, other_padded) * (-1)**self._sign
765 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000766 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000767 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000768 return -((-1)**self._sign)
769
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000770 def __eq__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000771 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000772 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000773 return self.__cmp__(other) == 0
774
775 def __ne__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000776 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000777 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000778 return self.__cmp__(other) != 0
779
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000780 def __lt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000781 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000782 return NotImplemented
783 return self.__cmp__(other) < 0
784
785 def __le__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000786 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000787 return NotImplemented
788 return self.__cmp__(other) <= 0
789
790 def __gt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000791 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000792 return NotImplemented
793 return self.__cmp__(other) > 0
794
795 def __ge__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000796 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000797 return NotImplemented
798 return self.__cmp__(other) >= 0
799
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000800 def compare(self, other, context=None):
801 """Compares one to another.
802
803 -1 => a < b
804 0 => a = b
805 1 => a > b
806 NaN => one is NaN
807 Like __cmp__, but returns Decimal instances.
808 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000809 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000810
Guido van Rossumd8faa362007-04-27 19:54:29 +0000811 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000812 if (self._is_special or other and other._is_special):
813 ans = self._check_nans(other, context)
814 if ans:
815 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000816
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000817 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000818
819 def __hash__(self):
820 """x.__hash__() <==> hash(x)"""
821 # Decimal integers must hash the same as the ints
822 # Non-integer decimals are normalized and hashed as strings
Thomas Wouters477c8d52006-05-27 19:21:47 +0000823 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000824 if self._is_special:
825 if self._isnan():
826 raise TypeError('Cannot hash a NaN value.')
827 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000828 if not self:
829 return 0
830 if self._isinteger():
831 op = _WorkRep(self.to_integral_value())
832 # to make computation feasible for Decimals with large
833 # exponent, we use the fact that hash(n) == hash(m) for
834 # any two nonzero integers n and m such that (i) n and m
835 # have the same sign, and (ii) n is congruent to m modulo
836 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
837 # hash((-1)**s*c*pow(10, e, 2**64-1).
838 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000839 return hash(str(self.normalize()))
840
841 def as_tuple(self):
842 """Represents the number as a triple tuple.
843
844 To show the internals exactly as they are.
845 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000846 return (self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000847
848 def __repr__(self):
849 """Represents the number as an instance of Decimal."""
850 # Invariant: eval(repr(d)) == d
851 return 'Decimal("%s")' % str(self)
852
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000853 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000854 """Return string representation of the number in scientific notation.
855
856 Captures all of the information in the underlying representation.
857 """
858
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000859 if self._is_special:
860 if self._isnan():
861 minus = '-'*self._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000862 if self._int == '0':
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000863 info = ''
864 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000865 info = self._int
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000866 if self._isnan() == 2:
867 return minus + 'sNaN' + info
868 return minus + 'NaN' + info
869 if self._isinfinity():
870 minus = '-'*self._sign
871 return minus + 'Infinity'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000872
873 if context is None:
874 context = getcontext()
875
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000876 tmp = list(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000877 numdigits = len(self._int)
878 leftdigits = self._exp + numdigits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000879 if eng and not self: # self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
880 if self._exp < 0 and self._exp >= -6: # short, no need for e/E
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000881 s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
882 return s
Guido van Rossumd8faa362007-04-27 19:54:29 +0000883 # exp is closest mult. of 3 >= self._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000884 exp = ((self._exp - 1)// 3 + 1) * 3
885 if exp != self._exp:
886 s = '0.'+'0'*(exp - self._exp)
887 else:
888 s = '0'
889 if exp != 0:
890 if context.capitals:
891 s += 'E'
892 else:
893 s += 'e'
894 if exp > 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000895 s += '+' # 0.0e+3, not 0.0e3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000896 s += str(exp)
897 s = '-'*self._sign + s
898 return s
899 if eng:
900 dotplace = (leftdigits-1)%3+1
901 adjexp = leftdigits -1 - (leftdigits-1)%3
902 else:
903 adjexp = leftdigits-1
904 dotplace = 1
905 if self._exp == 0:
906 pass
907 elif self._exp < 0 and adjexp >= 0:
908 tmp.insert(leftdigits, '.')
909 elif self._exp < 0 and adjexp >= -6:
910 tmp[0:0] = ['0'] * int(-leftdigits)
911 tmp.insert(0, '0.')
912 else:
913 if numdigits > dotplace:
914 tmp.insert(dotplace, '.')
915 elif numdigits < dotplace:
916 tmp.extend(['0']*(dotplace-numdigits))
917 if adjexp:
918 if not context.capitals:
919 tmp.append('e')
920 else:
921 tmp.append('E')
922 if adjexp > 0:
923 tmp.append('+')
924 tmp.append(str(adjexp))
925 if eng:
926 while tmp[0:1] == ['0']:
927 tmp[0:1] = []
928 if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
929 tmp[0:0] = ['0']
930 if self._sign:
931 tmp.insert(0, '-')
932
933 return ''.join(tmp)
934
935 def to_eng_string(self, context=None):
936 """Convert to engineering-type string.
937
938 Engineering notation has an exponent which is a multiple of 3, so there
939 are up to 3 digits left of the decimal place.
940
941 Same rules for when in exponential and when as a value as in __str__.
942 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000943 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000944
945 def __neg__(self, context=None):
946 """Returns a copy with the sign switched.
947
948 Rounds, if it has reason.
949 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000950 if self._is_special:
951 ans = self._check_nans(context=context)
952 if ans:
953 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000954
955 if not self:
956 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000957 ans = self.copy_sign(Dec_0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000958 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000959 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000960
961 if context is None:
962 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000963 if context._rounding_decision == ALWAYS_ROUND:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000964 return ans._fix(context)
965 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000966
967 def __pos__(self, context=None):
968 """Returns a copy, unless it is a sNaN.
969
970 Rounds the number (if more then precision digits)
971 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000972 if self._is_special:
973 ans = self._check_nans(context=context)
974 if ans:
975 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000976
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000977 if not self:
978 # + (-0) = 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000979 ans = self.copy_sign(Dec_0)
980 else:
981 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000982
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000983 if context is None:
984 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000985 if context._rounding_decision == ALWAYS_ROUND:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000986 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000987 return ans
988
989 def __abs__(self, round=1, context=None):
990 """Returns the absolute value of self.
991
992 If the second argument is 0, do not round.
993 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000994 if self._is_special:
995 ans = self._check_nans(context=context)
996 if ans:
997 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000998
999 if not round:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001000 if context is None:
1001 context = getcontext()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00001002 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001003 context._set_rounding_decision(NEVER_ROUND)
1004
1005 if self._sign:
1006 ans = self.__neg__(context=context)
1007 else:
1008 ans = self.__pos__(context=context)
1009
1010 return ans
1011
1012 def __add__(self, other, context=None):
1013 """Returns self + other.
1014
1015 -INF + INF (or the reverse) cause InvalidOperation errors.
1016 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001017 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001018 if other is NotImplemented:
1019 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001020
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001021 if context is None:
1022 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001023
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001024 if self._is_special or other._is_special:
1025 ans = self._check_nans(other, context)
1026 if ans:
1027 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001028
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001029 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001030 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001031 if self._sign != other._sign and other._isinfinity():
1032 return context._raise_error(InvalidOperation, '-INF + INF')
1033 return Decimal(self)
1034 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001035 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001036
1037 shouldround = context._rounding_decision == ALWAYS_ROUND
1038
1039 exp = min(self._exp, other._exp)
1040 negativezero = 0
1041 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001042 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001043 negativezero = 1
1044
1045 if not self and not other:
1046 sign = min(self._sign, other._sign)
1047 if negativezero:
1048 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001049 ans = _dec_from_triple(sign, '0', exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001050 if shouldround:
1051 ans = ans._fix(context)
1052 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001053 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001054 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001055 ans = other._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001056 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001057 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001058 return ans
1059 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001060 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001061 ans = self._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001062 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001063 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001064 return ans
1065
1066 op1 = _WorkRep(self)
1067 op2 = _WorkRep(other)
1068 op1, op2 = _normalize(op1, op2, shouldround, context.prec)
1069
1070 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001071 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001072 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001073 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001074 ans = _dec_from_triple(negativezero, '0', exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001075 if shouldround:
1076 ans = ans._fix(context)
1077 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001078 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001079 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001080 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001081 if op1.sign == 1:
1082 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001083 op1.sign, op2.sign = op2.sign, op1.sign
1084 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001085 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001086 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001087 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001088 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001089 op1.sign, op2.sign = (0, 0)
1090 else:
1091 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001092 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001093
Raymond Hettinger17931de2004-10-27 06:21:46 +00001094 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001095 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001096 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001097 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001098
1099 result.exp = op1.exp
1100 ans = Decimal(result)
1101 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001102 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001103 return ans
1104
1105 __radd__ = __add__
1106
1107 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001108 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001109 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001110 if other is NotImplemented:
1111 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001112
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001113 if self._is_special or other._is_special:
1114 ans = self._check_nans(other, context=context)
1115 if ans:
1116 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001117
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001118 # self - other is computed as self + other.copy_negate()
1119 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001120
1121 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001122 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001123 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001124 if other is NotImplemented:
1125 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001126
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001127 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001128
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001129 def _increment(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001130 """Special case of add, adding 1eExponent
1131
1132 Since it is common, (rounding, for example) this adds
1133 (sign)*one E self._exp to the number more efficiently than add.
1134
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001135 Assumes that self is nonspecial.
1136
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001137 For example:
1138 Decimal('5.624e10')._increment() == Decimal('5.625e10')
1139 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001140 L = list(map(int, self._int))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141 L[-1] += 1
1142 spot = len(L)-1
1143 while L[spot] == 10:
1144 L[spot] = 0
1145 if spot == 0:
1146 L[0:0] = [1]
1147 break
1148 L[spot-1] += 1
1149 spot -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001150 return _dec_from_triple(self._sign, "".join(map(str, L)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001151
1152 def __mul__(self, other, context=None):
1153 """Return self * other.
1154
1155 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1156 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001157 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001158 if other is NotImplemented:
1159 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001160
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001161 if context is None:
1162 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001163
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001164 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001165
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001166 if self._is_special or other._is_special:
1167 ans = self._check_nans(other, context)
1168 if ans:
1169 return ans
1170
1171 if self._isinfinity():
1172 if not other:
1173 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1174 return Infsign[resultsign]
1175
1176 if other._isinfinity():
1177 if not self:
1178 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1179 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001180
1181 resultexp = self._exp + other._exp
1182 shouldround = context._rounding_decision == ALWAYS_ROUND
1183
1184 # Special case for multiplying by zero
1185 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001186 ans = _dec_from_triple(resultsign, '0', resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001187 if shouldround:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001188 # Fixing in case the exponent is out of bounds
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001189 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001190 return ans
1191
1192 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001193 if self._int == '1':
1194 ans = _dec_from_triple(resultsign, other._int, resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001195 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001196 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001197 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001198 if other._int == '1':
1199 ans = _dec_from_triple(resultsign, self._int, resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001200 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001201 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001202 return ans
1203
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001204 op1 = _WorkRep(self)
1205 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001206
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001207 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001208 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001209 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001210
1211 return ans
1212 __rmul__ = __mul__
1213
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001214 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001215 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001216 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001217 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001218 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001219
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001220 if context is None:
1221 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001222
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001223 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001224
1225 if self._is_special or other._is_special:
1226 ans = self._check_nans(other, context)
1227 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001228 return ans
1229
1230 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001231 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001232
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001233 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001234 return Infsign[sign]
1235
1236 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001237 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001238 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001239
1240 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001241 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001242 if not self:
1243 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001244 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001245
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001246 if not self:
1247 exp = self._exp - other._exp
1248 coeff = 0
1249 else:
1250 # OK, so neither = 0, INF or NaN
1251 shift = len(other._int) - len(self._int) + context.prec + 1
1252 exp = self._exp - other._exp - shift
1253 op1 = _WorkRep(self)
1254 op2 = _WorkRep(other)
1255 if shift >= 0:
1256 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1257 else:
1258 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1259 if remainder:
1260 # result is not exact; adjust to ensure correct rounding
1261 if coeff % 5 == 0:
1262 coeff += 1
1263 else:
1264 # result is exact; get as close to ideal exponent as possible
1265 ideal_exp = self._exp - other._exp
1266 while exp < ideal_exp and coeff % 10 == 0:
1267 coeff //= 10
1268 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001269
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001270 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001271 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001272
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001273 def _divide(self, other, context):
1274 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001275
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001276 Assumes that neither self nor other is a NaN, that self is not
1277 infinite and that other is nonzero.
1278 """
1279 sign = self._sign ^ other._sign
1280 if other._isinfinity():
1281 ideal_exp = self._exp
1282 else:
1283 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001284
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001285 expdiff = self.adjusted() - other.adjusted()
1286 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001287 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001288 self._rescale(ideal_exp, context.rounding))
1289 if expdiff <= context.prec:
1290 op1 = _WorkRep(self)
1291 op2 = _WorkRep(other)
1292 if op1.exp >= op2.exp:
1293 op1.int *= 10**(op1.exp - op2.exp)
1294 else:
1295 op2.int *= 10**(op2.exp - op1.exp)
1296 q, r = divmod(op1.int, op2.int)
1297 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001298 return (_dec_from_triple(sign, str(q), 0),
1299 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001300
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001301 # Here the quotient is too large to be representable
1302 ans = context._raise_error(DivisionImpossible,
1303 'quotient too large in //, % or divmod')
1304 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001305
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001306 def __rtruediv__(self, other, context=None):
1307 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001308 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001309 if other is NotImplemented:
1310 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001311 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001312
1313 def __divmod__(self, other, context=None):
1314 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001315 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001316 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001317 other = _convert_other(other)
1318 if other is NotImplemented:
1319 return other
1320
1321 if context is None:
1322 context = getcontext()
1323
1324 ans = self._check_nans(other, context)
1325 if ans:
1326 return (ans, ans)
1327
1328 sign = self._sign ^ other._sign
1329 if self._isinfinity():
1330 if other._isinfinity():
1331 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1332 return ans, ans
1333 else:
1334 return (Infsign[sign],
1335 context._raise_error(InvalidOperation, 'INF % x'))
1336
1337 if not other:
1338 if not self:
1339 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1340 return ans, ans
1341 else:
1342 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1343 context._raise_error(InvalidOperation, 'x % 0'))
1344
1345 quotient, remainder = self._divide(other, context)
1346 if context._rounding_decision == ALWAYS_ROUND:
1347 remainder = remainder._fix(context)
1348 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001349
1350 def __rdivmod__(self, other, context=None):
1351 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001352 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001353 if other is NotImplemented:
1354 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001355 return other.__divmod__(self, context=context)
1356
1357 def __mod__(self, other, context=None):
1358 """
1359 self % other
1360 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001361 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001362 if other is NotImplemented:
1363 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001364
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001365 if context is None:
1366 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001367
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001368 ans = self._check_nans(other, context)
1369 if ans:
1370 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001371
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001372 if self._isinfinity():
1373 return context._raise_error(InvalidOperation, 'INF % x')
1374 elif not other:
1375 if self:
1376 return context._raise_error(InvalidOperation, 'x % 0')
1377 else:
1378 return context._raise_error(DivisionUndefined, '0 % 0')
1379
1380 remainder = self._divide(other, context)[1]
1381 if context._rounding_decision == ALWAYS_ROUND:
1382 remainder = remainder._fix(context)
1383 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001384
1385 def __rmod__(self, other, context=None):
1386 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001387 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001388 if other is NotImplemented:
1389 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001390 return other.__mod__(self, context=context)
1391
1392 def remainder_near(self, other, context=None):
1393 """
1394 Remainder nearest to 0- abs(remainder-near) <= other/2
1395 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001396 if context is None:
1397 context = getcontext()
1398
1399 other = _convert_other(other, raiseit=True)
1400
1401 ans = self._check_nans(other, context)
1402 if ans:
1403 return ans
1404
1405 # self == +/-infinity -> InvalidOperation
1406 if self._isinfinity():
1407 return context._raise_error(InvalidOperation,
1408 'remainder_near(infinity, x)')
1409
1410 # other == 0 -> either InvalidOperation or DivisionUndefined
1411 if not other:
1412 if self:
1413 return context._raise_error(InvalidOperation,
1414 'remainder_near(x, 0)')
1415 else:
1416 return context._raise_error(DivisionUndefined,
1417 'remainder_near(0, 0)')
1418
1419 # other = +/-infinity -> remainder = self
1420 if other._isinfinity():
1421 ans = Decimal(self)
1422 return ans._fix(context)
1423
1424 # self = 0 -> remainder = self, with ideal exponent
1425 ideal_exponent = min(self._exp, other._exp)
1426 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001427 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001428 return ans._fix(context)
1429
1430 # catch most cases of large or small quotient
1431 expdiff = self.adjusted() - other.adjusted()
1432 if expdiff >= context.prec + 1:
1433 # expdiff >= prec+1 => abs(self/other) > 10**prec
1434 return context._raise_error(DivisionImpossible)
1435 if expdiff <= -2:
1436 # expdiff <= -2 => abs(self/other) < 0.1
1437 ans = self._rescale(ideal_exponent, context.rounding)
1438 return ans._fix(context)
1439
1440 # adjust both arguments to have the same exponent, then divide
1441 op1 = _WorkRep(self)
1442 op2 = _WorkRep(other)
1443 if op1.exp >= op2.exp:
1444 op1.int *= 10**(op1.exp - op2.exp)
1445 else:
1446 op2.int *= 10**(op2.exp - op1.exp)
1447 q, r = divmod(op1.int, op2.int)
1448 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1449 # 10**ideal_exponent. Apply correction to ensure that
1450 # abs(remainder) <= abs(other)/2
1451 if 2*r + (q&1) > op2.int:
1452 r -= op2.int
1453 q += 1
1454
1455 if q >= 10**context.prec:
1456 return context._raise_error(DivisionImpossible)
1457
1458 # result has same sign as self unless r is negative
1459 sign = self._sign
1460 if r < 0:
1461 sign = 1-sign
1462 r = -r
1463
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001464 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001465 return ans._fix(context)
1466
1467 def __floordiv__(self, other, context=None):
1468 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001469 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001470 if other is NotImplemented:
1471 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001472
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001473 if context is None:
1474 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001475
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001476 ans = self._check_nans(other, context)
1477 if ans:
1478 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001479
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001480 if self._isinfinity():
1481 if other._isinfinity():
1482 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001483 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001484 return Infsign[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001485
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001486 if not other:
1487 if self:
1488 return context._raise_error(DivisionByZero, 'x // 0',
1489 self._sign ^ other._sign)
1490 else:
1491 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001492
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001493 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001494
1495 def __rfloordiv__(self, other, context=None):
1496 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001497 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001498 if other is NotImplemented:
1499 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001500 return other.__floordiv__(self, context=context)
1501
1502 def __float__(self):
1503 """Float representation."""
1504 return float(str(self))
1505
1506 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001507 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001508 if self._is_special:
1509 if self._isnan():
1510 context = getcontext()
1511 return context._raise_error(InvalidContext)
1512 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001513 raise OverflowError("Cannot convert infinity to int")
1514 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001515 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001516 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001517 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001518 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001519
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001520 def _fix_nan(self, context):
1521 """Decapitate the payload of a NaN to fit the context"""
1522 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001523
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001524 # maximum length of payload is precision if _clamp=0,
1525 # precision-1 if _clamp=1.
1526 max_payload_len = context.prec - context._clamp
1527 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001528 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1529 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001530 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001531
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001532 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001533 """Round if it is necessary to keep self within prec precision.
1534
1535 Rounds and fixes the exponent. Does not raise on a sNaN.
1536
1537 Arguments:
1538 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001539 context - context used.
1540 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001541
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001542 if context is None:
1543 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001544
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001545 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001546 if self._isnan():
1547 # decapitate payload if necessary
1548 return self._fix_nan(context)
1549 else:
1550 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001551 return Decimal(self)
1552
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001553 # if self is zero then exponent should be between Etiny and
1554 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1555 Etiny = context.Etiny()
1556 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001557 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001558 exp_max = [context.Emax, Etop][context._clamp]
1559 new_exp = min(max(self._exp, Etiny), exp_max)
1560 if new_exp != self._exp:
1561 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001562 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001563 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001564 return Decimal(self)
1565
1566 # exp_min is the smallest allowable exponent of the result,
1567 # equal to max(self.adjusted()-context.prec+1, Etiny)
1568 exp_min = len(self._int) + self._exp - context.prec
1569 if exp_min > Etop:
1570 # overflow: exp_min > Etop iff self.adjusted() > Emax
1571 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001572 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001573 return context._raise_error(Overflow, 'above Emax', self._sign)
1574 self_is_subnormal = exp_min < Etiny
1575 if self_is_subnormal:
1576 context._raise_error(Subnormal)
1577 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001578
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001579 # round if self has too many digits
1580 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001581 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001582 ans = self._rescale(exp_min, context.rounding)
1583 if ans != self:
1584 context._raise_error(Inexact)
1585 if self_is_subnormal:
1586 context._raise_error(Underflow)
1587 if not ans:
1588 # raise Clamped on underflow to 0
1589 context._raise_error(Clamped)
1590 elif len(ans._int) == context.prec+1:
1591 # we get here only if rescaling rounds the
1592 # cofficient up to exactly 10**context.prec
1593 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001594 ans = _dec_from_triple(ans._sign,
1595 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001596 else:
1597 # Inexact and Rounded have already been raised
1598 ans = context._raise_error(Overflow, 'above Emax',
1599 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001600 return ans
1601
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001602 # fold down if _clamp == 1 and self has too few digits
1603 if context._clamp == 1 and self._exp > Etop:
1604 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001605 self_padded = self._int + '0'*(self._exp - Etop)
1606 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001607
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001608 # here self was representable to begin with; return unchanged
1609 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001610
1611 _pick_rounding_function = {}
1612
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001613 # for each of the rounding functions below:
1614 # self is a finite, nonzero Decimal
1615 # prec is an integer satisfying 0 <= prec < len(self._int)
1616 # the rounded result will have exponent self._exp + len(self._int) - prec;
1617
1618 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001619 """Also known as round-towards-0, truncate."""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001620 newexp = self._exp + len(self._int) - prec
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001621 return _dec_from_triple(self._sign, self._int[:prec] or '0', newexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001622
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001623 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001624 """Rounds away from 0."""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001625 newexp = self._exp + len(self._int) - prec
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001626 tmp = _dec_from_triple(self._sign, self._int[:prec] or '0', newexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001627 for digit in self._int[prec:]:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001628 if digit != '0':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001629 return tmp._increment()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001630 return tmp
1631
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001632 def _round_half_up(self, prec):
1633 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001634 if self._int[prec] in '56789':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001635 return self._round_up(prec)
1636 else:
1637 return self._round_down(prec)
1638
1639 def _round_half_down(self, prec):
1640 """Round 5 down"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001641 if self._int[prec] == '5':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001642 for digit in self._int[prec+1:]:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001643 if digit != '0':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001644 break
1645 else:
1646 return self._round_down(prec)
1647 return self._round_half_up(prec)
1648
1649 def _round_half_even(self, prec):
1650 """Round 5 to even, rest to nearest."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001651 if prec and self._int[prec-1] in '13579':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001652 return self._round_half_up(prec)
1653 else:
1654 return self._round_half_down(prec)
1655
1656 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001657 """Rounds up (not away from 0 if negative.)"""
1658 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001659 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001660 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001661 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001662
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001663 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001664 """Rounds down (not towards 0 if negative)"""
1665 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001666 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001667 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001668 return self._round_up(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001669
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001670 def _round_05up(self, prec):
1671 """Round down unless digit prec-1 is 0 or 5."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001672 if prec == 0 or self._int[prec-1] in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001673 return self._round_up(prec)
1674 else:
1675 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001676
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001677 def fma(self, other, third, context=None):
1678 """Fused multiply-add.
1679
1680 Returns self*other+third with no rounding of the intermediate
1681 product self*other.
1682
1683 self and other are multiplied together, with no rounding of
1684 the result. The third operand is then added to the result,
1685 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001686 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001687
1688 other = _convert_other(other, raiseit=True)
1689 third = _convert_other(third, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001690
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001691 if context is None:
1692 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001693
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001694 # do self*other in fresh context with no traps and no rounding
1695 mul_context = Context(traps=[], flags=[],
1696 _rounding_decision=NEVER_ROUND)
1697 product = self.__mul__(other, mul_context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001698
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001699 if mul_context.flags[InvalidOperation]:
1700 # reraise in current context
1701 return context._raise_error(InvalidOperation,
1702 'invalid multiplication in fma',
1703 1, product)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001704
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001705 ans = product.__add__(third, context)
1706 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001707
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001708 def _power_modulo(self, other, modulo, context=None):
1709 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001710
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001711 # if can't convert other and modulo to Decimal, raise
1712 # TypeError; there's no point returning NotImplemented (no
1713 # equivalent of __rpow__ for three argument pow)
1714 other = _convert_other(other, raiseit=True)
1715 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001716
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001717 if context is None:
1718 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001719
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001720 # deal with NaNs: if there are any sNaNs then first one wins,
1721 # (i.e. behaviour for NaNs is identical to that of fma)
1722 self_is_nan = self._isnan()
1723 other_is_nan = other._isnan()
1724 modulo_is_nan = modulo._isnan()
1725 if self_is_nan or other_is_nan or modulo_is_nan:
1726 if self_is_nan == 2:
1727 return context._raise_error(InvalidOperation, 'sNaN',
1728 1, self)
1729 if other_is_nan == 2:
1730 return context._raise_error(InvalidOperation, 'sNaN',
1731 1, other)
1732 if modulo_is_nan == 2:
1733 return context._raise_error(InvalidOperation, 'sNaN',
1734 1, modulo)
1735 if self_is_nan:
1736 return self._fix_nan(context)
1737 if other_is_nan:
1738 return other._fix_nan(context)
1739 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001740
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001741 # check inputs: we apply same restrictions as Python's pow()
1742 if not (self._isinteger() and
1743 other._isinteger() and
1744 modulo._isinteger()):
1745 return context._raise_error(InvalidOperation,
1746 'pow() 3rd argument not allowed '
1747 'unless all arguments are integers')
1748 if other < 0:
1749 return context._raise_error(InvalidOperation,
1750 'pow() 2nd argument cannot be '
1751 'negative when 3rd argument specified')
1752 if not modulo:
1753 return context._raise_error(InvalidOperation,
1754 'pow() 3rd argument cannot be 0')
1755
1756 # additional restriction for decimal: the modulus must be less
1757 # than 10**prec in absolute value
1758 if modulo.adjusted() >= context.prec:
1759 return context._raise_error(InvalidOperation,
1760 'insufficient precision: pow() 3rd '
1761 'argument must not have more than '
1762 'precision digits')
1763
1764 # define 0**0 == NaN, for consistency with two-argument pow
1765 # (even though it hurts!)
1766 if not other and not self:
1767 return context._raise_error(InvalidOperation,
1768 'at least one of pow() 1st argument '
1769 'and 2nd argument must be nonzero ;'
1770 '0**0 is not defined')
1771
1772 # compute sign of result
1773 if other._iseven():
1774 sign = 0
1775 else:
1776 sign = self._sign
1777
1778 # convert modulo to a Python integer, and self and other to
1779 # Decimal integers (i.e. force their exponents to be >= 0)
1780 modulo = abs(int(modulo))
1781 base = _WorkRep(self.to_integral_value())
1782 exponent = _WorkRep(other.to_integral_value())
1783
1784 # compute result using integer pow()
1785 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1786 for i in range(exponent.exp):
1787 base = pow(base, 10, modulo)
1788 base = pow(base, exponent.int, modulo)
1789
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001790 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001791
1792 def _power_exact(self, other, p):
1793 """Attempt to compute self**other exactly.
1794
1795 Given Decimals self and other and an integer p, attempt to
1796 compute an exact result for the power self**other, with p
1797 digits of precision. Return None if self**other is not
1798 exactly representable in p digits.
1799
1800 Assumes that elimination of special cases has already been
1801 performed: self and other must both be nonspecial; self must
1802 be positive and not numerically equal to 1; other must be
1803 nonzero. For efficiency, other._exp should not be too large,
1804 so that 10**abs(other._exp) is a feasible calculation."""
1805
1806 # In the comments below, we write x for the value of self and
1807 # y for the value of other. Write x = xc*10**xe and y =
1808 # yc*10**ye.
1809
1810 # The main purpose of this method is to identify the *failure*
1811 # of x**y to be exactly representable with as little effort as
1812 # possible. So we look for cheap and easy tests that
1813 # eliminate the possibility of x**y being exact. Only if all
1814 # these tests are passed do we go on to actually compute x**y.
1815
1816 # Here's the main idea. First normalize both x and y. We
1817 # express y as a rational m/n, with m and n relatively prime
1818 # and n>0. Then for x**y to be exactly representable (at
1819 # *any* precision), xc must be the nth power of a positive
1820 # integer and xe must be divisible by n. If m is negative
1821 # then additionally xc must be a power of either 2 or 5, hence
1822 # a power of 2**n or 5**n.
1823 #
1824 # There's a limit to how small |y| can be: if y=m/n as above
1825 # then:
1826 #
1827 # (1) if xc != 1 then for the result to be representable we
1828 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1829 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1830 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1831 # representable.
1832 #
1833 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1834 # |y| < 1/|xe| then the result is not representable.
1835 #
1836 # Note that since x is not equal to 1, at least one of (1) and
1837 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1838 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1839 #
1840 # There's also a limit to how large y can be, at least if it's
1841 # positive: the normalized result will have coefficient xc**y,
1842 # so if it's representable then xc**y < 10**p, and y <
1843 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1844 # not exactly representable.
1845
1846 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1847 # so |y| < 1/xe and the result is not representable.
1848 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1849 # < 1/nbits(xc).
1850
1851 x = _WorkRep(self)
1852 xc, xe = x.int, x.exp
1853 while xc % 10 == 0:
1854 xc //= 10
1855 xe += 1
1856
1857 y = _WorkRep(other)
1858 yc, ye = y.int, y.exp
1859 while yc % 10 == 0:
1860 yc //= 10
1861 ye += 1
1862
1863 # case where xc == 1: result is 10**(xe*y), with xe*y
1864 # required to be an integer
1865 if xc == 1:
1866 if ye >= 0:
1867 exponent = xe*yc*10**ye
1868 else:
1869 exponent, remainder = divmod(xe*yc, 10**-ye)
1870 if remainder:
1871 return None
1872 if y.sign == 1:
1873 exponent = -exponent
1874 # if other is a nonnegative integer, use ideal exponent
1875 if other._isinteger() and other._sign == 0:
1876 ideal_exponent = self._exp*int(other)
1877 zeros = min(exponent-ideal_exponent, p-1)
1878 else:
1879 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001880 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001881
1882 # case where y is negative: xc must be either a power
1883 # of 2 or a power of 5.
1884 if y.sign == 1:
1885 last_digit = xc % 10
1886 if last_digit in (2,4,6,8):
1887 # quick test for power of 2
1888 if xc & -xc != xc:
1889 return None
1890 # now xc is a power of 2; e is its exponent
1891 e = _nbits(xc)-1
1892 # find e*y and xe*y; both must be integers
1893 if ye >= 0:
1894 y_as_int = yc*10**ye
1895 e = e*y_as_int
1896 xe = xe*y_as_int
1897 else:
1898 ten_pow = 10**-ye
1899 e, remainder = divmod(e*yc, ten_pow)
1900 if remainder:
1901 return None
1902 xe, remainder = divmod(xe*yc, ten_pow)
1903 if remainder:
1904 return None
1905
1906 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1907 return None
1908 xc = 5**e
1909
1910 elif last_digit == 5:
1911 # e >= log_5(xc) if xc is a power of 5; we have
1912 # equality all the way up to xc=5**2658
1913 e = _nbits(xc)*28//65
1914 xc, remainder = divmod(5**e, xc)
1915 if remainder:
1916 return None
1917 while xc % 5 == 0:
1918 xc //= 5
1919 e -= 1
1920 if ye >= 0:
1921 y_as_integer = yc*10**ye
1922 e = e*y_as_integer
1923 xe = xe*y_as_integer
1924 else:
1925 ten_pow = 10**-ye
1926 e, remainder = divmod(e*yc, ten_pow)
1927 if remainder:
1928 return None
1929 xe, remainder = divmod(xe*yc, ten_pow)
1930 if remainder:
1931 return None
1932 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1933 return None
1934 xc = 2**e
1935 else:
1936 return None
1937
1938 if xc >= 10**p:
1939 return None
1940 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001941 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001942
1943 # now y is positive; find m and n such that y = m/n
1944 if ye >= 0:
1945 m, n = yc*10**ye, 1
1946 else:
1947 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1948 return None
1949 xc_bits = _nbits(xc)
1950 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1951 return None
1952 m, n = yc, 10**(-ye)
1953 while m % 2 == n % 2 == 0:
1954 m //= 2
1955 n //= 2
1956 while m % 5 == n % 5 == 0:
1957 m //= 5
1958 n //= 5
1959
1960 # compute nth root of xc*10**xe
1961 if n > 1:
1962 # if 1 < xc < 2**n then xc isn't an nth power
1963 if xc != 1 and xc_bits <= n:
1964 return None
1965
1966 xe, rem = divmod(xe, n)
1967 if rem != 0:
1968 return None
1969
1970 # compute nth root of xc using Newton's method
1971 a = 1 << -(-_nbits(xc)//n) # initial estimate
1972 while True:
1973 q, r = divmod(xc, a**(n-1))
1974 if a <= q:
1975 break
1976 else:
1977 a = (a*(n-1) + q)//n
1978 if not (a == q and r == 0):
1979 return None
1980 xc = a
1981
1982 # now xc*10**xe is the nth root of the original xc*10**xe
1983 # compute mth power of xc*10**xe
1984
1985 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1986 # 10**p and the result is not representable.
1987 if xc > 1 and m > p*100//_log10_lb(xc):
1988 return None
1989 xc = xc**m
1990 xe *= m
1991 if xc > 10**p:
1992 return None
1993
1994 # by this point the result *is* exactly representable
1995 # adjust the exponent to get as close as possible to the ideal
1996 # exponent, if necessary
1997 str_xc = str(xc)
1998 if other._isinteger() and other._sign == 0:
1999 ideal_exponent = self._exp*int(other)
2000 zeros = min(xe-ideal_exponent, p-len(str_xc))
2001 else:
2002 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002003 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002004
2005 def __pow__(self, other, modulo=None, context=None):
2006 """Return self ** other [ % modulo].
2007
2008 With two arguments, compute self**other.
2009
2010 With three arguments, compute (self**other) % modulo. For the
2011 three argument form, the following restrictions on the
2012 arguments hold:
2013
2014 - all three arguments must be integral
2015 - other must be nonnegative
2016 - either self or other (or both) must be nonzero
2017 - modulo must be nonzero and must have at most p digits,
2018 where p is the context precision.
2019
2020 If any of these restrictions is violated the InvalidOperation
2021 flag is raised.
2022
2023 The result of pow(self, other, modulo) is identical to the
2024 result that would be obtained by computing (self**other) %
2025 modulo with unbounded precision, but is computed more
2026 efficiently. It is always exact.
2027 """
2028
2029 if modulo is not None:
2030 return self._power_modulo(other, modulo, context)
2031
2032 other = _convert_other(other)
2033 if other is NotImplemented:
2034 return other
2035
2036 if context is None:
2037 context = getcontext()
2038
2039 # either argument is a NaN => result is NaN
2040 ans = self._check_nans(other, context)
2041 if ans:
2042 return ans
2043
2044 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2045 if not other:
2046 if not self:
2047 return context._raise_error(InvalidOperation, '0 ** 0')
2048 else:
2049 return Dec_p1
2050
2051 # result has sign 1 iff self._sign is 1 and other is an odd integer
2052 result_sign = 0
2053 if self._sign == 1:
2054 if other._isinteger():
2055 if not other._iseven():
2056 result_sign = 1
2057 else:
2058 # -ve**noninteger = NaN
2059 # (-0)**noninteger = 0**noninteger
2060 if self:
2061 return context._raise_error(InvalidOperation,
2062 'x ** y with x negative and y not an integer')
2063 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002064 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002065
2066 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2067 if not self:
2068 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002069 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002070 else:
2071 return Infsign[result_sign]
2072
2073 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002074 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002075 if other._sign == 0:
2076 return Infsign[result_sign]
2077 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002078 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002079
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002080 # 1**other = 1, but the choice of exponent and the flags
2081 # depend on the exponent of self, and on whether other is a
2082 # positive integer, a negative integer, or neither
2083 if self == Dec_p1:
2084 if other._isinteger():
2085 # exp = max(self._exp*max(int(other), 0),
2086 # 1-context.prec) but evaluating int(other) directly
2087 # is dangerous until we know other is small (other
2088 # could be 1e999999999)
2089 if other._sign == 1:
2090 multiplier = 0
2091 elif other > context.prec:
2092 multiplier = context.prec
2093 else:
2094 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002095
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002096 exp = self._exp * multiplier
2097 if exp < 1-context.prec:
2098 exp = 1-context.prec
2099 context._raise_error(Rounded)
2100 else:
2101 context._raise_error(Inexact)
2102 context._raise_error(Rounded)
2103 exp = 1-context.prec
2104
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002105 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002106
2107 # compute adjusted exponent of self
2108 self_adj = self.adjusted()
2109
2110 # self ** infinity is infinity if self > 1, 0 if self < 1
2111 # self ** -infinity is infinity if self < 1, 0 if self > 1
2112 if other._isinfinity():
2113 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002114 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002115 else:
2116 return Infsign[result_sign]
2117
2118 # from here on, the result always goes through the call
2119 # to _fix at the end of this function.
2120 ans = None
2121
2122 # crude test to catch cases of extreme overflow/underflow. If
2123 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2124 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2125 # self**other >= 10**(Emax+1), so overflow occurs. The test
2126 # for underflow is similar.
2127 bound = self._log10_exp_bound() + other.adjusted()
2128 if (self_adj >= 0) == (other._sign == 0):
2129 # self > 1 and other +ve, or self < 1 and other -ve
2130 # possibility of overflow
2131 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002132 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002133 else:
2134 # self > 1 and other -ve, or self < 1 and other +ve
2135 # possibility of underflow to 0
2136 Etiny = context.Etiny()
2137 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002138 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002139
2140 # try for an exact result with precision +1
2141 if ans is None:
2142 ans = self._power_exact(other, context.prec + 1)
2143 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002144 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002145
2146 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2147 if ans is None:
2148 p = context.prec
2149 x = _WorkRep(self)
2150 xc, xe = x.int, x.exp
2151 y = _WorkRep(other)
2152 yc, ye = y.int, y.exp
2153 if y.sign == 1:
2154 yc = -yc
2155
2156 # compute correctly rounded result: start with precision +3,
2157 # then increase precision until result is unambiguously roundable
2158 extra = 3
2159 while True:
2160 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2161 if coeff % (5*10**(len(str(coeff))-p-1)):
2162 break
2163 extra += 3
2164
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002165 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002166
2167 # the specification says that for non-integer other we need to
2168 # raise Inexact, even when the result is actually exact. In
2169 # the same way, we need to raise Underflow here if the result
2170 # is subnormal. (The call to _fix will take care of raising
2171 # Rounded and Subnormal, as usual.)
2172 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002173 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002174 # pad with zeros up to length context.prec+1 if necessary
2175 if len(ans._int) <= context.prec:
2176 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002177 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2178 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002179 if ans.adjusted() < context.Emin:
2180 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002181
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002182 # unlike exp, ln and log10, the power function respects the
2183 # rounding mode; no need to use ROUND_HALF_EVEN here
2184 ans = ans._fix(context)
2185 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002186
2187 def __rpow__(self, other, context=None):
2188 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002189 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002190 if other is NotImplemented:
2191 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002192 return other.__pow__(self, context=context)
2193
2194 def normalize(self, context=None):
2195 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002196
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002197 if context is None:
2198 context = getcontext()
2199
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002200 if self._is_special:
2201 ans = self._check_nans(context=context)
2202 if ans:
2203 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002204
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002205 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002206 if dup._isinfinity():
2207 return dup
2208
2209 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002210 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002211 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002212 end = len(dup._int)
2213 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002214 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002215 exp += 1
2216 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002217 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002218
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002219 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002220 """Quantize self so its exponent is the same as that of exp.
2221
2222 Similar to self._rescale(exp._exp) but with error checking.
2223 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002224 exp = _convert_other(exp, raiseit=True)
2225
2226 if context is None:
2227 context = getcontext()
2228 if rounding is None:
2229 rounding = context.rounding
2230
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002231 if self._is_special or exp._is_special:
2232 ans = self._check_nans(exp, context)
2233 if ans:
2234 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002235
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002236 if exp._isinfinity() or self._isinfinity():
2237 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002238 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002239 return context._raise_error(InvalidOperation,
2240 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002241
2242 # if we're not watching exponents, do a simple rescale
2243 if not watchexp:
2244 ans = self._rescale(exp._exp, rounding)
2245 # raise Inexact and Rounded where appropriate
2246 if ans._exp > self._exp:
2247 context._raise_error(Rounded)
2248 if ans != self:
2249 context._raise_error(Inexact)
2250 return ans
2251
2252 # exp._exp should be between Etiny and Emax
2253 if not (context.Etiny() <= exp._exp <= context.Emax):
2254 return context._raise_error(InvalidOperation,
2255 'target exponent out of bounds in quantize')
2256
2257 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002258 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002259 return ans._fix(context)
2260
2261 self_adjusted = self.adjusted()
2262 if self_adjusted > context.Emax:
2263 return context._raise_error(InvalidOperation,
2264 'exponent of quantize result too large for current context')
2265 if self_adjusted - exp._exp + 1 > context.prec:
2266 return context._raise_error(InvalidOperation,
2267 'quantize result has too many digits for current context')
2268
2269 ans = self._rescale(exp._exp, rounding)
2270 if ans.adjusted() > context.Emax:
2271 return context._raise_error(InvalidOperation,
2272 'exponent of quantize result too large for current context')
2273 if len(ans._int) > context.prec:
2274 return context._raise_error(InvalidOperation,
2275 'quantize result has too many digits for current context')
2276
2277 # raise appropriate flags
2278 if ans._exp > self._exp:
2279 context._raise_error(Rounded)
2280 if ans != self:
2281 context._raise_error(Inexact)
2282 if ans and ans.adjusted() < context.Emin:
2283 context._raise_error(Subnormal)
2284
2285 # call to fix takes care of any necessary folddown
2286 ans = ans._fix(context)
2287 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002288
2289 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002290 """Return True if self and other have the same exponent; otherwise
2291 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002292
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002293 If either operand is a special value, the following rules are used:
2294 * return True if both operands are infinities
2295 * return True if both operands are NaNs
2296 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002297 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002298 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002299 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002300 return (self.is_nan() and other.is_nan() or
2301 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002302 return self._exp == other._exp
2303
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002304 def _rescale(self, exp, rounding):
2305 """Rescale self so that the exponent is exp, either by padding with zeros
2306 or by truncating digits, using the given rounding mode.
2307
2308 Specials are returned without change. This operation is
2309 quiet: it raises no flags, and uses no information from the
2310 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002311
2312 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002313 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002314 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002315 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002316 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002317 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002318 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002319
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002320 if self._exp >= exp:
2321 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002322 return _dec_from_triple(self._sign,
2323 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002324
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002325 # too many digits; round and lose data. If self.adjusted() <
2326 # exp-1, replace self by 10**(exp-1) before rounding
2327 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002328 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002329 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002330 digits = 0
2331 this_function = getattr(self, self._pick_rounding_function[rounding])
2332 return this_function(digits)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002333
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002334 def to_integral_exact(self, rounding=None, context=None):
2335 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002336
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002337 If no rounding mode is specified, take the rounding mode from
2338 the context. This method raises the Rounded and Inexact flags
2339 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002340
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002341 See also: to_integral_value, which does exactly the same as
2342 this method except that it doesn't raise Inexact or Rounded.
2343 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002344 if self._is_special:
2345 ans = self._check_nans(context=context)
2346 if ans:
2347 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002348 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002349 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002350 return Decimal(self)
2351 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002352 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002353 if context is None:
2354 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002355 if rounding is None:
2356 rounding = context.rounding
2357 context._raise_error(Rounded)
2358 ans = self._rescale(0, rounding)
2359 if ans != self:
2360 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002361 return ans
2362
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002363 def to_integral_value(self, rounding=None, context=None):
2364 """Rounds to the nearest integer, without raising inexact, rounded."""
2365 if context is None:
2366 context = getcontext()
2367 if rounding is None:
2368 rounding = context.rounding
2369 if self._is_special:
2370 ans = self._check_nans(context=context)
2371 if ans:
2372 return ans
2373 return Decimal(self)
2374 if self._exp >= 0:
2375 return Decimal(self)
2376 else:
2377 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002378
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002379 # the method name changed, but we provide also the old one, for compatibility
2380 to_integral = to_integral_value
2381
2382 def sqrt(self, context=None):
2383 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002384 if self._is_special:
2385 ans = self._check_nans(context=context)
2386 if ans:
2387 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002388
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002389 if self._isinfinity() and self._sign == 0:
2390 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002391
2392 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002393 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002394 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002395 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002396
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002397 if context is None:
2398 context = getcontext()
2399
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002400 if self._sign == 1:
2401 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2402
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002403 # At this point self represents a positive number. Let p be
2404 # the desired precision and express self in the form c*100**e
2405 # with c a positive real number and e an integer, c and e
2406 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2407 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2408 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2409 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2410 # the closest integer to sqrt(c) with the even integer chosen
2411 # in the case of a tie.
2412 #
2413 # To ensure correct rounding in all cases, we use the
2414 # following trick: we compute the square root to an extra
2415 # place (precision p+1 instead of precision p), rounding down.
2416 # Then, if the result is inexact and its last digit is 0 or 5,
2417 # we increase the last digit to 1 or 6 respectively; if it's
2418 # exact we leave the last digit alone. Now the final round to
2419 # p places (or fewer in the case of underflow) will round
2420 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002421
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002422 # use an extra digit of precision
2423 prec = context.prec+1
2424
2425 # write argument in the form c*100**e where e = self._exp//2
2426 # is the 'ideal' exponent, to be used if the square root is
2427 # exactly representable. l is the number of 'digits' of c in
2428 # base 100, so that 100**(l-1) <= c < 100**l.
2429 op = _WorkRep(self)
2430 e = op.exp >> 1
2431 if op.exp & 1:
2432 c = op.int * 10
2433 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002434 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002435 c = op.int
2436 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002437
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002438 # rescale so that c has exactly prec base 100 'digits'
2439 shift = prec-l
2440 if shift >= 0:
2441 c *= 100**shift
2442 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002443 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002444 c, remainder = divmod(c, 100**-shift)
2445 exact = not remainder
2446 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002447
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002448 # find n = floor(sqrt(c)) using Newton's method
2449 n = 10**prec
2450 while True:
2451 q = c//n
2452 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002453 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002454 else:
2455 n = n + q >> 1
2456 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002457
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002458 if exact:
2459 # result is exact; rescale to use ideal exponent e
2460 if shift >= 0:
2461 # assert n % 10**shift == 0
2462 n //= 10**shift
2463 else:
2464 n *= 10**-shift
2465 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002466 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002467 # result is not exact; fix last digit as described above
2468 if n % 5 == 0:
2469 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002470
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002471 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002472
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002473 # round, and fit to current context
2474 context = context._shallow_copy()
2475 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002476 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002477 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002478
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002479 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002480
2481 def max(self, other, context=None):
2482 """Returns the larger value.
2483
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002484 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002485 NaN (and signals if one is sNaN). Also rounds.
2486 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002487 other = _convert_other(other, raiseit=True)
2488
2489 if context is None:
2490 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002491
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002492 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002493 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002494 # number is always returned
2495 sn = self._isnan()
2496 on = other._isnan()
2497 if sn or on:
2498 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002499 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002500 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002501 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002502 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002503
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002504 c = self.__cmp__(other)
2505 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002506 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002507 # then an ordering is applied:
2508 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002509 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002510 # positive sign and min returns the operand with the negative sign
2511 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002512 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002513 # the result. This is exactly the ordering used in compare_total.
2514 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002515
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002516 if c == -1:
2517 ans = other
2518 else:
2519 ans = self
2520
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 min(self, other, context=None):
2526 """Returns the smaller value.
2527
Guido van Rossumd8faa362007-04-27 19:54:29 +00002528 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002529 NaN (and signals if one is sNaN). Also rounds.
2530 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002531 other = _convert_other(other, raiseit=True)
2532
2533 if context is None:
2534 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002535
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002536 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002537 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002538 # number is always returned
2539 sn = self._isnan()
2540 on = other._isnan()
2541 if sn or on:
2542 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002543 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002544 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002545 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002546 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002547
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002548 c = self.__cmp__(other)
2549 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002550 c = self.compare_total(other)
2551
2552 if c == -1:
2553 ans = self
2554 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002555 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002556
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002557 if context._rounding_decision == ALWAYS_ROUND:
2558 return ans._fix(context)
2559 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002560
2561 def _isinteger(self):
2562 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002563 if self._is_special:
2564 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002565 if self._exp >= 0:
2566 return True
2567 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002568 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002569
2570 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002571 """Returns True if self is even. Assumes self is an integer."""
2572 if not self or self._exp > 0:
2573 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002574 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002575
2576 def adjusted(self):
2577 """Return the adjusted exponent of self"""
2578 try:
2579 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002580 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002581 except TypeError:
2582 return 0
2583
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002584 def canonical(self, context=None):
2585 """Returns the same Decimal object.
2586
2587 As we do not have different encodings for the same number, the
2588 received object already is in its canonical form.
2589 """
2590 return self
2591
2592 def compare_signal(self, other, context=None):
2593 """Compares self to the other operand numerically.
2594
2595 It's pretty much like compare(), but all NaNs signal, with signaling
2596 NaNs taking precedence over quiet NaNs.
2597 """
2598 if context is None:
2599 context = getcontext()
2600
2601 self_is_nan = self._isnan()
2602 other_is_nan = other._isnan()
2603 if self_is_nan == 2:
2604 return context._raise_error(InvalidOperation, 'sNaN',
2605 1, self)
2606 if other_is_nan == 2:
2607 return context._raise_error(InvalidOperation, 'sNaN',
2608 1, other)
2609 if self_is_nan:
2610 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2611 1, self)
2612 if other_is_nan:
2613 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2614 1, other)
2615 return self.compare(other, context=context)
2616
2617 def compare_total(self, other):
2618 """Compares self to other using the abstract representations.
2619
2620 This is not like the standard compare, which use their numerical
2621 value. Note that a total ordering is defined for all possible abstract
2622 representations.
2623 """
2624 # if one is negative and the other is positive, it's easy
2625 if self._sign and not other._sign:
2626 return Dec_n1
2627 if not self._sign and other._sign:
2628 return Dec_p1
2629 sign = self._sign
2630
2631 # let's handle both NaN types
2632 self_nan = self._isnan()
2633 other_nan = other._isnan()
2634 if self_nan or other_nan:
2635 if self_nan == other_nan:
2636 if self._int < other._int:
2637 if sign:
2638 return Dec_p1
2639 else:
2640 return Dec_n1
2641 if self._int > other._int:
2642 if sign:
2643 return Dec_n1
2644 else:
2645 return Dec_p1
2646 return Dec_0
2647
2648 if sign:
2649 if self_nan == 1:
2650 return Dec_n1
2651 if other_nan == 1:
2652 return Dec_p1
2653 if self_nan == 2:
2654 return Dec_n1
2655 if other_nan == 2:
2656 return Dec_p1
2657 else:
2658 if self_nan == 1:
2659 return Dec_p1
2660 if other_nan == 1:
2661 return Dec_n1
2662 if self_nan == 2:
2663 return Dec_p1
2664 if other_nan == 2:
2665 return Dec_n1
2666
2667 if self < other:
2668 return Dec_n1
2669 if self > other:
2670 return Dec_p1
2671
2672 if self._exp < other._exp:
2673 if sign:
2674 return Dec_p1
2675 else:
2676 return Dec_n1
2677 if self._exp > other._exp:
2678 if sign:
2679 return Dec_n1
2680 else:
2681 return Dec_p1
2682 return Dec_0
2683
2684
2685 def compare_total_mag(self, other):
2686 """Compares self to other using abstract repr., ignoring sign.
2687
2688 Like compare_total, but with operand's sign ignored and assumed to be 0.
2689 """
2690 s = self.copy_abs()
2691 o = other.copy_abs()
2692 return s.compare_total(o)
2693
2694 def copy_abs(self):
2695 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002696 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002697
2698 def copy_negate(self):
2699 """Returns a copy with the sign inverted."""
2700 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002701 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002702 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002703 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002704
2705 def copy_sign(self, other):
2706 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002707 return _dec_from_triple(other._sign, self._int,
2708 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002709
2710 def exp(self, context=None):
2711 """Returns e ** self."""
2712
2713 if context is None:
2714 context = getcontext()
2715
2716 # exp(NaN) = NaN
2717 ans = self._check_nans(context=context)
2718 if ans:
2719 return ans
2720
2721 # exp(-Infinity) = 0
2722 if self._isinfinity() == -1:
2723 return Dec_0
2724
2725 # exp(0) = 1
2726 if not self:
2727 return Dec_p1
2728
2729 # exp(Infinity) = Infinity
2730 if self._isinfinity() == 1:
2731 return Decimal(self)
2732
2733 # the result is now guaranteed to be inexact (the true
2734 # mathematical result is transcendental). There's no need to
2735 # raise Rounded and Inexact here---they'll always be raised as
2736 # a result of the call to _fix.
2737 p = context.prec
2738 adj = self.adjusted()
2739
2740 # we only need to do any computation for quite a small range
2741 # of adjusted exponents---for example, -29 <= adj <= 10 for
2742 # the default context. For smaller exponent the result is
2743 # indistinguishable from 1 at the given precision, while for
2744 # larger exponent the result either overflows or underflows.
2745 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2746 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002747 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002748 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2749 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002750 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002751 elif self._sign == 0 and adj < -p:
2752 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002753 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002754 elif self._sign == 1 and adj < -p-1:
2755 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002756 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002757 # general case
2758 else:
2759 op = _WorkRep(self)
2760 c, e = op.int, op.exp
2761 if op.sign == 1:
2762 c = -c
2763
2764 # compute correctly rounded result: increase precision by
2765 # 3 digits at a time until we get an unambiguously
2766 # roundable result
2767 extra = 3
2768 while True:
2769 coeff, exp = _dexp(c, e, p+extra)
2770 if coeff % (5*10**(len(str(coeff))-p-1)):
2771 break
2772 extra += 3
2773
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002774 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002775
2776 # at this stage, ans should round correctly with *any*
2777 # rounding mode, not just with ROUND_HALF_EVEN
2778 context = context._shallow_copy()
2779 rounding = context._set_rounding(ROUND_HALF_EVEN)
2780 ans = ans._fix(context)
2781 context.rounding = rounding
2782
2783 return ans
2784
2785 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002786 """Return True if self is canonical; otherwise return False.
2787
2788 Currently, the encoding of a Decimal instance is always
2789 canonical, so this method returns True for any Decimal.
2790 """
2791 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002792
2793 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002794 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002795
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002796 A Decimal instance is considered finite if it is neither
2797 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002798 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002799 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002800
2801 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002802 """Return True if self is infinite; otherwise return False."""
2803 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002804
2805 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002806 """Return True if self is a qNaN or sNaN; otherwise return False."""
2807 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002808
2809 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002810 """Return True if self is a normal number; otherwise return False."""
2811 if self._is_special or not self:
2812 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002813 if context is None:
2814 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002815 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002816
2817 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002818 """Return True if self is a quiet NaN; otherwise return False."""
2819 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002820
2821 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002822 """Return True if self is negative; otherwise return False."""
2823 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002824
2825 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002826 """Return True if self is a signaling NaN; otherwise return False."""
2827 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002828
2829 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002830 """Return True if self is subnormal; otherwise return False."""
2831 if self._is_special or not self:
2832 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002833 if context is None:
2834 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002835 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002836
2837 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002838 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002839 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002840
2841 def _ln_exp_bound(self):
2842 """Compute a lower bound for the adjusted exponent of self.ln().
2843 In other words, compute r such that self.ln() >= 10**r. Assumes
2844 that self is finite and positive and that self != 1.
2845 """
2846
2847 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2848 adj = self._exp + len(self._int) - 1
2849 if adj >= 1:
2850 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2851 return len(str(adj*23//10)) - 1
2852 if adj <= -2:
2853 # argument <= 0.1
2854 return len(str((-1-adj)*23//10)) - 1
2855 op = _WorkRep(self)
2856 c, e = op.int, op.exp
2857 if adj == 0:
2858 # 1 < self < 10
2859 num = str(c-10**-e)
2860 den = str(c)
2861 return len(num) - len(den) - (num < den)
2862 # adj == -1, 0.1 <= self < 1
2863 return e + len(str(10**-e - c)) - 1
2864
2865
2866 def ln(self, context=None):
2867 """Returns the natural (base e) logarithm of self."""
2868
2869 if context is None:
2870 context = getcontext()
2871
2872 # ln(NaN) = NaN
2873 ans = self._check_nans(context=context)
2874 if ans:
2875 return ans
2876
2877 # ln(0.0) == -Infinity
2878 if not self:
2879 return negInf
2880
2881 # ln(Infinity) = Infinity
2882 if self._isinfinity() == 1:
2883 return Inf
2884
2885 # ln(1.0) == 0.0
2886 if self == Dec_p1:
2887 return Dec_0
2888
2889 # ln(negative) raises InvalidOperation
2890 if self._sign == 1:
2891 return context._raise_error(InvalidOperation,
2892 'ln of a negative value')
2893
2894 # result is irrational, so necessarily inexact
2895 op = _WorkRep(self)
2896 c, e = op.int, op.exp
2897 p = context.prec
2898
2899 # correctly rounded result: repeatedly increase precision by 3
2900 # until we get an unambiguously roundable result
2901 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2902 while True:
2903 coeff = _dlog(c, e, places)
2904 # assert len(str(abs(coeff)))-p >= 1
2905 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2906 break
2907 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002908 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002909
2910 context = context._shallow_copy()
2911 rounding = context._set_rounding(ROUND_HALF_EVEN)
2912 ans = ans._fix(context)
2913 context.rounding = rounding
2914 return ans
2915
2916 def _log10_exp_bound(self):
2917 """Compute a lower bound for the adjusted exponent of self.log10().
2918 In other words, find r such that self.log10() >= 10**r.
2919 Assumes that self is finite and positive and that self != 1.
2920 """
2921
2922 # For x >= 10 or x < 0.1 we only need a bound on the integer
2923 # part of log10(self), and this comes directly from the
2924 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2925 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2926 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2927
2928 adj = self._exp + len(self._int) - 1
2929 if adj >= 1:
2930 # self >= 10
2931 return len(str(adj))-1
2932 if adj <= -2:
2933 # self < 0.1
2934 return len(str(-1-adj))-1
2935 op = _WorkRep(self)
2936 c, e = op.int, op.exp
2937 if adj == 0:
2938 # 1 < self < 10
2939 num = str(c-10**-e)
2940 den = str(231*c)
2941 return len(num) - len(den) - (num < den) + 2
2942 # adj == -1, 0.1 <= self < 1
2943 num = str(10**-e-c)
2944 return len(num) + e - (num < "231") - 1
2945
2946 def log10(self, context=None):
2947 """Returns the base 10 logarithm of self."""
2948
2949 if context is None:
2950 context = getcontext()
2951
2952 # log10(NaN) = NaN
2953 ans = self._check_nans(context=context)
2954 if ans:
2955 return ans
2956
2957 # log10(0.0) == -Infinity
2958 if not self:
2959 return negInf
2960
2961 # log10(Infinity) = Infinity
2962 if self._isinfinity() == 1:
2963 return Inf
2964
2965 # log10(negative or -Infinity) raises InvalidOperation
2966 if self._sign == 1:
2967 return context._raise_error(InvalidOperation,
2968 'log10 of a negative value')
2969
2970 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002971 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002972 # answer may need rounding
2973 ans = Decimal(self._exp + len(self._int) - 1)
2974 else:
2975 # result is irrational, so necessarily inexact
2976 op = _WorkRep(self)
2977 c, e = op.int, op.exp
2978 p = context.prec
2979
2980 # correctly rounded result: repeatedly increase precision
2981 # until result is unambiguously roundable
2982 places = p-self._log10_exp_bound()+2
2983 while True:
2984 coeff = _dlog10(c, e, places)
2985 # assert len(str(abs(coeff)))-p >= 1
2986 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2987 break
2988 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002989 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002990
2991 context = context._shallow_copy()
2992 rounding = context._set_rounding(ROUND_HALF_EVEN)
2993 ans = ans._fix(context)
2994 context.rounding = rounding
2995 return ans
2996
2997 def logb(self, context=None):
2998 """ Returns the exponent of the magnitude of self's MSD.
2999
3000 The result is the integer which is the exponent of the magnitude
3001 of the most significant digit of self (as though it were truncated
3002 to a single digit while maintaining the value of that digit and
3003 without limiting the resulting exponent).
3004 """
3005 # logb(NaN) = NaN
3006 ans = self._check_nans(context=context)
3007 if ans:
3008 return ans
3009
3010 if context is None:
3011 context = getcontext()
3012
3013 # logb(+/-Inf) = +Inf
3014 if self._isinfinity():
3015 return Inf
3016
3017 # logb(0) = -Inf, DivisionByZero
3018 if not self:
3019 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3020
3021 # otherwise, simply return the adjusted exponent of self, as a
3022 # Decimal. Note that no attempt is made to fit the result
3023 # into the current context.
3024 return Decimal(self.adjusted())
3025
3026 def _islogical(self):
3027 """Return True if self is a logical operand.
3028
3029 For being logical, it must be a finite numbers with a sign of 0,
3030 an exponent of 0, and a coefficient whose digits must all be
3031 either 0 or 1.
3032 """
3033 if self._sign != 0 or self._exp != 0:
3034 return False
3035 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003036 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003037 return False
3038 return True
3039
3040 def _fill_logical(self, context, opa, opb):
3041 dif = context.prec - len(opa)
3042 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003043 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003044 elif dif < 0:
3045 opa = opa[-context.prec:]
3046 dif = context.prec - len(opb)
3047 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003048 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003049 elif dif < 0:
3050 opb = opb[-context.prec:]
3051 return opa, opb
3052
3053 def logical_and(self, other, context=None):
3054 """Applies an 'and' operation between self and other's digits."""
3055 if context is None:
3056 context = getcontext()
3057 if not self._islogical() or not other._islogical():
3058 return context._raise_error(InvalidOperation)
3059
3060 # fill to context.prec
3061 (opa, opb) = self._fill_logical(context, self._int, other._int)
3062
3063 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003064 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3065 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003066
3067 def logical_invert(self, context=None):
3068 """Invert all its digits."""
3069 if context is None:
3070 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003071 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3072 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003073
3074 def logical_or(self, other, context=None):
3075 """Applies an 'or' operation between self and other's digits."""
3076 if context is None:
3077 context = getcontext()
3078 if not self._islogical() or not other._islogical():
3079 return context._raise_error(InvalidOperation)
3080
3081 # fill to context.prec
3082 (opa, opb) = self._fill_logical(context, self._int, other._int)
3083
3084 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003085 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3086 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003087
3088 def logical_xor(self, other, context=None):
3089 """Applies an 'xor' operation between self and other's digits."""
3090 if context is None:
3091 context = getcontext()
3092 if not self._islogical() or not other._islogical():
3093 return context._raise_error(InvalidOperation)
3094
3095 # fill to context.prec
3096 (opa, opb) = self._fill_logical(context, self._int, other._int)
3097
3098 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003099 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3100 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003101
3102 def max_mag(self, other, context=None):
3103 """Compares the values numerically with their sign ignored."""
3104 other = _convert_other(other, raiseit=True)
3105
3106 if context is None:
3107 context = getcontext()
3108
3109 if self._is_special or other._is_special:
3110 # If one operand is a quiet NaN and the other is number, then the
3111 # number is always returned
3112 sn = self._isnan()
3113 on = other._isnan()
3114 if sn or on:
3115 if on == 1 and sn != 2:
3116 return self._fix_nan(context)
3117 if sn == 1 and on != 2:
3118 return other._fix_nan(context)
3119 return self._check_nans(other, context)
3120
3121 c = self.copy_abs().__cmp__(other.copy_abs())
3122 if c == 0:
3123 c = self.compare_total(other)
3124
3125 if c == -1:
3126 ans = other
3127 else:
3128 ans = self
3129
3130 if context._rounding_decision == ALWAYS_ROUND:
3131 return ans._fix(context)
3132 return ans
3133
3134 def min_mag(self, other, context=None):
3135 """Compares the values numerically with their sign ignored."""
3136 other = _convert_other(other, raiseit=True)
3137
3138 if context is None:
3139 context = getcontext()
3140
3141 if self._is_special or other._is_special:
3142 # If one operand is a quiet NaN and the other is number, then the
3143 # number is always returned
3144 sn = self._isnan()
3145 on = other._isnan()
3146 if sn or on:
3147 if on == 1 and sn != 2:
3148 return self._fix_nan(context)
3149 if sn == 1 and on != 2:
3150 return other._fix_nan(context)
3151 return self._check_nans(other, context)
3152
3153 c = self.copy_abs().__cmp__(other.copy_abs())
3154 if c == 0:
3155 c = self.compare_total(other)
3156
3157 if c == -1:
3158 ans = self
3159 else:
3160 ans = other
3161
3162 if context._rounding_decision == ALWAYS_ROUND:
3163 return ans._fix(context)
3164 return ans
3165
3166 def next_minus(self, context=None):
3167 """Returns the largest representable number smaller than itself."""
3168 if context is None:
3169 context = getcontext()
3170
3171 ans = self._check_nans(context=context)
3172 if ans:
3173 return ans
3174
3175 if self._isinfinity() == -1:
3176 return negInf
3177 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003178 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003179
3180 context = context.copy()
3181 context._set_rounding(ROUND_FLOOR)
3182 context._ignore_all_flags()
3183 new_self = self._fix(context)
3184 if new_self != self:
3185 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003186 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3187 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003188
3189 def next_plus(self, context=None):
3190 """Returns the smallest representable number larger than itself."""
3191 if context is None:
3192 context = getcontext()
3193
3194 ans = self._check_nans(context=context)
3195 if ans:
3196 return ans
3197
3198 if self._isinfinity() == 1:
3199 return Inf
3200 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003201 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003202
3203 context = context.copy()
3204 context._set_rounding(ROUND_CEILING)
3205 context._ignore_all_flags()
3206 new_self = self._fix(context)
3207 if new_self != self:
3208 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003209 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3210 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003211
3212 def next_toward(self, other, context=None):
3213 """Returns the number closest to self, in the direction towards other.
3214
3215 The result is the closest representable number to self
3216 (excluding self) that is in the direction towards other,
3217 unless both have the same value. If the two operands are
3218 numerically equal, then the result is a copy of self with the
3219 sign set to be the same as the sign of other.
3220 """
3221 other = _convert_other(other, raiseit=True)
3222
3223 if context is None:
3224 context = getcontext()
3225
3226 ans = self._check_nans(other, context)
3227 if ans:
3228 return ans
3229
3230 comparison = self.__cmp__(other)
3231 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003232 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003233
3234 if comparison == -1:
3235 ans = self.next_plus(context)
3236 else: # comparison == 1
3237 ans = self.next_minus(context)
3238
3239 # decide which flags to raise using value of ans
3240 if ans._isinfinity():
3241 context._raise_error(Overflow,
3242 'Infinite result from next_toward',
3243 ans._sign)
3244 context._raise_error(Rounded)
3245 context._raise_error(Inexact)
3246 elif ans.adjusted() < context.Emin:
3247 context._raise_error(Underflow)
3248 context._raise_error(Subnormal)
3249 context._raise_error(Rounded)
3250 context._raise_error(Inexact)
3251 # if precision == 1 then we don't raise Clamped for a
3252 # result 0E-Etiny.
3253 if not ans:
3254 context._raise_error(Clamped)
3255
3256 return ans
3257
3258 def number_class(self, context=None):
3259 """Returns an indication of the class of self.
3260
3261 The class is one of the following strings:
3262 -sNaN
3263 -NaN
3264 -Infinity
3265 -Normal
3266 -Subnormal
3267 -Zero
3268 +Zero
3269 +Subnormal
3270 +Normal
3271 +Infinity
3272 """
3273 if self.is_snan():
3274 return "sNaN"
3275 if self.is_qnan():
3276 return "NaN"
3277 inf = self._isinfinity()
3278 if inf == 1:
3279 return "+Infinity"
3280 if inf == -1:
3281 return "-Infinity"
3282 if self.is_zero():
3283 if self._sign:
3284 return "-Zero"
3285 else:
3286 return "+Zero"
3287 if context is None:
3288 context = getcontext()
3289 if self.is_subnormal(context=context):
3290 if self._sign:
3291 return "-Subnormal"
3292 else:
3293 return "+Subnormal"
3294 # just a normal, regular, boring number, :)
3295 if self._sign:
3296 return "-Normal"
3297 else:
3298 return "+Normal"
3299
3300 def radix(self):
3301 """Just returns 10, as this is Decimal, :)"""
3302 return Decimal(10)
3303
3304 def rotate(self, other, context=None):
3305 """Returns a rotated copy of self, value-of-other times."""
3306 if context is None:
3307 context = getcontext()
3308
3309 ans = self._check_nans(other, context)
3310 if ans:
3311 return ans
3312
3313 if other._exp != 0:
3314 return context._raise_error(InvalidOperation)
3315 if not (-context.prec <= int(other) <= context.prec):
3316 return context._raise_error(InvalidOperation)
3317
3318 if self._isinfinity():
3319 return Decimal(self)
3320
3321 # get values, pad if necessary
3322 torot = int(other)
3323 rotdig = self._int
3324 topad = context.prec - len(rotdig)
3325 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003326 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003327
3328 # let's rotate!
3329 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003330 return _dec_from_triple(self._sign,
3331 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003332
3333 def scaleb (self, other, context=None):
3334 """Returns self operand after adding the second value to its exp."""
3335 if context is None:
3336 context = getcontext()
3337
3338 ans = self._check_nans(other, context)
3339 if ans:
3340 return ans
3341
3342 if other._exp != 0:
3343 return context._raise_error(InvalidOperation)
3344 liminf = -2 * (context.Emax + context.prec)
3345 limsup = 2 * (context.Emax + context.prec)
3346 if not (liminf <= int(other) <= limsup):
3347 return context._raise_error(InvalidOperation)
3348
3349 if self._isinfinity():
3350 return Decimal(self)
3351
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003352 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003353 d = d._fix(context)
3354 return d
3355
3356 def shift(self, other, context=None):
3357 """Returns a shifted copy of self, value-of-other times."""
3358 if context is None:
3359 context = getcontext()
3360
3361 ans = self._check_nans(other, context)
3362 if ans:
3363 return ans
3364
3365 if other._exp != 0:
3366 return context._raise_error(InvalidOperation)
3367 if not (-context.prec <= int(other) <= context.prec):
3368 return context._raise_error(InvalidOperation)
3369
3370 if self._isinfinity():
3371 return Decimal(self)
3372
3373 # get values, pad if necessary
3374 torot = int(other)
3375 if not torot:
3376 return Decimal(self)
3377 rotdig = self._int
3378 topad = context.prec - len(rotdig)
3379 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003380 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003381
3382 # let's shift!
3383 if torot < 0:
3384 rotated = rotdig[:torot]
3385 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003386 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003387 rotated = rotated[-context.prec:]
3388
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003389 return _dec_from_triple(self._sign,
3390 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003391
Guido van Rossumd8faa362007-04-27 19:54:29 +00003392 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003393 def __reduce__(self):
3394 return (self.__class__, (str(self),))
3395
3396 def __copy__(self):
3397 if type(self) == Decimal:
3398 return self # I'm immutable; therefore I am my own clone
3399 return self.__class__(str(self))
3400
3401 def __deepcopy__(self, memo):
3402 if type(self) == Decimal:
3403 return self # My components are also immutable
3404 return self.__class__(str(self))
3405
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003406def _dec_from_triple(sign, coefficient, exponent, special=False):
3407 """Create a decimal instance directly, without any validation,
3408 normalization (e.g. removal of leading zeros) or argument
3409 conversion.
3410
3411 This function is for *internal use only*.
3412 """
3413
3414 self = object.__new__(Decimal)
3415 self._sign = sign
3416 self._int = coefficient
3417 self._exp = exponent
3418 self._is_special = special
3419
3420 return self
3421
Guido van Rossumd8faa362007-04-27 19:54:29 +00003422##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003423
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003424
3425# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003426rounding_functions = [name for name in Decimal.__dict__.keys()
3427 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003428for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003429 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003430 globalname = name[1:].upper()
3431 val = globals()[globalname]
3432 Decimal._pick_rounding_function[val] = name
3433
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003434del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003435
Thomas Wouters89f507f2006-12-13 04:49:30 +00003436class _ContextManager(object):
3437 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003438
Thomas Wouters89f507f2006-12-13 04:49:30 +00003439 Sets a copy of the supplied context in __enter__() and restores
3440 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003441 """
3442 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003443 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003444 def __enter__(self):
3445 self.saved_context = getcontext()
3446 setcontext(self.new_context)
3447 return self.new_context
3448 def __exit__(self, t, v, tb):
3449 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003450
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003451class Context(object):
3452 """Contains the context for a Decimal instance.
3453
3454 Contains:
3455 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003456 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003457 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003458 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003459 raised when it is caused. Otherwise, a value is
3460 substituted in.
3461 flags - When an exception is caused, flags[exception] is incremented.
3462 (Whether or not the trap_enabler is set)
3463 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003464 Emin - Minimum exponent
3465 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003466 capitals - If 1, 1*10^1 is printed as 1E+1.
3467 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003468 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003469 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003470
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003471 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003472 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003473 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003474 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003475 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003476 _ignored_flags=None):
3477 if flags is None:
3478 flags = []
3479 if _ignored_flags is None:
3480 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003481 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003482 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003483 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003484 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003485 for name, val in locals().items():
3486 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003487 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003488 else:
3489 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003490 del self.self
3491
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003492 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003493 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003494 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003495 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3496 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3497 % vars(self))
3498 names = [f.__name__ for f, v in self.flags.items() if v]
3499 s.append('flags=[' + ', '.join(names) + ']')
3500 names = [t.__name__ for t, v in self.traps.items() if v]
3501 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003502 return ', '.join(s) + ')'
3503
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003504 def clear_flags(self):
3505 """Reset all flags to zero"""
3506 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003507 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003508
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003509 def _shallow_copy(self):
3510 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003511 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003512 self._rounding_decision, self.Emin, self.Emax,
3513 self.capitals, self._clamp, self._ignored_flags)
3514 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003515
3516 def copy(self):
3517 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003518 nc = Context(self.prec, self.rounding, self.traps.copy(),
3519 self.flags.copy(), self._rounding_decision, self.Emin,
3520 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003521 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003522 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003523
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003524 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003525 """Handles an error
3526
3527 If the flag is in _ignored_flags, returns the default response.
3528 Otherwise, it increments the flag, then, if the corresponding
3529 trap_enabler is set, it reaises the exception. Otherwise, it returns
3530 the default value after incrementing the flag.
3531 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003532 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003533 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003534 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003535 return error().handle(self, *args)
3536
3537 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003538 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003539 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003540 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003541
3542 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003543 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003544 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003545
3546 def _ignore_all_flags(self):
3547 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003548 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003549
3550 def _ignore_flags(self, *flags):
3551 """Ignore the flags, if they are raised"""
3552 # Do not mutate-- This way, copies of a context leave the original
3553 # alone.
3554 self._ignored_flags = (self._ignored_flags + list(flags))
3555 return list(flags)
3556
3557 def _regard_flags(self, *flags):
3558 """Stop ignoring the flags, if they are raised"""
3559 if flags and isinstance(flags[0], (tuple,list)):
3560 flags = flags[0]
3561 for flag in flags:
3562 self._ignored_flags.remove(flag)
3563
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003564 def __hash__(self):
3565 """A Context cannot be hashed."""
3566 # We inherit object.__hash__, so we must deny this explicitly
Guido van Rossumd8faa362007-04-27 19:54:29 +00003567 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003568
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003569 def Etiny(self):
3570 """Returns Etiny (= Emin - prec + 1)"""
3571 return int(self.Emin - self.prec + 1)
3572
3573 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003574 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003575 return int(self.Emax - self.prec + 1)
3576
3577 def _set_rounding_decision(self, type):
3578 """Sets the rounding decision.
3579
3580 Sets the rounding decision, and returns the current (previous)
3581 rounding decision. Often used like:
3582
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003583 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003584 # That so you don't change the calling context
3585 # if an error occurs in the middle (say DivisionImpossible is raised).
3586
3587 rounding = context._set_rounding_decision(NEVER_ROUND)
3588 instance = instance / Decimal(2)
3589 context._set_rounding_decision(rounding)
3590
3591 This will make it not round for that operation.
3592 """
3593
3594 rounding = self._rounding_decision
3595 self._rounding_decision = type
3596 return rounding
3597
3598 def _set_rounding(self, type):
3599 """Sets the rounding type.
3600
3601 Sets the rounding type, and returns the current (previous)
3602 rounding type. Often used like:
3603
3604 context = context.copy()
3605 # so you don't change the calling context
3606 # if an error occurs in the middle.
3607 rounding = context._set_rounding(ROUND_UP)
3608 val = self.__sub__(other, context=context)
3609 context._set_rounding(rounding)
3610
3611 This will make it round up for that operation.
3612 """
3613 rounding = self.rounding
3614 self.rounding= type
3615 return rounding
3616
Raymond Hettingerfed52962004-07-14 15:41:57 +00003617 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003618 """Creates a new Decimal instance but using self as context."""
3619 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003620 if d._isnan() and len(d._int) > self.prec - self._clamp:
3621 return self._raise_error(ConversionSyntax,
3622 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003623 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003624
Guido van Rossumd8faa362007-04-27 19:54:29 +00003625 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003626 def abs(self, a):
3627 """Returns the absolute value of the operand.
3628
3629 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003630 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003631 the plus operation on the operand.
3632
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003633 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003634 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003635 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003636 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003637 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003638 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003639 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003640 Decimal("101.5")
3641 """
3642 return a.__abs__(context=self)
3643
3644 def add(self, a, b):
3645 """Return the sum of the two operands.
3646
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003647 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003648 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003649 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003650 Decimal("1.02E+4")
3651 """
3652 return a.__add__(b, context=self)
3653
3654 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003655 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003656
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003657 def canonical(self, a):
3658 """Returns the same Decimal object.
3659
3660 As we do not have different encodings for the same number, the
3661 received object already is in its canonical form.
3662
3663 >>> ExtendedContext.canonical(Decimal('2.50'))
3664 Decimal("2.50")
3665 """
3666 return a.canonical(context=self)
3667
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003668 def compare(self, a, b):
3669 """Compares values numerically.
3670
3671 If the signs of the operands differ, a value representing each operand
3672 ('-1' if the operand is less than zero, '0' if the operand is zero or
3673 negative zero, or '1' if the operand is greater than zero) is used in
3674 place of that operand for the comparison instead of the actual
3675 operand.
3676
3677 The comparison is then effected by subtracting the second operand from
3678 the first and then returning a value according to the result of the
3679 subtraction: '-1' if the result is less than zero, '0' if the result is
3680 zero or negative zero, or '1' if the result is greater than zero.
3681
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003682 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003683 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003684 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003685 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003686 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003687 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003688 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003689 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003690 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003691 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003692 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003693 Decimal("-1")
3694 """
3695 return a.compare(b, context=self)
3696
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003697 def compare_signal(self, a, b):
3698 """Compares the values of the two operands numerically.
3699
3700 It's pretty much like compare(), but all NaNs signal, with signaling
3701 NaNs taking precedence over quiet NaNs.
3702
3703 >>> c = ExtendedContext
3704 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3705 Decimal("-1")
3706 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3707 Decimal("0")
3708 >>> c.flags[InvalidOperation] = 0
3709 >>> print(c.flags[InvalidOperation])
3710 0
3711 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3712 Decimal("NaN")
3713 >>> print(c.flags[InvalidOperation])
3714 1
3715 >>> c.flags[InvalidOperation] = 0
3716 >>> print(c.flags[InvalidOperation])
3717 0
3718 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3719 Decimal("NaN")
3720 >>> print(c.flags[InvalidOperation])
3721 1
3722 """
3723 return a.compare_signal(b, context=self)
3724
3725 def compare_total(self, a, b):
3726 """Compares two operands using their abstract representation.
3727
3728 This is not like the standard compare, which use their numerical
3729 value. Note that a total ordering is defined for all possible abstract
3730 representations.
3731
3732 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3733 Decimal("-1")
3734 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3735 Decimal("-1")
3736 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3737 Decimal("-1")
3738 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3739 Decimal("0")
3740 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3741 Decimal("1")
3742 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3743 Decimal("-1")
3744 """
3745 return a.compare_total(b)
3746
3747 def compare_total_mag(self, a, b):
3748 """Compares two operands using their abstract representation ignoring sign.
3749
3750 Like compare_total, but with operand's sign ignored and assumed to be 0.
3751 """
3752 return a.compare_total_mag(b)
3753
3754 def copy_abs(self, a):
3755 """Returns a copy of the operand with the sign set to 0.
3756
3757 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3758 Decimal("2.1")
3759 >>> ExtendedContext.copy_abs(Decimal('-100'))
3760 Decimal("100")
3761 """
3762 return a.copy_abs()
3763
3764 def copy_decimal(self, a):
3765 """Returns a copy of the decimal objet.
3766
3767 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3768 Decimal("2.1")
3769 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3770 Decimal("-1.00")
3771 """
3772 return Decimal(a)
3773
3774 def copy_negate(self, a):
3775 """Returns a copy of the operand with the sign inverted.
3776
3777 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3778 Decimal("-101.5")
3779 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3780 Decimal("101.5")
3781 """
3782 return a.copy_negate()
3783
3784 def copy_sign(self, a, b):
3785 """Copies the second operand's sign to the first one.
3786
3787 In detail, it returns a copy of the first operand with the sign
3788 equal to the sign of the second operand.
3789
3790 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3791 Decimal("1.50")
3792 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3793 Decimal("1.50")
3794 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3795 Decimal("-1.50")
3796 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3797 Decimal("-1.50")
3798 """
3799 return a.copy_sign(b)
3800
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003801 def divide(self, a, b):
3802 """Decimal division in a specified context.
3803
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003804 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003805 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003806 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003807 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003808 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003809 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003810 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003811 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003812 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003813 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003814 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003815 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003816 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003817 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003818 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003819 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003820 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003821 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003822 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003823 Decimal("1.20E+6")
3824 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003825 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003826
3827 def divide_int(self, a, b):
3828 """Divides two numbers and returns the integer part of the result.
3829
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003830 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003831 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003832 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003833 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003834 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003835 Decimal("3")
3836 """
3837 return a.__floordiv__(b, context=self)
3838
3839 def divmod(self, a, b):
3840 return a.__divmod__(b, context=self)
3841
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003842 def exp(self, a):
3843 """Returns e ** a.
3844
3845 >>> c = ExtendedContext.copy()
3846 >>> c.Emin = -999
3847 >>> c.Emax = 999
3848 >>> c.exp(Decimal('-Infinity'))
3849 Decimal("0")
3850 >>> c.exp(Decimal('-1'))
3851 Decimal("0.367879441")
3852 >>> c.exp(Decimal('0'))
3853 Decimal("1")
3854 >>> c.exp(Decimal('1'))
3855 Decimal("2.71828183")
3856 >>> c.exp(Decimal('0.693147181'))
3857 Decimal("2.00000000")
3858 >>> c.exp(Decimal('+Infinity'))
3859 Decimal("Infinity")
3860 """
3861 return a.exp(context=self)
3862
3863 def fma(self, a, b, c):
3864 """Returns a multiplied by b, plus c.
3865
3866 The first two operands are multiplied together, using multiply,
3867 the third operand is then added to the result of that
3868 multiplication, using add, all with only one final rounding.
3869
3870 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3871 Decimal("22")
3872 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3873 Decimal("-8")
3874 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3875 Decimal("1.38435736E+12")
3876 """
3877 return a.fma(b, c, context=self)
3878
3879 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003880 """Return True if the operand is canonical; otherwise return False.
3881
3882 Currently, the encoding of a Decimal instance is always
3883 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003884
3885 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003886 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003887 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003888 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003889
3890 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003891 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003892
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003893 A Decimal instance is considered finite if it is neither
3894 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003895
3896 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003897 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003898 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003899 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003900 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003901 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003902 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003903 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003904 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003905 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003906 """
3907 return a.is_finite()
3908
3909 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003910 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003911
3912 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003913 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003914 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003915 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003916 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003917 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003918 """
3919 return a.is_infinite()
3920
3921 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003922 """Return True if the operand is a qNaN or sNaN;
3923 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003924
3925 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003926 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003927 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003928 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003929 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003930 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003931 """
3932 return a.is_nan()
3933
3934 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003935 """Return True if the operand is a normal number;
3936 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003937
3938 >>> c = ExtendedContext.copy()
3939 >>> c.Emin = -999
3940 >>> c.Emax = 999
3941 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003942 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003943 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003944 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003945 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003946 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003947 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003948 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003949 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003950 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003951 """
3952 return a.is_normal(context=self)
3953
3954 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003955 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003956
3957 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003958 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003959 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003960 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003961 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003962 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003963 """
3964 return a.is_qnan()
3965
3966 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003967 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003968
3969 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003970 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003971 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003972 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003973 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003974 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003975 """
3976 return a.is_signed()
3977
3978 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003979 """Return True if the operand is a signaling NaN;
3980 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003981
3982 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003983 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003984 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003985 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003986 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003987 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003988 """
3989 return a.is_snan()
3990
3991 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003992 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003993
3994 >>> c = ExtendedContext.copy()
3995 >>> c.Emin = -999
3996 >>> c.Emax = 999
3997 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003998 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003999 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004000 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004001 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004002 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004003 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004004 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004005 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004006 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004007 """
4008 return a.is_subnormal(context=self)
4009
4010 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004011 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004012
4013 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004014 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004015 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004016 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004017 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004018 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004019 """
4020 return a.is_zero()
4021
4022 def ln(self, a):
4023 """Returns the natural (base e) logarithm of the operand.
4024
4025 >>> c = ExtendedContext.copy()
4026 >>> c.Emin = -999
4027 >>> c.Emax = 999
4028 >>> c.ln(Decimal('0'))
4029 Decimal("-Infinity")
4030 >>> c.ln(Decimal('1.000'))
4031 Decimal("0")
4032 >>> c.ln(Decimal('2.71828183'))
4033 Decimal("1.00000000")
4034 >>> c.ln(Decimal('10'))
4035 Decimal("2.30258509")
4036 >>> c.ln(Decimal('+Infinity'))
4037 Decimal("Infinity")
4038 """
4039 return a.ln(context=self)
4040
4041 def log10(self, a):
4042 """Returns the base 10 logarithm of the operand.
4043
4044 >>> c = ExtendedContext.copy()
4045 >>> c.Emin = -999
4046 >>> c.Emax = 999
4047 >>> c.log10(Decimal('0'))
4048 Decimal("-Infinity")
4049 >>> c.log10(Decimal('0.001'))
4050 Decimal("-3")
4051 >>> c.log10(Decimal('1.000'))
4052 Decimal("0")
4053 >>> c.log10(Decimal('2'))
4054 Decimal("0.301029996")
4055 >>> c.log10(Decimal('10'))
4056 Decimal("1")
4057 >>> c.log10(Decimal('70'))
4058 Decimal("1.84509804")
4059 >>> c.log10(Decimal('+Infinity'))
4060 Decimal("Infinity")
4061 """
4062 return a.log10(context=self)
4063
4064 def logb(self, a):
4065 """ Returns the exponent of the magnitude of the operand's MSD.
4066
4067 The result is the integer which is the exponent of the magnitude
4068 of the most significant digit of the operand (as though the
4069 operand were truncated to a single digit while maintaining the
4070 value of that digit and without limiting the resulting exponent).
4071
4072 >>> ExtendedContext.logb(Decimal('250'))
4073 Decimal("2")
4074 >>> ExtendedContext.logb(Decimal('2.50'))
4075 Decimal("0")
4076 >>> ExtendedContext.logb(Decimal('0.03'))
4077 Decimal("-2")
4078 >>> ExtendedContext.logb(Decimal('0'))
4079 Decimal("-Infinity")
4080 """
4081 return a.logb(context=self)
4082
4083 def logical_and(self, a, b):
4084 """Applies the logical operation 'and' between each operand's digits.
4085
4086 The operands must be both logical numbers.
4087
4088 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4089 Decimal("0")
4090 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4091 Decimal("0")
4092 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4093 Decimal("0")
4094 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4095 Decimal("1")
4096 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4097 Decimal("1000")
4098 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4099 Decimal("10")
4100 """
4101 return a.logical_and(b, context=self)
4102
4103 def logical_invert(self, a):
4104 """Invert all the digits in the operand.
4105
4106 The operand must be a logical number.
4107
4108 >>> ExtendedContext.logical_invert(Decimal('0'))
4109 Decimal("111111111")
4110 >>> ExtendedContext.logical_invert(Decimal('1'))
4111 Decimal("111111110")
4112 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4113 Decimal("0")
4114 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4115 Decimal("10101010")
4116 """
4117 return a.logical_invert(context=self)
4118
4119 def logical_or(self, a, b):
4120 """Applies the logical operation 'or' between each operand's digits.
4121
4122 The operands must be both logical numbers.
4123
4124 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4125 Decimal("0")
4126 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4127 Decimal("1")
4128 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4129 Decimal("1")
4130 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4131 Decimal("1")
4132 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4133 Decimal("1110")
4134 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4135 Decimal("1110")
4136 """
4137 return a.logical_or(b, context=self)
4138
4139 def logical_xor(self, a, b):
4140 """Applies the logical operation 'xor' between each operand's digits.
4141
4142 The operands must be both logical numbers.
4143
4144 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4145 Decimal("0")
4146 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4147 Decimal("1")
4148 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4149 Decimal("1")
4150 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4151 Decimal("0")
4152 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4153 Decimal("110")
4154 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4155 Decimal("1101")
4156 """
4157 return a.logical_xor(b, context=self)
4158
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004159 def max(self, a,b):
4160 """max compares two values numerically and returns the maximum.
4161
4162 If either operand is a NaN then the general rules apply.
4163 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004164 operation. If they are numerically equal then the left-hand operand
4165 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004166 infinity) of the two operands is chosen as the result.
4167
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004168 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004169 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004170 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004171 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004172 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004173 Decimal("1")
4174 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4175 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004176 """
4177 return a.max(b, context=self)
4178
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004179 def max_mag(self, a, b):
4180 """Compares the values numerically with their sign ignored."""
4181 return a.max_mag(b, context=self)
4182
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004183 def min(self, a,b):
4184 """min compares two values numerically and returns the minimum.
4185
4186 If either operand is a NaN then the general rules apply.
4187 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004188 operation. If they are numerically equal then the left-hand operand
4189 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004190 infinity) of the two operands is chosen as the result.
4191
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004192 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004193 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004194 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004195 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004196 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004197 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004198 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4199 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004200 """
4201 return a.min(b, context=self)
4202
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004203 def min_mag(self, a, b):
4204 """Compares the values numerically with their sign ignored."""
4205 return a.min_mag(b, context=self)
4206
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004207 def minus(self, a):
4208 """Minus corresponds to unary prefix minus in Python.
4209
4210 The operation is evaluated using the same rules as subtract; the
4211 operation minus(a) is calculated as subtract('0', a) where the '0'
4212 has the same exponent as the operand.
4213
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004214 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004215 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004216 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004217 Decimal("1.3")
4218 """
4219 return a.__neg__(context=self)
4220
4221 def multiply(self, a, b):
4222 """multiply multiplies two operands.
4223
4224 If either operand is a special value then the general rules apply.
4225 Otherwise, the operands are multiplied together ('long multiplication'),
4226 resulting in a number which may be as long as the sum of the lengths
4227 of the two operands.
4228
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004229 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004230 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004231 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004232 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004233 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004234 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004235 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004236 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004237 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004238 Decimal("4.28135971E+11")
4239 """
4240 return a.__mul__(b, context=self)
4241
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004242 def next_minus(self, a):
4243 """Returns the largest representable number smaller than a.
4244
4245 >>> c = ExtendedContext.copy()
4246 >>> c.Emin = -999
4247 >>> c.Emax = 999
4248 >>> ExtendedContext.next_minus(Decimal('1'))
4249 Decimal("0.999999999")
4250 >>> c.next_minus(Decimal('1E-1007'))
4251 Decimal("0E-1007")
4252 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4253 Decimal("-1.00000004")
4254 >>> c.next_minus(Decimal('Infinity'))
4255 Decimal("9.99999999E+999")
4256 """
4257 return a.next_minus(context=self)
4258
4259 def next_plus(self, a):
4260 """Returns the smallest representable number larger than a.
4261
4262 >>> c = ExtendedContext.copy()
4263 >>> c.Emin = -999
4264 >>> c.Emax = 999
4265 >>> ExtendedContext.next_plus(Decimal('1'))
4266 Decimal("1.00000001")
4267 >>> c.next_plus(Decimal('-1E-1007'))
4268 Decimal("-0E-1007")
4269 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4270 Decimal("-1.00000002")
4271 >>> c.next_plus(Decimal('-Infinity'))
4272 Decimal("-9.99999999E+999")
4273 """
4274 return a.next_plus(context=self)
4275
4276 def next_toward(self, a, b):
4277 """Returns the number closest to a, in direction towards b.
4278
4279 The result is the closest representable number from the first
4280 operand (but not the first operand) that is in the direction
4281 towards the second operand, unless the operands have the same
4282 value.
4283
4284 >>> c = ExtendedContext.copy()
4285 >>> c.Emin = -999
4286 >>> c.Emax = 999
4287 >>> c.next_toward(Decimal('1'), Decimal('2'))
4288 Decimal("1.00000001")
4289 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4290 Decimal("-0E-1007")
4291 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4292 Decimal("-1.00000002")
4293 >>> c.next_toward(Decimal('1'), Decimal('0'))
4294 Decimal("0.999999999")
4295 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4296 Decimal("0E-1007")
4297 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4298 Decimal("-1.00000004")
4299 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4300 Decimal("-0.00")
4301 """
4302 return a.next_toward(b, context=self)
4303
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004304 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004305 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004306
4307 Essentially a plus operation with all trailing zeros removed from the
4308 result.
4309
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004310 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004311 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004312 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004313 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004314 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004315 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004316 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004317 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004318 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004319 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004320 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004321 Decimal("0")
4322 """
4323 return a.normalize(context=self)
4324
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004325 def number_class(self, a):
4326 """Returns an indication of the class of the operand.
4327
4328 The class is one of the following strings:
4329 -sNaN
4330 -NaN
4331 -Infinity
4332 -Normal
4333 -Subnormal
4334 -Zero
4335 +Zero
4336 +Subnormal
4337 +Normal
4338 +Infinity
4339
4340 >>> c = Context(ExtendedContext)
4341 >>> c.Emin = -999
4342 >>> c.Emax = 999
4343 >>> c.number_class(Decimal('Infinity'))
4344 '+Infinity'
4345 >>> c.number_class(Decimal('1E-10'))
4346 '+Normal'
4347 >>> c.number_class(Decimal('2.50'))
4348 '+Normal'
4349 >>> c.number_class(Decimal('0.1E-999'))
4350 '+Subnormal'
4351 >>> c.number_class(Decimal('0'))
4352 '+Zero'
4353 >>> c.number_class(Decimal('-0'))
4354 '-Zero'
4355 >>> c.number_class(Decimal('-0.1E-999'))
4356 '-Subnormal'
4357 >>> c.number_class(Decimal('-1E-10'))
4358 '-Normal'
4359 >>> c.number_class(Decimal('-2.50'))
4360 '-Normal'
4361 >>> c.number_class(Decimal('-Infinity'))
4362 '-Infinity'
4363 >>> c.number_class(Decimal('NaN'))
4364 'NaN'
4365 >>> c.number_class(Decimal('-NaN'))
4366 'NaN'
4367 >>> c.number_class(Decimal('sNaN'))
4368 'sNaN'
4369 """
4370 return a.number_class(context=self)
4371
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004372 def plus(self, a):
4373 """Plus corresponds to unary prefix plus in Python.
4374
4375 The operation is evaluated using the same rules as add; the
4376 operation plus(a) is calculated as add('0', a) where the '0'
4377 has the same exponent as the operand.
4378
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004379 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004380 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004381 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004382 Decimal("-1.3")
4383 """
4384 return a.__pos__(context=self)
4385
4386 def power(self, a, b, modulo=None):
4387 """Raises a to the power of b, to modulo if given.
4388
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004389 With two arguments, compute a**b. If a is negative then b
4390 must be integral. The result will be inexact unless b is
4391 integral and the result is finite and can be expressed exactly
4392 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004393
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004394 With three arguments, compute (a**b) % modulo. For the
4395 three argument form, the following restrictions on the
4396 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004397
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004398 - all three arguments must be integral
4399 - b must be nonnegative
4400 - at least one of a or b must be nonzero
4401 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004402
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004403 The result of pow(a, b, modulo) is identical to the result
4404 that would be obtained by computing (a**b) % modulo with
4405 unbounded precision, but is computed more efficiently. It is
4406 always exact.
4407
4408 >>> c = ExtendedContext.copy()
4409 >>> c.Emin = -999
4410 >>> c.Emax = 999
4411 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004412 Decimal("8")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004413 >>> c.power(Decimal('-2'), Decimal('3'))
4414 Decimal("-8")
4415 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004416 Decimal("0.125")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004417 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004418 Decimal("69.7575744")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004419 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4420 Decimal("2.00000000")
4421 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004422 Decimal("0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004423 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004424 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004425 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004426 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004427 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004428 Decimal("-0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004429 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004430 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004431 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004432 Decimal("-Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004433 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004434 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004435 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004436 Decimal("NaN")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004437
4438 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4439 Decimal("11")
4440 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4441 Decimal("-11")
4442 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4443 Decimal("1")
4444 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4445 Decimal("11")
4446 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4447 Decimal("11729830")
4448 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4449 Decimal("-0")
4450 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4451 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004452 """
4453 return a.__pow__(b, modulo, context=self)
4454
4455 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004456 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004457
4458 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004459 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004460 exponent is being increased), multiplied by a positive power of ten (if
4461 the exponent is being decreased), or is unchanged (if the exponent is
4462 already equal to that of the right-hand operand).
4463
4464 Unlike other operations, if the length of the coefficient after the
4465 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004466 operation condition is raised. This guarantees that, unless there is
4467 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004468 equal to that of the right-hand operand.
4469
4470 Also unlike other operations, quantize will never raise Underflow, even
4471 if the result is subnormal and inexact.
4472
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004473 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004474 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004475 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004476 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004477 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004478 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004479 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004480 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004481 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004482 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004483 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004484 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004485 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004486 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004487 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004488 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004489 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004490 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004491 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004492 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004493 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004494 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004495 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004496 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004497 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004498 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004499 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004500 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004501 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004502 Decimal("2E+2")
4503 """
4504 return a.quantize(b, context=self)
4505
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004506 def radix(self):
4507 """Just returns 10, as this is Decimal, :)
4508
4509 >>> ExtendedContext.radix()
4510 Decimal("10")
4511 """
4512 return Decimal(10)
4513
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004514 def remainder(self, a, b):
4515 """Returns the remainder from integer division.
4516
4517 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004518 calculating integer division as described for divide-integer, rounded
4519 to precision digits if necessary. The sign of the result, if
4520 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004521
4522 This operation will fail under the same conditions as integer division
4523 (that is, if integer division on the same two operands would fail, the
4524 remainder cannot be calculated).
4525
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004526 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004527 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004528 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004529 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004530 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004531 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004532 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004533 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004534 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004535 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004536 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004537 Decimal("1.0")
4538 """
4539 return a.__mod__(b, context=self)
4540
4541 def remainder_near(self, a, b):
4542 """Returns to be "a - b * n", where n is the integer nearest the exact
4543 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004544 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004545 sign of a.
4546
4547 This operation will fail under the same conditions as integer division
4548 (that is, if integer division on the same two operands would fail, the
4549 remainder cannot be calculated).
4550
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004551 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004552 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004553 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004554 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004555 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004556 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004557 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004558 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004559 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004560 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004561 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004562 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004563 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004564 Decimal("-0.3")
4565 """
4566 return a.remainder_near(b, context=self)
4567
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004568 def rotate(self, a, b):
4569 """Returns a rotated copy of a, b times.
4570
4571 The coefficient of the result is a rotated copy of the digits in
4572 the coefficient of the first operand. The number of places of
4573 rotation is taken from the absolute value of the second operand,
4574 with the rotation being to the left if the second operand is
4575 positive or to the right otherwise.
4576
4577 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4578 Decimal("400000003")
4579 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4580 Decimal("12")
4581 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4582 Decimal("891234567")
4583 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4584 Decimal("123456789")
4585 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4586 Decimal("345678912")
4587 """
4588 return a.rotate(b, context=self)
4589
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004590 def same_quantum(self, a, b):
4591 """Returns True if the two operands have the same exponent.
4592
4593 The result is never affected by either the sign or the coefficient of
4594 either operand.
4595
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004596 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004597 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004598 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004599 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004600 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004601 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004602 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004603 True
4604 """
4605 return a.same_quantum(b)
4606
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004607 def scaleb (self, a, b):
4608 """Returns the first operand after adding the second value its exp.
4609
4610 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4611 Decimal("0.0750")
4612 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4613 Decimal("7.50")
4614 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4615 Decimal("7.50E+3")
4616 """
4617 return a.scaleb (b, context=self)
4618
4619 def shift(self, a, b):
4620 """Returns a shifted copy of a, b times.
4621
4622 The coefficient of the result is a shifted copy of the digits
4623 in the coefficient of the first operand. The number of places
4624 to shift is taken from the absolute value of the second operand,
4625 with the shift being to the left if the second operand is
4626 positive or to the right otherwise. Digits shifted into the
4627 coefficient are zeros.
4628
4629 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4630 Decimal("400000000")
4631 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4632 Decimal("0")
4633 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4634 Decimal("1234567")
4635 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4636 Decimal("123456789")
4637 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4638 Decimal("345678900")
4639 """
4640 return a.shift(b, context=self)
4641
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004642 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004643 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004644
4645 If the result must be inexact, it is rounded using the round-half-even
4646 algorithm.
4647
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004648 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004649 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004650 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004651 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004652 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004653 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004654 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004655 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004656 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004657 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004658 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004659 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004660 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004661 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004662 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004663 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004664 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004665 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004666 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004667 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004668 """
4669 return a.sqrt(context=self)
4670
4671 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004672 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004673
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004674 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004675 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004676 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004677 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004678 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004679 Decimal("-0.77")
4680 """
4681 return a.__sub__(b, context=self)
4682
4683 def to_eng_string(self, a):
4684 """Converts a number to a string, using scientific notation.
4685
4686 The operation is not affected by the context.
4687 """
4688 return a.to_eng_string(context=self)
4689
4690 def to_sci_string(self, a):
4691 """Converts a number to a string, using scientific notation.
4692
4693 The operation is not affected by the context.
4694 """
4695 return a.__str__(context=self)
4696
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004697 def to_integral_exact(self, a):
4698 """Rounds to an integer.
4699
4700 When the operand has a negative exponent, the result is the same
4701 as using the quantize() operation using the given operand as the
4702 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4703 of the operand as the precision setting; Inexact and Rounded flags
4704 are allowed in this operation. The rounding mode is taken from the
4705 context.
4706
4707 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4708 Decimal("2")
4709 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4710 Decimal("100")
4711 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4712 Decimal("100")
4713 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4714 Decimal("102")
4715 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4716 Decimal("-102")
4717 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4718 Decimal("1.0E+6")
4719 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4720 Decimal("7.89E+77")
4721 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4722 Decimal("-Infinity")
4723 """
4724 return a.to_integral_exact(context=self)
4725
4726 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004727 """Rounds to an integer.
4728
4729 When the operand has a negative exponent, the result is the same
4730 as using the quantize() operation using the given operand as the
4731 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4732 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004733 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004734
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004735 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004736 Decimal("2")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004737 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004738 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004739 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004740 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004741 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004742 Decimal("102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004743 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004744 Decimal("-102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004745 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004746 Decimal("1.0E+6")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004747 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004748 Decimal("7.89E+77")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004749 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004750 Decimal("-Infinity")
4751 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004752 return a.to_integral_value(context=self)
4753
4754 # the method name changed, but we provide also the old one, for compatibility
4755 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004756
4757class _WorkRep(object):
4758 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004759 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004760 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004761 # exp: None, int, or string
4762
4763 def __init__(self, value=None):
4764 if value is None:
4765 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004766 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004767 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004768 elif isinstance(value, Decimal):
4769 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00004770 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004771 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004772 else:
4773 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004774 self.sign = value[0]
4775 self.int = value[1]
4776 self.exp = value[2]
4777
4778 def __repr__(self):
4779 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4780
4781 __str__ = __repr__
4782
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004783
4784
4785def _normalize(op1, op2, shouldround = 0, prec = 0):
4786 """Normalizes op1, op2 to have the same exp and length of coefficient.
4787
4788 Done during addition.
4789 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004790 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004791 tmp = op2
4792 other = op1
4793 else:
4794 tmp = op1
4795 other = op2
4796
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004797 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4798 # Then adding 10**exp to tmp has the same effect (after rounding)
4799 # as adding any positive quantity smaller than 10**exp; similarly
4800 # for subtraction. So if other is smaller than 10**exp we replace
4801 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4802 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004803 tmp_len = len(str(tmp.int))
4804 other_len = len(str(other.int))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004805 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4806 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004807 other.int = 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004808 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004809
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004810 tmp.int *= 10 ** (tmp.exp - other.exp)
4811 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004812 return op1, op2
4813
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004814##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004815
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004816# This function from Tim Peters was taken from here:
4817# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4818# The correction being in the function definition is for speed, and
4819# the whole function is not resolved with math.log because of avoiding
4820# the use of floats.
4821def _nbits(n, correction = {
4822 '0': 4, '1': 3, '2': 2, '3': 2,
4823 '4': 1, '5': 1, '6': 1, '7': 1,
4824 '8': 0, '9': 0, 'a': 0, 'b': 0,
4825 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4826 """Number of bits in binary representation of the positive integer n,
4827 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004828 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004829 if n < 0:
4830 raise ValueError("The argument to _nbits should be nonnegative.")
4831 hex_n = "%x" % n
4832 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004833
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004834def _sqrt_nearest(n, a):
4835 """Closest integer to the square root of the positive integer n. a is
4836 an initial approximation to the square root. Any positive integer
4837 will do for a, but the closer a is to the square root of n the
4838 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004839
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004840 """
4841 if n <= 0 or a <= 0:
4842 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4843
4844 b=0
4845 while a != b:
4846 b, a = a, a--n//a>>1
4847 return a
4848
4849def _rshift_nearest(x, shift):
4850 """Given an integer x and a nonnegative integer shift, return closest
4851 integer to x / 2**shift; use round-to-even in case of a tie.
4852
4853 """
4854 b, q = 1 << shift, x >> shift
4855 return q + (2*(x & (b-1)) + (q&1) > b)
4856
4857def _div_nearest(a, b):
4858 """Closest integer to a/b, a and b positive integers; rounds to even
4859 in the case of a tie.
4860
4861 """
4862 q, r = divmod(a, b)
4863 return q + (2*r + (q&1) > b)
4864
4865def _ilog(x, M, L = 8):
4866 """Integer approximation to M*log(x/M), with absolute error boundable
4867 in terms only of x/M.
4868
4869 Given positive integers x and M, return an integer approximation to
4870 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4871 between the approximation and the exact result is at most 22. For
4872 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4873 both cases these are upper bounds on the error; it will usually be
4874 much smaller."""
4875
4876 # The basic algorithm is the following: let log1p be the function
4877 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4878 # the reduction
4879 #
4880 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4881 #
4882 # repeatedly until the argument to log1p is small (< 2**-L in
4883 # absolute value). For small y we can use the Taylor series
4884 # expansion
4885 #
4886 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4887 #
4888 # truncating at T such that y**T is small enough. The whole
4889 # computation is carried out in a form of fixed-point arithmetic,
4890 # with a real number z being represented by an integer
4891 # approximation to z*M. To avoid loss of precision, the y below
4892 # is actually an integer approximation to 2**R*y*M, where R is the
4893 # number of reductions performed so far.
4894
4895 y = x-M
4896 # argument reduction; R = number of reductions performed
4897 R = 0
4898 while (R <= L and abs(y) << L-R >= M or
4899 R > L and abs(y) >> R-L >= M):
4900 y = _div_nearest((M*y) << 1,
4901 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4902 R += 1
4903
4904 # Taylor series with T terms
4905 T = -int(-10*len(str(M))//(3*L))
4906 yshift = _rshift_nearest(y, R)
4907 w = _div_nearest(M, T)
4908 for k in range(T-1, 0, -1):
4909 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4910
4911 return _div_nearest(w*y, M)
4912
4913def _dlog10(c, e, p):
4914 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4915 approximation to 10**p * log10(c*10**e), with an absolute error of
4916 at most 1. Assumes that c*10**e is not exactly 1."""
4917
4918 # increase precision by 2; compensate for this by dividing
4919 # final result by 100
4920 p += 2
4921
4922 # write c*10**e as d*10**f with either:
4923 # f >= 0 and 1 <= d <= 10, or
4924 # f <= 0 and 0.1 <= d <= 1.
4925 # Thus for c*10**e close to 1, f = 0
4926 l = len(str(c))
4927 f = e+l - (e+l >= 1)
4928
4929 if p > 0:
4930 M = 10**p
4931 k = e+p-f
4932 if k >= 0:
4933 c *= 10**k
4934 else:
4935 c = _div_nearest(c, 10**-k)
4936
4937 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004938 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004939 log_d = _div_nearest(log_d*M, log_10)
4940 log_tenpower = f*M # exact
4941 else:
4942 log_d = 0 # error < 2.31
4943 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4944
4945 return _div_nearest(log_tenpower+log_d, 100)
4946
4947def _dlog(c, e, p):
4948 """Given integers c, e and p with c > 0, compute an integer
4949 approximation to 10**p * log(c*10**e), with an absolute error of
4950 at most 1. Assumes that c*10**e is not exactly 1."""
4951
4952 # Increase precision by 2. The precision increase is compensated
4953 # for at the end with a division by 100.
4954 p += 2
4955
4956 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4957 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4958 # as 10**p * log(d) + 10**p*f * log(10).
4959 l = len(str(c))
4960 f = e+l - (e+l >= 1)
4961
4962 # compute approximation to 10**p*log(d), with error < 27
4963 if p > 0:
4964 k = e+p-f
4965 if k >= 0:
4966 c *= 10**k
4967 else:
4968 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4969
4970 # _ilog magnifies existing error in c by a factor of at most 10
4971 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4972 else:
4973 # p <= 0: just approximate the whole thing by 0; error < 2.31
4974 log_d = 0
4975
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004976 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004977 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004978 extra = len(str(abs(f)))-1
4979 if p + extra >= 0:
4980 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4981 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4982 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004983 else:
4984 f_log_ten = 0
4985 else:
4986 f_log_ten = 0
4987
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004988 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004989 return _div_nearest(f_log_ten + log_d, 100)
4990
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004991class _Log10Memoize(object):
4992 """Class to compute, store, and allow retrieval of, digits of the
4993 constant log(10) = 2.302585.... This constant is needed by
4994 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4995 def __init__(self):
4996 self.digits = "23025850929940456840179914546843642076011014886"
4997
4998 def getdigits(self, p):
4999 """Given an integer p >= 0, return floor(10**p)*log(10).
5000
5001 For example, self.getdigits(3) returns 2302.
5002 """
5003 # digits are stored as a string, for quick conversion to
5004 # integer in the case that we've already computed enough
5005 # digits; the stored digits should always be correct
5006 # (truncated, not rounded to nearest).
5007 if p < 0:
5008 raise ValueError("p should be nonnegative")
5009
5010 if p >= len(self.digits):
5011 # compute p+3, p+6, p+9, ... digits; continue until at
5012 # least one of the extra digits is nonzero
5013 extra = 3
5014 while True:
5015 # compute p+extra digits, correct to within 1ulp
5016 M = 10**(p+extra+2)
5017 digits = str(_div_nearest(_ilog(10*M, M), 100))
5018 if digits[-extra:] != '0'*extra:
5019 break
5020 extra += 3
5021 # keep all reliable digits so far; remove trailing zeros
5022 # and next nonzero digit
5023 self.digits = digits.rstrip('0')[:-1]
5024 return int(self.digits[:p+1])
5025
5026_log10_digits = _Log10Memoize().getdigits
5027
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005028def _iexp(x, M, L=8):
5029 """Given integers x and M, M > 0, such that x/M is small in absolute
5030 value, compute an integer approximation to M*exp(x/M). For 0 <=
5031 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5032 is usually much smaller)."""
5033
5034 # Algorithm: to compute exp(z) for a real number z, first divide z
5035 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5036 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5037 # series
5038 #
5039 # expm1(x) = x + x**2/2! + x**3/3! + ...
5040 #
5041 # Now use the identity
5042 #
5043 # expm1(2x) = expm1(x)*(expm1(x)+2)
5044 #
5045 # R times to compute the sequence expm1(z/2**R),
5046 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5047
5048 # Find R such that x/2**R/M <= 2**-L
5049 R = _nbits((x<<L)//M)
5050
5051 # Taylor series. (2**L)**T > M
5052 T = -int(-10*len(str(M))//(3*L))
5053 y = _div_nearest(x, T)
5054 Mshift = M<<R
5055 for i in range(T-1, 0, -1):
5056 y = _div_nearest(x*(Mshift + y), Mshift * i)
5057
5058 # Expansion
5059 for k in range(R-1, -1, -1):
5060 Mshift = M<<(k+2)
5061 y = _div_nearest(y*(y+Mshift), Mshift)
5062
5063 return M+y
5064
5065def _dexp(c, e, p):
5066 """Compute an approximation to exp(c*10**e), with p decimal places of
5067 precision.
5068
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005069 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005070
5071 10**(p-1) <= d <= 10**p, and
5072 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5073
5074 In other words, d*10**f is an approximation to exp(c*10**e) with p
5075 digits of precision, and with an error in d of at most 1. This is
5076 almost, but not quite, the same as the error being < 1ulp: when d
5077 = 10**(p-1) the error could be up to 10 ulp."""
5078
5079 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5080 p += 2
5081
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005082 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005083 extra = max(0, e + len(str(c)) - 1)
5084 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005085
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005086 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005087 # rounding down
5088 shift = e+q
5089 if shift >= 0:
5090 cshift = c*10**shift
5091 else:
5092 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005093 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005094
5095 # reduce remainder back to original precision
5096 rem = _div_nearest(rem, 10**extra)
5097
5098 # error in result of _iexp < 120; error after division < 0.62
5099 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5100
5101def _dpower(xc, xe, yc, ye, p):
5102 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5103 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5104
5105 10**(p-1) <= c <= 10**p, and
5106 (c-1)*10**e < x**y < (c+1)*10**e
5107
5108 in other words, c*10**e is an approximation to x**y with p digits
5109 of precision, and with an error in c of at most 1. (This is
5110 almost, but not quite, the same as the error being < 1ulp: when c
5111 == 10**(p-1) we can only guarantee error < 10ulp.)
5112
5113 We assume that: x is positive and not equal to 1, and y is nonzero.
5114 """
5115
5116 # Find b such that 10**(b-1) <= |y| <= 10**b
5117 b = len(str(abs(yc))) + ye
5118
5119 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5120 lxc = _dlog(xc, xe, p+b+1)
5121
5122 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5123 shift = ye-b
5124 if shift >= 0:
5125 pc = lxc*yc*10**shift
5126 else:
5127 pc = _div_nearest(lxc*yc, 10**-shift)
5128
5129 if pc == 0:
5130 # we prefer a result that isn't exactly 1; this makes it
5131 # easier to compute a correctly rounded result in __pow__
5132 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5133 coeff, exp = 10**(p-1)+1, 1-p
5134 else:
5135 coeff, exp = 10**p-1, -p
5136 else:
5137 coeff, exp = _dexp(pc, -(p+1), p+1)
5138 coeff = _div_nearest(coeff, 10)
5139 exp += 1
5140
5141 return coeff, exp
5142
5143def _log10_lb(c, correction = {
5144 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5145 '6': 23, '7': 16, '8': 10, '9': 5}):
5146 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5147 if c <= 0:
5148 raise ValueError("The argument to _log10_lb should be nonnegative.")
5149 str_c = str(c)
5150 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005151
Guido van Rossumd8faa362007-04-27 19:54:29 +00005152##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005153
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005154def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005155 """Convert other to Decimal.
5156
5157 Verifies that it's ok to use in an implicit construction.
5158 """
5159 if isinstance(other, Decimal):
5160 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005161 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005162 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005163 if raiseit:
5164 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005165 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005166
Guido van Rossumd8faa362007-04-27 19:54:29 +00005167##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005168
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005169# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005170# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005171
5172DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005173 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005174 traps=[DivisionByZero, Overflow, InvalidOperation],
5175 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005176 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005177 Emax=999999999,
5178 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005179 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005180)
5181
5182# Pre-made alternate contexts offered by the specification
5183# Don't change these; the user should be able to select these
5184# contexts and be able to reproduce results from other implementations
5185# of the spec.
5186
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005187BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005188 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005189 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5190 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005191)
5192
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005193ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005194 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005195 traps=[],
5196 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005197)
5198
5199
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005200##### crud for parsing strings #############################################
5201import re
5202
5203# Regular expression used for parsing numeric strings. Additional
5204# comments:
5205#
5206# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5207# whitespace. But note that the specification disallows whitespace in
5208# a numeric string.
5209#
5210# 2. For finite numbers (not infinities and NaNs) the body of the
5211# number between the optional sign and the optional exponent must have
5212# at least one decimal digit, possibly after the decimal point. The
5213# lookahead expression '(?=\d|\.\d)' checks this.
5214#
5215# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5216# other meaning for \d than the numbers [0-9].
5217
5218import re
5219_parser = re.compile(r""" # A numeric string consists of:
5220# \s*
5221 (?P<sign>[-+])? # an optional sign, followed by either...
5222 (
5223 (?=\d|\.\d) # ...a number (with at least one digit)
5224 (?P<int>\d*) # consisting of a (possibly empty) integer part
5225 (\.(?P<frac>\d*))? # followed by an optional fractional part
5226 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5227 |
5228 Inf(inity)? # ...an infinity, or...
5229 |
5230 (?P<signal>s)? # ...an (optionally signaling)
5231 NaN # NaN
5232 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5233 )
5234# \s*
5235 $
5236""", re.VERBOSE | re.IGNORECASE).match
5237
5238del re
5239
5240
Guido van Rossumd8faa362007-04-27 19:54:29 +00005241##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005242
Guido van Rossumd8faa362007-04-27 19:54:29 +00005243# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005244Inf = Decimal('Inf')
5245negInf = Decimal('-Inf')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005246NaN = Decimal('NaN')
5247Dec_0 = Decimal(0)
5248Dec_p1 = Decimal(1)
5249Dec_n1 = Decimal(-1)
5250Dec_p2 = Decimal(2)
5251Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005252
Guido van Rossumd8faa362007-04-27 19:54:29 +00005253# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005254Infsign = (Inf, negInf)
5255
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005256
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005257
5258if __name__ == '__main__':
5259 import doctest, sys
5260 doctest.testmod(sys.modules[__name__])