blob: 1652914e6f4f865369df6befa06737386210f1cc [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
Guido van Rossuma13f4a12007-12-10 20:04:04 +0000137import numbers as _numbers
Raymond Hettingereb260842005-06-07 18:52:34 +0000138import copy as _copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000139
Christian Heimes25bb7832008-01-11 16:17:00 +0000140try:
141 from collections import namedtuple as _namedtuple
142 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
143except ImportError:
144 DecimalTuple = lambda *args: args
145
Guido van Rossumd8faa362007-04-27 19:54:29 +0000146# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000147ROUND_DOWN = 'ROUND_DOWN'
148ROUND_HALF_UP = 'ROUND_HALF_UP'
149ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
150ROUND_CEILING = 'ROUND_CEILING'
151ROUND_FLOOR = 'ROUND_FLOOR'
152ROUND_UP = 'ROUND_UP'
153ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000154ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000155
Guido van Rossumd8faa362007-04-27 19:54:29 +0000156# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000157
158class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000159 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000160
161 Used exceptions derive from this.
162 If an exception derives from another exception besides this (such as
163 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
164 called if the others are present. This isn't actually used for
165 anything, though.
166
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000167 handle -- Called when context._raise_error is called and the
168 trap_enabler is set. First argument is self, second is the
169 context. More arguments can be given, those being after
170 the explanation in _raise_error (For example,
171 context._raise_error(NewError, '(-x)!', self._sign) would
172 call NewError().handle(context, self._sign).)
173
174 To define a new exception, it should be sufficient to have it derive
175 from DecimalException.
176 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000177 def handle(self, context, *args):
178 pass
179
180
181class Clamped(DecimalException):
182 """Exponent of a 0 changed to fit bounds.
183
184 This occurs and signals clamped if the exponent of a result has been
185 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000186 representation. This may occur when the exponent of a zero result would
187 be outside the bounds of a representation, or when a large normal
188 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000189 this latter case, the exponent is reduced to fit and the corresponding
190 number of zero digits are appended to the coefficient ("fold-down").
191 """
192
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000193class InvalidOperation(DecimalException):
194 """An invalid operation was performed.
195
196 Various bad things cause this:
197
198 Something creates a signaling NaN
199 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000200 0 * (+-)INF
201 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000202 x % 0
203 (+-)INF % x
204 x._rescale( non-integer )
205 sqrt(-x) , x > 0
206 0 ** 0
207 x ** (non-integer)
208 x ** (+-)INF
209 An operand is invalid
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000210
211 The result of the operation after these is a quiet positive NaN,
212 except when the cause is a signaling NaN, in which case the result is
213 also a quiet NaN, but with the original sign, and an optional
214 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000215 """
216 def handle(self, context, *args):
217 if args:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000218 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
219 return ans._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000220 return NaN
221
222class ConversionSyntax(InvalidOperation):
223 """Trying to convert badly formed string.
224
225 This occurs and signals invalid-operation if an string is being
226 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000228 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000229 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000230 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000231
232class DivisionByZero(DecimalException, ZeroDivisionError):
233 """Division by 0.
234
235 This occurs and signals division-by-zero if division of a finite number
236 by zero was attempted (during a divide-integer or divide operation, or a
237 power operation with negative right-hand operand), and the dividend was
238 not zero.
239
240 The result of the operation is [sign,inf], where sign is the exclusive
241 or of the signs of the operands for divide, or is 1 for an odd power of
242 -0, for power.
243 """
244
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000245 def handle(self, context, sign, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000246 return Infsign[sign]
247
248class DivisionImpossible(InvalidOperation):
249 """Cannot perform the division adequately.
250
251 This occurs and signals invalid-operation if the integer result of a
252 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000253 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000254 """
255
256 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000257 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000258
259class DivisionUndefined(InvalidOperation, ZeroDivisionError):
260 """Undefined result of division.
261
262 This occurs and signals invalid-operation if division by zero was
263 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000264 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000265 """
266
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000267 def handle(self, context, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000268 return NaN
269
270class Inexact(DecimalException):
271 """Had to round, losing information.
272
273 This occurs and signals inexact whenever the result of an operation is
274 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000275 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000276 result in all cases is unchanged.
277
278 The inexact signal may be tested (or trapped) to determine if a given
279 operation (or sequence of operations) was inexact.
280 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000281
282class InvalidContext(InvalidOperation):
283 """Invalid context. Unknown rounding, for example.
284
285 This occurs and signals invalid-operation if an invalid context was
Guido van Rossumd8faa362007-04-27 19:54:29 +0000286 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000287 on creation and either the precision exceeds the capability of the
288 underlying concrete representation or an unknown or unsupported rounding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000289 was specified. These aspects of the context need only be checked when
290 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000291 """
292
293 def handle(self, context, *args):
294 return NaN
295
296class Rounded(DecimalException):
297 """Number got rounded (not necessarily changed during rounding).
298
299 This occurs and signals rounded whenever the result of an operation is
300 rounded (that is, some zero or non-zero digits were discarded from the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000301 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000302 result in all cases is unchanged.
303
304 The rounded signal may be tested (or trapped) to determine if a given
305 operation (or sequence of operations) caused a loss of precision.
306 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000307
308class Subnormal(DecimalException):
309 """Exponent < Emin before rounding.
310
311 This occurs and signals subnormal whenever the result of a conversion or
312 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000313 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000314
315 The subnormal signal may be tested (or trapped) to determine if a given
316 or operation (or sequence of operations) yielded a subnormal result.
317 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000318
319class Overflow(Inexact, Rounded):
320 """Numerical overflow.
321
322 This occurs and signals overflow if the adjusted exponent of a result
323 (from a conversion or from an operation that is not an attempt to divide
324 by zero), after rounding, would be greater than the largest value that
325 can be handled by the implementation (the value Emax).
326
327 The result depends on the rounding mode:
328
329 For round-half-up and round-half-even (and for round-half-down and
330 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000331 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000332 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000333 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000334 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000335 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000336 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000337 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000338 will also be raised.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000339 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000340
341 def handle(self, context, sign, *args):
342 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000343 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000344 return Infsign[sign]
345 if sign == 0:
346 if context.rounding == ROUND_CEILING:
347 return Infsign[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000348 return _dec_from_triple(sign, '9'*context.prec,
349 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000350 if sign == 1:
351 if context.rounding == ROUND_FLOOR:
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
356
357class Underflow(Inexact, Rounded, Subnormal):
358 """Numerical underflow with result rounded to 0.
359
360 This occurs and signals underflow if a result is inexact and the
361 adjusted exponent of the result would be smaller (more negative) than
362 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000363 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000364
365 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000366 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000367 in 0 with the sign of the intermediate result and an exponent of Etiny.
368
369 In all cases, Inexact, Rounded, and Subnormal will also be raised.
370 """
371
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000372# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000373_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000374 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000375
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000376# Map conditions (per the spec) to signals
377_condition_map = {ConversionSyntax:InvalidOperation,
378 DivisionImpossible:InvalidOperation,
379 DivisionUndefined:InvalidOperation,
380 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000381
Guido van Rossumd8faa362007-04-27 19:54:29 +0000382##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000383
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000384# The getcontext() and setcontext() function manage access to a thread-local
385# current context. Py2.4 offers direct support for thread locals. If that
386# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000387# work for older Pythons. If threads are not part of the build, create a
388# mock threading object with threading.local() returning the module namespace.
389
390try:
391 import threading
392except ImportError:
393 # Python was compiled without threads; create a mock object instead
394 import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +0000395 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000396 def local(self, sys=sys):
397 return sys.modules[__name__]
398 threading = MockThreading()
399 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000400
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000401try:
402 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000403
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000404except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000405
Guido van Rossumd8faa362007-04-27 19:54:29 +0000406 # To fix reloading, force it to create a new context
407 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000408 if hasattr(threading.currentThread(), '__decimal_context__'):
409 del threading.currentThread().__decimal_context__
410
411 def setcontext(context):
412 """Set this thread's context to context."""
413 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000414 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000415 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000416 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000417
418 def getcontext():
419 """Returns this thread's context.
420
421 If this thread does not yet have a context, returns
422 a new context and sets this thread's context.
423 New contexts are copies of DefaultContext.
424 """
425 try:
426 return threading.currentThread().__decimal_context__
427 except AttributeError:
428 context = Context()
429 threading.currentThread().__decimal_context__ = context
430 return context
431
432else:
433
434 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000435 if hasattr(local, '__decimal_context__'):
436 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000437
438 def getcontext(_local=local):
439 """Returns this thread's context.
440
441 If this thread does not yet have a context, returns
442 a new context and sets this thread's context.
443 New contexts are copies of DefaultContext.
444 """
445 try:
446 return _local.__decimal_context__
447 except AttributeError:
448 context = Context()
449 _local.__decimal_context__ = context
450 return context
451
452 def setcontext(context, _local=local):
453 """Set this thread's context to context."""
454 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000455 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000456 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000457 _local.__decimal_context__ = context
458
459 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000460
Thomas Wouters89f507f2006-12-13 04:49:30 +0000461def localcontext(ctx=None):
462 """Return a context manager for a copy of the supplied context
463
464 Uses a copy of the current context if no context is specified
465 The returned context manager creates a local decimal context
466 in a with statement:
467 def sin(x):
468 with localcontext() as ctx:
469 ctx.prec += 2
470 # Rest of sin calculation algorithm
471 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000472 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000473
474 def sin(x):
475 with localcontext(ExtendedContext):
476 # Rest of sin calculation algorithm
477 # uses the Extended Context from the
478 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000479 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000480
481 """
482 # The string below can't be included in the docstring until Python 2.6
483 # as the doctest module doesn't understand __future__ statements
484 """
485 >>> from __future__ import with_statement
Guido van Rossum7131f842007-02-09 20:13:25 +0000486 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000487 28
488 >>> with localcontext():
489 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000490 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000491 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000492 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000493 30
494 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000495 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000496 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000497 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000498 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000499 28
500 """
501 if ctx is None: ctx = getcontext()
502 return _ContextManager(ctx)
503
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000504
Guido van Rossumd8faa362007-04-27 19:54:29 +0000505##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000506
Guido van Rossuma13f4a12007-12-10 20:04:04 +0000507class Decimal(_numbers.Real, _numbers.Inexact):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000508 """Floating point class for decimal arithmetic."""
509
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000510 __slots__ = ('_exp','_int','_sign', '_is_special')
511 # Generally, the value of the Decimal instance is given by
512 # (-1)**_sign * _int * 10**_exp
513 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000514
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000515 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000516 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000517 """Create a decimal point instance.
518
519 >>> Decimal('3.14') # string input
520 Decimal("3.14")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000521 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000522 Decimal("3.14")
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000523 >>> Decimal(314) # int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000524 Decimal("314")
525 >>> Decimal(Decimal(314)) # another decimal instance
526 Decimal("314")
Christian Heimesa62da1d2008-01-12 19:39:10 +0000527 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
528 Decimal("3.14")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000529 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000530
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000531 # Note that the coefficient, self._int, is actually stored as
532 # a string rather than as a tuple of digits. This speeds up
533 # the "digits to integer" and "integer to digits" conversions
534 # that are used in almost every arithmetic operation on
535 # Decimals. This is an internal detail: the as_tuple function
536 # and the Decimal constructor still deal with tuples of
537 # digits.
538
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000539 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000540
Christian Heimesd59c64c2007-11-30 19:27:20 +0000541 # From a string
542 # REs insist on real strings, so we can too.
543 if isinstance(value, str):
Christian Heimesa62da1d2008-01-12 19:39:10 +0000544 m = _parser(value.strip())
Christian Heimesd59c64c2007-11-30 19:27:20 +0000545 if m is None:
546 if context is None:
547 context = getcontext()
548 return context._raise_error(ConversionSyntax,
549 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000550
Christian Heimesd59c64c2007-11-30 19:27:20 +0000551 if m.group('sign') == "-":
552 self._sign = 1
553 else:
554 self._sign = 0
555 intpart = m.group('int')
556 if intpart is not None:
557 # finite number
558 fracpart = m.group('frac')
559 exp = int(m.group('exp') or '0')
560 if fracpart is not None:
561 self._int = (intpart+fracpart).lstrip('0') or '0'
562 self._exp = exp - len(fracpart)
563 else:
564 self._int = intpart.lstrip('0') or '0'
565 self._exp = exp
566 self._is_special = False
567 else:
568 diag = m.group('diag')
569 if diag is not None:
570 # NaN
571 self._int = diag.lstrip('0')
572 if m.group('signal'):
573 self._exp = 'N'
574 else:
575 self._exp = 'n'
576 else:
577 # infinity
578 self._int = '0'
579 self._exp = 'F'
580 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000581 return self
582
583 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000584 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000585 if value >= 0:
586 self._sign = 0
587 else:
588 self._sign = 1
589 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000590 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000591 self._is_special = False
592 return self
593
594 # From another decimal
595 if isinstance(value, Decimal):
596 self._exp = value._exp
597 self._sign = value._sign
598 self._int = value._int
599 self._is_special = value._is_special
600 return self
601
602 # From an internal working value
603 if isinstance(value, _WorkRep):
604 self._sign = value.sign
605 self._int = str(value.int)
606 self._exp = int(value.exp)
607 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000608 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000609
610 # tuple/list conversion (possibly from as_tuple())
611 if isinstance(value, (list,tuple)):
612 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000613 raise ValueError('Invalid tuple size in creation of Decimal '
614 'from list or tuple. The list or tuple '
615 'should have exactly three elements.')
616 # process sign. The isinstance test rejects floats
617 if not (isinstance(value[0], int) and value[0] in (0,1)):
618 raise ValueError("Invalid sign. The first value in the tuple "
619 "should be an integer; either 0 for a "
620 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000621 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000622 if value[2] == 'F':
623 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000624 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000625 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000626 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000627 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000628 # process and validate the digits in value[1]
629 digits = []
630 for digit in value[1]:
631 if isinstance(digit, int) and 0 <= digit <= 9:
632 # skip leading zeros
633 if digits or digit != 0:
634 digits.append(digit)
635 else:
636 raise ValueError("The second value in the tuple must "
637 "be composed of integers in the range "
638 "0 through 9.")
639 if value[2] in ('n', 'N'):
640 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000641 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000642 self._exp = value[2]
643 self._is_special = True
644 elif isinstance(value[2], int):
645 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000646 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000647 self._exp = value[2]
648 self._is_special = False
649 else:
650 raise ValueError("The third value in the tuple must "
651 "be an integer, or one of the "
652 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000653 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000654
Raymond Hettingerbf440692004-07-10 14:14:37 +0000655 if isinstance(value, float):
656 raise TypeError("Cannot convert float to Decimal. " +
657 "First convert the float to a string")
658
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000659 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000660
661 def _isnan(self):
662 """Returns whether the number is not actually one.
663
664 0 if a number
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000665 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000666 2 if sNaN
667 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000668 if self._is_special:
669 exp = self._exp
670 if exp == 'n':
671 return 1
672 elif exp == 'N':
673 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000674 return 0
675
676 def _isinfinity(self):
677 """Returns whether the number is infinite
678
679 0 if finite or not a number
680 1 if +INF
681 -1 if -INF
682 """
683 if self._exp == 'F':
684 if self._sign:
685 return -1
686 return 1
687 return 0
688
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000689 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000690 """Returns whether the number is not actually one.
691
692 if self, other are sNaN, signal
693 if self, other are NaN return nan
694 return 0
695
696 Done before operations.
697 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000698
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000699 self_is_nan = self._isnan()
700 if other is None:
701 other_is_nan = False
702 else:
703 other_is_nan = other._isnan()
704
705 if self_is_nan or other_is_nan:
706 if context is None:
707 context = getcontext()
708
709 if self_is_nan == 2:
710 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000711 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000712 if other_is_nan == 2:
713 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000714 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000715 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000716 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000717
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000718 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000719 return 0
720
Jack Diederich4dafcc42006-11-28 19:15:13 +0000721 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000722 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000723
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000724 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000725 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000726 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000727
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000728 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000729 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000730 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000731 # Never return NotImplemented
732 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000733
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000734 if self._is_special or other._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000735 # check for nans, without raising on a signaling nan
736 if self._isnan() or other._isnan():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000737 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000738
739 # INF = INF
740 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000741
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000742 # check for zeros; note that cmp(0, -0) should return 0
743 if not self:
744 if not other:
745 return 0
746 else:
747 return -((-1)**other._sign)
748 if not other:
749 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000750
Guido van Rossumd8faa362007-04-27 19:54:29 +0000751 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000752 if other._sign < self._sign:
753 return -1
754 if self._sign < other._sign:
755 return 1
756
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000757 self_adjusted = self.adjusted()
758 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000759 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000760 self_padded = self._int + '0'*(self._exp - other._exp)
761 other_padded = other._int + '0'*(other._exp - self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000762 return cmp(self_padded, other_padded) * (-1)**self._sign
763 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000764 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000765 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000766 return -((-1)**self._sign)
767
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000768 def __eq__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000769 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000770 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000771 return self.__cmp__(other) == 0
772
773 def __ne__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000774 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000775 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000776 return self.__cmp__(other) != 0
777
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000778 def __lt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000779 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000780 return NotImplemented
781 return self.__cmp__(other) < 0
782
783 def __le__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000784 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000785 return NotImplemented
786 return self.__cmp__(other) <= 0
787
788 def __gt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000789 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000790 return NotImplemented
791 return self.__cmp__(other) > 0
792
793 def __ge__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000794 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000795 return NotImplemented
796 return self.__cmp__(other) >= 0
797
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000798 def compare(self, other, context=None):
799 """Compares one to another.
800
801 -1 => a < b
802 0 => a = b
803 1 => a > b
804 NaN => one is NaN
805 Like __cmp__, but returns Decimal instances.
806 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000807 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000808
Guido van Rossumd8faa362007-04-27 19:54:29 +0000809 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000810 if (self._is_special or other and other._is_special):
811 ans = self._check_nans(other, context)
812 if ans:
813 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000814
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000815 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000816
817 def __hash__(self):
818 """x.__hash__() <==> hash(x)"""
819 # Decimal integers must hash the same as the ints
Christian Heimes2380ac72008-01-09 00:17:24 +0000820 #
821 # The hash of a nonspecial noninteger Decimal must depend only
822 # on the value of that Decimal, and not on its representation.
823 # For example: hash(Decimal("100E-1")) == hash(Decimal("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))
Christian Heimes2380ac72008-01-09 00:17:24 +0000839 # The value of a nonzero nonspecial Decimal instance is
840 # faithfully represented by the triple consisting of its sign,
841 # its adjusted exponent, and its coefficient with trailing
842 # zeros removed.
843 return hash((self._sign,
844 self._exp+len(self._int),
845 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000846
847 def as_tuple(self):
848 """Represents the number as a triple tuple.
849
850 To show the internals exactly as they are.
851 """
Christian Heimes25bb7832008-01-11 16:17:00 +0000852 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000853
854 def __repr__(self):
855 """Represents the number as an instance of Decimal."""
856 # Invariant: eval(repr(d)) == d
857 return 'Decimal("%s")' % str(self)
858
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000859 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000860 """Return string representation of the number in scientific notation.
861
862 Captures all of the information in the underlying representation.
863 """
864
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000865 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000866 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000867 if self._exp == 'F':
868 return sign + 'Infinity'
869 elif self._exp == 'n':
870 return sign + 'NaN' + self._int
871 else: # self._exp == 'N'
872 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000873
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000874 # number of digits of self._int to left of decimal point
875 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000876
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000877 # dotplace is number of digits of self._int to the left of the
878 # decimal point in the mantissa of the output string (that is,
879 # after adjusting the exponent)
880 if self._exp <= 0 and leftdigits > -6:
881 # no exponent required
882 dotplace = leftdigits
883 elif not eng:
884 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000885 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000886 elif self._int == '0':
887 # engineering notation, zero
888 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000889 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000890 # engineering notation, nonzero
891 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000892
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000893 if dotplace <= 0:
894 intpart = '0'
895 fracpart = '.' + '0'*(-dotplace) + self._int
896 elif dotplace >= len(self._int):
897 intpart = self._int+'0'*(dotplace-len(self._int))
898 fracpart = ''
899 else:
900 intpart = self._int[:dotplace]
901 fracpart = '.' + self._int[dotplace:]
902 if leftdigits == dotplace:
903 exp = ''
904 else:
905 if context is None:
906 context = getcontext()
907 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
908
909 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000910
911 def to_eng_string(self, context=None):
912 """Convert to engineering-type string.
913
914 Engineering notation has an exponent which is a multiple of 3, so there
915 are up to 3 digits left of the decimal place.
916
917 Same rules for when in exponential and when as a value as in __str__.
918 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000919 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000920
921 def __neg__(self, context=None):
922 """Returns a copy with the sign switched.
923
924 Rounds, if it has reason.
925 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000926 if self._is_special:
927 ans = self._check_nans(context=context)
928 if ans:
929 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000930
931 if not self:
932 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000933 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000934 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000935 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000936
937 if context is None:
938 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +0000939 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000940
941 def __pos__(self, context=None):
942 """Returns a copy, unless it is a sNaN.
943
944 Rounds the number (if more then precision digits)
945 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000946 if self._is_special:
947 ans = self._check_nans(context=context)
948 if ans:
949 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000950
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000951 if not self:
952 # + (-0) = 0
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000953 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000954 else:
955 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000956
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000957 if context is None:
958 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +0000959 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000960
Christian Heimes2c181612007-12-17 20:04:13 +0000961 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000962 """Returns the absolute value of self.
963
Christian Heimes2c181612007-12-17 20:04:13 +0000964 If the keyword argument 'round' is false, do not round. The
965 expression self.__abs__(round=False) is equivalent to
966 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000967 """
Christian Heimes2c181612007-12-17 20:04:13 +0000968 if not round:
969 return self.copy_abs()
970
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000971 if self._is_special:
972 ans = self._check_nans(context=context)
973 if ans:
974 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000975
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000976 if self._sign:
977 ans = self.__neg__(context=context)
978 else:
979 ans = self.__pos__(context=context)
980
981 return ans
982
983 def __add__(self, other, context=None):
984 """Returns self + other.
985
986 -INF + INF (or the reverse) cause InvalidOperation errors.
987 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000988 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000989 if other is NotImplemented:
990 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000991
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000992 if context is None:
993 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000994
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000995 if self._is_special or other._is_special:
996 ans = self._check_nans(other, context)
997 if ans:
998 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000999
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001000 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001001 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001002 if self._sign != other._sign and other._isinfinity():
1003 return context._raise_error(InvalidOperation, '-INF + INF')
1004 return Decimal(self)
1005 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001006 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001007
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001008 exp = min(self._exp, other._exp)
1009 negativezero = 0
1010 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001011 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001012 negativezero = 1
1013
1014 if not self and not other:
1015 sign = min(self._sign, other._sign)
1016 if negativezero:
1017 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001018 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001019 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001020 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001021 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001022 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001023 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001024 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001025 return ans
1026 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001027 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001028 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001029 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001030 return ans
1031
1032 op1 = _WorkRep(self)
1033 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001034 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001035
1036 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001037 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001038 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001039 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001040 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001041 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001042 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001043 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001044 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001045 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001046 if op1.sign == 1:
1047 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001048 op1.sign, op2.sign = op2.sign, op1.sign
1049 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001050 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001051 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001052 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001053 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001054 op1.sign, op2.sign = (0, 0)
1055 else:
1056 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001057 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001058
Raymond Hettinger17931de2004-10-27 06:21:46 +00001059 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001060 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001061 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001062 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001063
1064 result.exp = op1.exp
1065 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001066 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001067 return ans
1068
1069 __radd__ = __add__
1070
1071 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001072 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001073 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001074 if other is NotImplemented:
1075 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001076
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001077 if self._is_special or other._is_special:
1078 ans = self._check_nans(other, context=context)
1079 if ans:
1080 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001082 # self - other is computed as self + other.copy_negate()
1083 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001084
1085 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001086 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001087 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001088 if other is NotImplemented:
1089 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001090
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001091 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001092
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001093 def __mul__(self, other, context=None):
1094 """Return self * other.
1095
1096 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1097 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001098 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001099 if other is NotImplemented:
1100 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001101
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001102 if context is None:
1103 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001104
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001105 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001106
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001107 if self._is_special or other._is_special:
1108 ans = self._check_nans(other, context)
1109 if ans:
1110 return ans
1111
1112 if self._isinfinity():
1113 if not other:
1114 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1115 return Infsign[resultsign]
1116
1117 if other._isinfinity():
1118 if not self:
1119 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1120 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001121
1122 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001123
1124 # Special case for multiplying by zero
1125 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001126 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001127 # Fixing in case the exponent is out of bounds
1128 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001129 return ans
1130
1131 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001132 if self._int == '1':
1133 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001134 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001135 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001136 if other._int == '1':
1137 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001138 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001139 return ans
1140
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001141 op1 = _WorkRep(self)
1142 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001143
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001144 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001145 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001146
1147 return ans
1148 __rmul__ = __mul__
1149
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001150 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001151 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001152 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001153 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001154 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001155
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001156 if context is None:
1157 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001158
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001159 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001160
1161 if self._is_special or other._is_special:
1162 ans = self._check_nans(other, context)
1163 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001164 return ans
1165
1166 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001167 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001168
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001169 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001170 return Infsign[sign]
1171
1172 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001173 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001174 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001175
1176 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001177 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001178 if not self:
1179 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001180 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001181
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001182 if not self:
1183 exp = self._exp - other._exp
1184 coeff = 0
1185 else:
1186 # OK, so neither = 0, INF or NaN
1187 shift = len(other._int) - len(self._int) + context.prec + 1
1188 exp = self._exp - other._exp - shift
1189 op1 = _WorkRep(self)
1190 op2 = _WorkRep(other)
1191 if shift >= 0:
1192 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1193 else:
1194 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1195 if remainder:
1196 # result is not exact; adjust to ensure correct rounding
1197 if coeff % 5 == 0:
1198 coeff += 1
1199 else:
1200 # result is exact; get as close to ideal exponent as possible
1201 ideal_exp = self._exp - other._exp
1202 while exp < ideal_exp and coeff % 10 == 0:
1203 coeff //= 10
1204 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001205
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001206 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001207 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001208
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001209 def _divide(self, other, context):
1210 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001211
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001212 Assumes that neither self nor other is a NaN, that self is not
1213 infinite and that other is nonzero.
1214 """
1215 sign = self._sign ^ other._sign
1216 if other._isinfinity():
1217 ideal_exp = self._exp
1218 else:
1219 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001220
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001221 expdiff = self.adjusted() - other.adjusted()
1222 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001223 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001224 self._rescale(ideal_exp, context.rounding))
1225 if expdiff <= context.prec:
1226 op1 = _WorkRep(self)
1227 op2 = _WorkRep(other)
1228 if op1.exp >= op2.exp:
1229 op1.int *= 10**(op1.exp - op2.exp)
1230 else:
1231 op2.int *= 10**(op2.exp - op1.exp)
1232 q, r = divmod(op1.int, op2.int)
1233 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001234 return (_dec_from_triple(sign, str(q), 0),
1235 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001236
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001237 # Here the quotient is too large to be representable
1238 ans = context._raise_error(DivisionImpossible,
1239 'quotient too large in //, % or divmod')
1240 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001241
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001242 def __rtruediv__(self, other, context=None):
1243 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001244 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001245 if other is NotImplemented:
1246 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001247 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001248
1249 def __divmod__(self, other, context=None):
1250 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001251 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001252 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001253 other = _convert_other(other)
1254 if other is NotImplemented:
1255 return other
1256
1257 if context is None:
1258 context = getcontext()
1259
1260 ans = self._check_nans(other, context)
1261 if ans:
1262 return (ans, ans)
1263
1264 sign = self._sign ^ other._sign
1265 if self._isinfinity():
1266 if other._isinfinity():
1267 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1268 return ans, ans
1269 else:
1270 return (Infsign[sign],
1271 context._raise_error(InvalidOperation, 'INF % x'))
1272
1273 if not other:
1274 if not self:
1275 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1276 return ans, ans
1277 else:
1278 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1279 context._raise_error(InvalidOperation, 'x % 0'))
1280
1281 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001282 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001283 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001284
1285 def __rdivmod__(self, other, context=None):
1286 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001287 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001288 if other is NotImplemented:
1289 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001290 return other.__divmod__(self, context=context)
1291
1292 def __mod__(self, other, context=None):
1293 """
1294 self % other
1295 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001296 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001297 if other is NotImplemented:
1298 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001299
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001300 if context is None:
1301 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001302
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001303 ans = self._check_nans(other, context)
1304 if ans:
1305 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001306
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001307 if self._isinfinity():
1308 return context._raise_error(InvalidOperation, 'INF % x')
1309 elif not other:
1310 if self:
1311 return context._raise_error(InvalidOperation, 'x % 0')
1312 else:
1313 return context._raise_error(DivisionUndefined, '0 % 0')
1314
1315 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001316 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001317 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001318
1319 def __rmod__(self, other, context=None):
1320 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001321 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001322 if other is NotImplemented:
1323 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001324 return other.__mod__(self, context=context)
1325
1326 def remainder_near(self, other, context=None):
1327 """
1328 Remainder nearest to 0- abs(remainder-near) <= other/2
1329 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001330 if context is None:
1331 context = getcontext()
1332
1333 other = _convert_other(other, raiseit=True)
1334
1335 ans = self._check_nans(other, context)
1336 if ans:
1337 return ans
1338
1339 # self == +/-infinity -> InvalidOperation
1340 if self._isinfinity():
1341 return context._raise_error(InvalidOperation,
1342 'remainder_near(infinity, x)')
1343
1344 # other == 0 -> either InvalidOperation or DivisionUndefined
1345 if not other:
1346 if self:
1347 return context._raise_error(InvalidOperation,
1348 'remainder_near(x, 0)')
1349 else:
1350 return context._raise_error(DivisionUndefined,
1351 'remainder_near(0, 0)')
1352
1353 # other = +/-infinity -> remainder = self
1354 if other._isinfinity():
1355 ans = Decimal(self)
1356 return ans._fix(context)
1357
1358 # self = 0 -> remainder = self, with ideal exponent
1359 ideal_exponent = min(self._exp, other._exp)
1360 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001361 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001362 return ans._fix(context)
1363
1364 # catch most cases of large or small quotient
1365 expdiff = self.adjusted() - other.adjusted()
1366 if expdiff >= context.prec + 1:
1367 # expdiff >= prec+1 => abs(self/other) > 10**prec
1368 return context._raise_error(DivisionImpossible)
1369 if expdiff <= -2:
1370 # expdiff <= -2 => abs(self/other) < 0.1
1371 ans = self._rescale(ideal_exponent, context.rounding)
1372 return ans._fix(context)
1373
1374 # adjust both arguments to have the same exponent, then divide
1375 op1 = _WorkRep(self)
1376 op2 = _WorkRep(other)
1377 if op1.exp >= op2.exp:
1378 op1.int *= 10**(op1.exp - op2.exp)
1379 else:
1380 op2.int *= 10**(op2.exp - op1.exp)
1381 q, r = divmod(op1.int, op2.int)
1382 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1383 # 10**ideal_exponent. Apply correction to ensure that
1384 # abs(remainder) <= abs(other)/2
1385 if 2*r + (q&1) > op2.int:
1386 r -= op2.int
1387 q += 1
1388
1389 if q >= 10**context.prec:
1390 return context._raise_error(DivisionImpossible)
1391
1392 # result has same sign as self unless r is negative
1393 sign = self._sign
1394 if r < 0:
1395 sign = 1-sign
1396 r = -r
1397
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001398 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001399 return ans._fix(context)
1400
1401 def __floordiv__(self, other, context=None):
1402 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001403 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001404 if other is NotImplemented:
1405 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001406
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001407 if context is None:
1408 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001409
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001410 ans = self._check_nans(other, context)
1411 if ans:
1412 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001413
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001414 if self._isinfinity():
1415 if other._isinfinity():
1416 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001417 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001418 return Infsign[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001419
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001420 if not other:
1421 if self:
1422 return context._raise_error(DivisionByZero, 'x // 0',
1423 self._sign ^ other._sign)
1424 else:
1425 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001426
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001427 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001428
1429 def __rfloordiv__(self, other, context=None):
1430 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001431 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001432 if other is NotImplemented:
1433 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001434 return other.__floordiv__(self, context=context)
1435
1436 def __float__(self):
1437 """Float representation."""
1438 return float(str(self))
1439
1440 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001441 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001442 if self._is_special:
1443 if self._isnan():
1444 context = getcontext()
1445 return context._raise_error(InvalidContext)
1446 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001447 raise OverflowError("Cannot convert infinity to int")
1448 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001449 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001450 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001451 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001452 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001453
Christian Heimes969fe572008-01-25 11:23:10 +00001454 __trunc__ = __int__
1455
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001456 def _fix_nan(self, context):
1457 """Decapitate the payload of a NaN to fit the context"""
1458 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001459
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001460 # maximum length of payload is precision if _clamp=0,
1461 # precision-1 if _clamp=1.
1462 max_payload_len = context.prec - context._clamp
1463 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001464 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1465 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001466 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001467
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001468 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001469 """Round if it is necessary to keep self within prec precision.
1470
1471 Rounds and fixes the exponent. Does not raise on a sNaN.
1472
1473 Arguments:
1474 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001475 context - context used.
1476 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001477
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001478 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001479 if self._isnan():
1480 # decapitate payload if necessary
1481 return self._fix_nan(context)
1482 else:
1483 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001484 return Decimal(self)
1485
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001486 # if self is zero then exponent should be between Etiny and
1487 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1488 Etiny = context.Etiny()
1489 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001490 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001491 exp_max = [context.Emax, Etop][context._clamp]
1492 new_exp = min(max(self._exp, Etiny), exp_max)
1493 if new_exp != self._exp:
1494 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001495 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001496 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001497 return Decimal(self)
1498
1499 # exp_min is the smallest allowable exponent of the result,
1500 # equal to max(self.adjusted()-context.prec+1, Etiny)
1501 exp_min = len(self._int) + self._exp - context.prec
1502 if exp_min > Etop:
1503 # overflow: exp_min > Etop iff self.adjusted() > Emax
1504 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001505 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001506 return context._raise_error(Overflow, 'above Emax', self._sign)
1507 self_is_subnormal = exp_min < Etiny
1508 if self_is_subnormal:
1509 context._raise_error(Subnormal)
1510 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001511
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001512 # round if self has too many digits
1513 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001514 context._raise_error(Rounded)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001515 digits = len(self._int) + self._exp - exp_min
1516 if digits < 0:
1517 self = _dec_from_triple(self._sign, '1', exp_min-1)
1518 digits = 0
1519 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1520 changed = this_function(digits)
1521 coeff = self._int[:digits] or '0'
1522 if changed == 1:
1523 coeff = str(int(coeff)+1)
1524 ans = _dec_from_triple(self._sign, coeff, exp_min)
1525
1526 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001527 context._raise_error(Inexact)
1528 if self_is_subnormal:
1529 context._raise_error(Underflow)
1530 if not ans:
1531 # raise Clamped on underflow to 0
1532 context._raise_error(Clamped)
1533 elif len(ans._int) == context.prec+1:
1534 # we get here only if rescaling rounds the
1535 # cofficient up to exactly 10**context.prec
1536 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001537 ans = _dec_from_triple(ans._sign,
1538 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001539 else:
1540 # Inexact and Rounded have already been raised
1541 ans = context._raise_error(Overflow, 'above Emax',
1542 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001543 return ans
1544
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001545 # fold down if _clamp == 1 and self has too few digits
1546 if context._clamp == 1 and self._exp > Etop:
1547 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001548 self_padded = self._int + '0'*(self._exp - Etop)
1549 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001550
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001551 # here self was representable to begin with; return unchanged
1552 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001553
1554 _pick_rounding_function = {}
1555
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001556 # for each of the rounding functions below:
1557 # self is a finite, nonzero Decimal
1558 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001559 #
1560 # each function returns either -1, 0, or 1, as follows:
1561 # 1 indicates that self should be rounded up (away from zero)
1562 # 0 indicates that self should be truncated, and that all the
1563 # digits to be truncated are zeros (so the value is unchanged)
1564 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001565
1566 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001567 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001568 if _all_zeros(self._int, prec):
1569 return 0
1570 else:
1571 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001572
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001573 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001574 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001575 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001576
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001577 def _round_half_up(self, prec):
1578 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001579 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001580 return 1
1581 elif _all_zeros(self._int, prec):
1582 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001583 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001584 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001585
1586 def _round_half_down(self, prec):
1587 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001588 if _exact_half(self._int, prec):
1589 return -1
1590 else:
1591 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001592
1593 def _round_half_even(self, prec):
1594 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001595 if _exact_half(self._int, prec) and \
1596 (prec == 0 or self._int[prec-1] in '02468'):
1597 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001598 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001599 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001600
1601 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001602 """Rounds up (not away from 0 if negative.)"""
1603 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001604 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001605 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001606 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001607
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001608 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001609 """Rounds down (not towards 0 if negative)"""
1610 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001611 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001612 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001613 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001614
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001615 def _round_05up(self, prec):
1616 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001617 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001618 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001619 else:
1620 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001621
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001622 def fma(self, other, third, context=None):
1623 """Fused multiply-add.
1624
1625 Returns self*other+third with no rounding of the intermediate
1626 product self*other.
1627
1628 self and other are multiplied together, with no rounding of
1629 the result. The third operand is then added to the result,
1630 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001631 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001632
1633 other = _convert_other(other, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001634
1635 # compute product; raise InvalidOperation if either operand is
1636 # a signaling NaN or if the product is zero times infinity.
1637 if self._is_special or other._is_special:
1638 if context is None:
1639 context = getcontext()
1640 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001641 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001642 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001643 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001644 if self._exp == 'n':
1645 product = self
1646 elif other._exp == 'n':
1647 product = other
1648 elif self._exp == 'F':
1649 if not other:
1650 return context._raise_error(InvalidOperation,
1651 'INF * 0 in fma')
1652 product = Infsign[self._sign ^ other._sign]
1653 elif other._exp == 'F':
1654 if not self:
1655 return context._raise_error(InvalidOperation,
1656 '0 * INF in fma')
1657 product = Infsign[self._sign ^ other._sign]
1658 else:
1659 product = _dec_from_triple(self._sign ^ other._sign,
1660 str(int(self._int) * int(other._int)),
1661 self._exp + other._exp)
1662
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001663 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001664 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001665
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001666 def _power_modulo(self, other, modulo, context=None):
1667 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001668
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001669 # if can't convert other and modulo to Decimal, raise
1670 # TypeError; there's no point returning NotImplemented (no
1671 # equivalent of __rpow__ for three argument pow)
1672 other = _convert_other(other, raiseit=True)
1673 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001674
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001675 if context is None:
1676 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001677
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001678 # deal with NaNs: if there are any sNaNs then first one wins,
1679 # (i.e. behaviour for NaNs is identical to that of fma)
1680 self_is_nan = self._isnan()
1681 other_is_nan = other._isnan()
1682 modulo_is_nan = modulo._isnan()
1683 if self_is_nan or other_is_nan or modulo_is_nan:
1684 if self_is_nan == 2:
1685 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001686 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001687 if other_is_nan == 2:
1688 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001689 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001690 if modulo_is_nan == 2:
1691 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001692 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001693 if self_is_nan:
1694 return self._fix_nan(context)
1695 if other_is_nan:
1696 return other._fix_nan(context)
1697 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001698
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001699 # check inputs: we apply same restrictions as Python's pow()
1700 if not (self._isinteger() and
1701 other._isinteger() and
1702 modulo._isinteger()):
1703 return context._raise_error(InvalidOperation,
1704 'pow() 3rd argument not allowed '
1705 'unless all arguments are integers')
1706 if other < 0:
1707 return context._raise_error(InvalidOperation,
1708 'pow() 2nd argument cannot be '
1709 'negative when 3rd argument specified')
1710 if not modulo:
1711 return context._raise_error(InvalidOperation,
1712 'pow() 3rd argument cannot be 0')
1713
1714 # additional restriction for decimal: the modulus must be less
1715 # than 10**prec in absolute value
1716 if modulo.adjusted() >= context.prec:
1717 return context._raise_error(InvalidOperation,
1718 'insufficient precision: pow() 3rd '
1719 'argument must not have more than '
1720 'precision digits')
1721
1722 # define 0**0 == NaN, for consistency with two-argument pow
1723 # (even though it hurts!)
1724 if not other and not self:
1725 return context._raise_error(InvalidOperation,
1726 'at least one of pow() 1st argument '
1727 'and 2nd argument must be nonzero ;'
1728 '0**0 is not defined')
1729
1730 # compute sign of result
1731 if other._iseven():
1732 sign = 0
1733 else:
1734 sign = self._sign
1735
1736 # convert modulo to a Python integer, and self and other to
1737 # Decimal integers (i.e. force their exponents to be >= 0)
1738 modulo = abs(int(modulo))
1739 base = _WorkRep(self.to_integral_value())
1740 exponent = _WorkRep(other.to_integral_value())
1741
1742 # compute result using integer pow()
1743 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1744 for i in range(exponent.exp):
1745 base = pow(base, 10, modulo)
1746 base = pow(base, exponent.int, modulo)
1747
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001748 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001749
1750 def _power_exact(self, other, p):
1751 """Attempt to compute self**other exactly.
1752
1753 Given Decimals self and other and an integer p, attempt to
1754 compute an exact result for the power self**other, with p
1755 digits of precision. Return None if self**other is not
1756 exactly representable in p digits.
1757
1758 Assumes that elimination of special cases has already been
1759 performed: self and other must both be nonspecial; self must
1760 be positive and not numerically equal to 1; other must be
1761 nonzero. For efficiency, other._exp should not be too large,
1762 so that 10**abs(other._exp) is a feasible calculation."""
1763
1764 # In the comments below, we write x for the value of self and
1765 # y for the value of other. Write x = xc*10**xe and y =
1766 # yc*10**ye.
1767
1768 # The main purpose of this method is to identify the *failure*
1769 # of x**y to be exactly representable with as little effort as
1770 # possible. So we look for cheap and easy tests that
1771 # eliminate the possibility of x**y being exact. Only if all
1772 # these tests are passed do we go on to actually compute x**y.
1773
1774 # Here's the main idea. First normalize both x and y. We
1775 # express y as a rational m/n, with m and n relatively prime
1776 # and n>0. Then for x**y to be exactly representable (at
1777 # *any* precision), xc must be the nth power of a positive
1778 # integer and xe must be divisible by n. If m is negative
1779 # then additionally xc must be a power of either 2 or 5, hence
1780 # a power of 2**n or 5**n.
1781 #
1782 # There's a limit to how small |y| can be: if y=m/n as above
1783 # then:
1784 #
1785 # (1) if xc != 1 then for the result to be representable we
1786 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1787 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1788 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1789 # representable.
1790 #
1791 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1792 # |y| < 1/|xe| then the result is not representable.
1793 #
1794 # Note that since x is not equal to 1, at least one of (1) and
1795 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1796 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1797 #
1798 # There's also a limit to how large y can be, at least if it's
1799 # positive: the normalized result will have coefficient xc**y,
1800 # so if it's representable then xc**y < 10**p, and y <
1801 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1802 # not exactly representable.
1803
1804 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1805 # so |y| < 1/xe and the result is not representable.
1806 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1807 # < 1/nbits(xc).
1808
1809 x = _WorkRep(self)
1810 xc, xe = x.int, x.exp
1811 while xc % 10 == 0:
1812 xc //= 10
1813 xe += 1
1814
1815 y = _WorkRep(other)
1816 yc, ye = y.int, y.exp
1817 while yc % 10 == 0:
1818 yc //= 10
1819 ye += 1
1820
1821 # case where xc == 1: result is 10**(xe*y), with xe*y
1822 # required to be an integer
1823 if xc == 1:
1824 if ye >= 0:
1825 exponent = xe*yc*10**ye
1826 else:
1827 exponent, remainder = divmod(xe*yc, 10**-ye)
1828 if remainder:
1829 return None
1830 if y.sign == 1:
1831 exponent = -exponent
1832 # if other is a nonnegative integer, use ideal exponent
1833 if other._isinteger() and other._sign == 0:
1834 ideal_exponent = self._exp*int(other)
1835 zeros = min(exponent-ideal_exponent, p-1)
1836 else:
1837 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001838 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001839
1840 # case where y is negative: xc must be either a power
1841 # of 2 or a power of 5.
1842 if y.sign == 1:
1843 last_digit = xc % 10
1844 if last_digit in (2,4,6,8):
1845 # quick test for power of 2
1846 if xc & -xc != xc:
1847 return None
1848 # now xc is a power of 2; e is its exponent
1849 e = _nbits(xc)-1
1850 # find e*y and xe*y; both must be integers
1851 if ye >= 0:
1852 y_as_int = yc*10**ye
1853 e = e*y_as_int
1854 xe = xe*y_as_int
1855 else:
1856 ten_pow = 10**-ye
1857 e, remainder = divmod(e*yc, ten_pow)
1858 if remainder:
1859 return None
1860 xe, remainder = divmod(xe*yc, ten_pow)
1861 if remainder:
1862 return None
1863
1864 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1865 return None
1866 xc = 5**e
1867
1868 elif last_digit == 5:
1869 # e >= log_5(xc) if xc is a power of 5; we have
1870 # equality all the way up to xc=5**2658
1871 e = _nbits(xc)*28//65
1872 xc, remainder = divmod(5**e, xc)
1873 if remainder:
1874 return None
1875 while xc % 5 == 0:
1876 xc //= 5
1877 e -= 1
1878 if ye >= 0:
1879 y_as_integer = yc*10**ye
1880 e = e*y_as_integer
1881 xe = xe*y_as_integer
1882 else:
1883 ten_pow = 10**-ye
1884 e, remainder = divmod(e*yc, ten_pow)
1885 if remainder:
1886 return None
1887 xe, remainder = divmod(xe*yc, ten_pow)
1888 if remainder:
1889 return None
1890 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1891 return None
1892 xc = 2**e
1893 else:
1894 return None
1895
1896 if xc >= 10**p:
1897 return None
1898 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001899 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001900
1901 # now y is positive; find m and n such that y = m/n
1902 if ye >= 0:
1903 m, n = yc*10**ye, 1
1904 else:
1905 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1906 return None
1907 xc_bits = _nbits(xc)
1908 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1909 return None
1910 m, n = yc, 10**(-ye)
1911 while m % 2 == n % 2 == 0:
1912 m //= 2
1913 n //= 2
1914 while m % 5 == n % 5 == 0:
1915 m //= 5
1916 n //= 5
1917
1918 # compute nth root of xc*10**xe
1919 if n > 1:
1920 # if 1 < xc < 2**n then xc isn't an nth power
1921 if xc != 1 and xc_bits <= n:
1922 return None
1923
1924 xe, rem = divmod(xe, n)
1925 if rem != 0:
1926 return None
1927
1928 # compute nth root of xc using Newton's method
1929 a = 1 << -(-_nbits(xc)//n) # initial estimate
1930 while True:
1931 q, r = divmod(xc, a**(n-1))
1932 if a <= q:
1933 break
1934 else:
1935 a = (a*(n-1) + q)//n
1936 if not (a == q and r == 0):
1937 return None
1938 xc = a
1939
1940 # now xc*10**xe is the nth root of the original xc*10**xe
1941 # compute mth power of xc*10**xe
1942
1943 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1944 # 10**p and the result is not representable.
1945 if xc > 1 and m > p*100//_log10_lb(xc):
1946 return None
1947 xc = xc**m
1948 xe *= m
1949 if xc > 10**p:
1950 return None
1951
1952 # by this point the result *is* exactly representable
1953 # adjust the exponent to get as close as possible to the ideal
1954 # exponent, if necessary
1955 str_xc = str(xc)
1956 if other._isinteger() and other._sign == 0:
1957 ideal_exponent = self._exp*int(other)
1958 zeros = min(xe-ideal_exponent, p-len(str_xc))
1959 else:
1960 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001961 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001962
1963 def __pow__(self, other, modulo=None, context=None):
1964 """Return self ** other [ % modulo].
1965
1966 With two arguments, compute self**other.
1967
1968 With three arguments, compute (self**other) % modulo. For the
1969 three argument form, the following restrictions on the
1970 arguments hold:
1971
1972 - all three arguments must be integral
1973 - other must be nonnegative
1974 - either self or other (or both) must be nonzero
1975 - modulo must be nonzero and must have at most p digits,
1976 where p is the context precision.
1977
1978 If any of these restrictions is violated the InvalidOperation
1979 flag is raised.
1980
1981 The result of pow(self, other, modulo) is identical to the
1982 result that would be obtained by computing (self**other) %
1983 modulo with unbounded precision, but is computed more
1984 efficiently. It is always exact.
1985 """
1986
1987 if modulo is not None:
1988 return self._power_modulo(other, modulo, context)
1989
1990 other = _convert_other(other)
1991 if other is NotImplemented:
1992 return other
1993
1994 if context is None:
1995 context = getcontext()
1996
1997 # either argument is a NaN => result is NaN
1998 ans = self._check_nans(other, context)
1999 if ans:
2000 return ans
2001
2002 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2003 if not other:
2004 if not self:
2005 return context._raise_error(InvalidOperation, '0 ** 0')
2006 else:
2007 return Dec_p1
2008
2009 # result has sign 1 iff self._sign is 1 and other is an odd integer
2010 result_sign = 0
2011 if self._sign == 1:
2012 if other._isinteger():
2013 if not other._iseven():
2014 result_sign = 1
2015 else:
2016 # -ve**noninteger = NaN
2017 # (-0)**noninteger = 0**noninteger
2018 if self:
2019 return context._raise_error(InvalidOperation,
2020 'x ** y with x negative and y not an integer')
2021 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002022 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002023
2024 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2025 if not self:
2026 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002027 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002028 else:
2029 return Infsign[result_sign]
2030
2031 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002032 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002033 if other._sign == 0:
2034 return Infsign[result_sign]
2035 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002036 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002037
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002038 # 1**other = 1, but the choice of exponent and the flags
2039 # depend on the exponent of self, and on whether other is a
2040 # positive integer, a negative integer, or neither
2041 if self == Dec_p1:
2042 if other._isinteger():
2043 # exp = max(self._exp*max(int(other), 0),
2044 # 1-context.prec) but evaluating int(other) directly
2045 # is dangerous until we know other is small (other
2046 # could be 1e999999999)
2047 if other._sign == 1:
2048 multiplier = 0
2049 elif other > context.prec:
2050 multiplier = context.prec
2051 else:
2052 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002053
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002054 exp = self._exp * multiplier
2055 if exp < 1-context.prec:
2056 exp = 1-context.prec
2057 context._raise_error(Rounded)
2058 else:
2059 context._raise_error(Inexact)
2060 context._raise_error(Rounded)
2061 exp = 1-context.prec
2062
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002063 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002064
2065 # compute adjusted exponent of self
2066 self_adj = self.adjusted()
2067
2068 # self ** infinity is infinity if self > 1, 0 if self < 1
2069 # self ** -infinity is infinity if self < 1, 0 if self > 1
2070 if other._isinfinity():
2071 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002072 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002073 else:
2074 return Infsign[result_sign]
2075
2076 # from here on, the result always goes through the call
2077 # to _fix at the end of this function.
2078 ans = None
2079
2080 # crude test to catch cases of extreme overflow/underflow. If
2081 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2082 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2083 # self**other >= 10**(Emax+1), so overflow occurs. The test
2084 # for underflow is similar.
2085 bound = self._log10_exp_bound() + other.adjusted()
2086 if (self_adj >= 0) == (other._sign == 0):
2087 # self > 1 and other +ve, or self < 1 and other -ve
2088 # possibility of overflow
2089 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002090 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002091 else:
2092 # self > 1 and other -ve, or self < 1 and other +ve
2093 # possibility of underflow to 0
2094 Etiny = context.Etiny()
2095 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002096 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002097
2098 # try for an exact result with precision +1
2099 if ans is None:
2100 ans = self._power_exact(other, context.prec + 1)
2101 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002102 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002103
2104 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2105 if ans is None:
2106 p = context.prec
2107 x = _WorkRep(self)
2108 xc, xe = x.int, x.exp
2109 y = _WorkRep(other)
2110 yc, ye = y.int, y.exp
2111 if y.sign == 1:
2112 yc = -yc
2113
2114 # compute correctly rounded result: start with precision +3,
2115 # then increase precision until result is unambiguously roundable
2116 extra = 3
2117 while True:
2118 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2119 if coeff % (5*10**(len(str(coeff))-p-1)):
2120 break
2121 extra += 3
2122
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002123 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002124
2125 # the specification says that for non-integer other we need to
2126 # raise Inexact, even when the result is actually exact. In
2127 # the same way, we need to raise Underflow here if the result
2128 # is subnormal. (The call to _fix will take care of raising
2129 # Rounded and Subnormal, as usual.)
2130 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002131 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002132 # pad with zeros up to length context.prec+1 if necessary
2133 if len(ans._int) <= context.prec:
2134 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002135 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2136 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002137 if ans.adjusted() < context.Emin:
2138 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002139
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002140 # unlike exp, ln and log10, the power function respects the
2141 # rounding mode; no need to use ROUND_HALF_EVEN here
2142 ans = ans._fix(context)
2143 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002144
2145 def __rpow__(self, other, context=None):
2146 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002147 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002148 if other is NotImplemented:
2149 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002150 return other.__pow__(self, context=context)
2151
2152 def normalize(self, context=None):
2153 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002154
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002155 if context is None:
2156 context = getcontext()
2157
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002158 if self._is_special:
2159 ans = self._check_nans(context=context)
2160 if ans:
2161 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002162
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002163 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002164 if dup._isinfinity():
2165 return dup
2166
2167 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002168 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002169 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002170 end = len(dup._int)
2171 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002172 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002173 exp += 1
2174 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002175 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002176
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002177 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002178 """Quantize self so its exponent is the same as that of exp.
2179
2180 Similar to self._rescale(exp._exp) but with error checking.
2181 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002182 exp = _convert_other(exp, raiseit=True)
2183
2184 if context is None:
2185 context = getcontext()
2186 if rounding is None:
2187 rounding = context.rounding
2188
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002189 if self._is_special or exp._is_special:
2190 ans = self._check_nans(exp, context)
2191 if ans:
2192 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002193
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002194 if exp._isinfinity() or self._isinfinity():
2195 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002196 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002197 return context._raise_error(InvalidOperation,
2198 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002199
2200 # if we're not watching exponents, do a simple rescale
2201 if not watchexp:
2202 ans = self._rescale(exp._exp, rounding)
2203 # raise Inexact and Rounded where appropriate
2204 if ans._exp > self._exp:
2205 context._raise_error(Rounded)
2206 if ans != self:
2207 context._raise_error(Inexact)
2208 return ans
2209
2210 # exp._exp should be between Etiny and Emax
2211 if not (context.Etiny() <= exp._exp <= context.Emax):
2212 return context._raise_error(InvalidOperation,
2213 'target exponent out of bounds in quantize')
2214
2215 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002216 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002217 return ans._fix(context)
2218
2219 self_adjusted = self.adjusted()
2220 if self_adjusted > context.Emax:
2221 return context._raise_error(InvalidOperation,
2222 'exponent of quantize result too large for current context')
2223 if self_adjusted - exp._exp + 1 > context.prec:
2224 return context._raise_error(InvalidOperation,
2225 'quantize result has too many digits for current context')
2226
2227 ans = self._rescale(exp._exp, rounding)
2228 if ans.adjusted() > context.Emax:
2229 return context._raise_error(InvalidOperation,
2230 'exponent of quantize result too large for current context')
2231 if len(ans._int) > context.prec:
2232 return context._raise_error(InvalidOperation,
2233 'quantize result has too many digits for current context')
2234
2235 # raise appropriate flags
2236 if ans._exp > self._exp:
2237 context._raise_error(Rounded)
2238 if ans != self:
2239 context._raise_error(Inexact)
2240 if ans and ans.adjusted() < context.Emin:
2241 context._raise_error(Subnormal)
2242
2243 # call to fix takes care of any necessary folddown
2244 ans = ans._fix(context)
2245 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002246
2247 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002248 """Return True if self and other have the same exponent; otherwise
2249 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002250
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002251 If either operand is a special value, the following rules are used:
2252 * return True if both operands are infinities
2253 * return True if both operands are NaNs
2254 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002255 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002256 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002257 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002258 return (self.is_nan() and other.is_nan() or
2259 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002260 return self._exp == other._exp
2261
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002262 def _rescale(self, exp, rounding):
2263 """Rescale self so that the exponent is exp, either by padding with zeros
2264 or by truncating digits, using the given rounding mode.
2265
2266 Specials are returned without change. This operation is
2267 quiet: it raises no flags, and uses no information from the
2268 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002269
2270 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002271 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002272 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002273 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002274 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002275 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002276 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002277
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002278 if self._exp >= exp:
2279 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002280 return _dec_from_triple(self._sign,
2281 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002282
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002283 # too many digits; round and lose data. If self.adjusted() <
2284 # exp-1, replace self by 10**(exp-1) before rounding
2285 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002286 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002287 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002288 digits = 0
2289 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002290 changed = this_function(digits)
2291 coeff = self._int[:digits] or '0'
2292 if changed == 1:
2293 coeff = str(int(coeff)+1)
2294 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002295
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002296 def to_integral_exact(self, rounding=None, context=None):
2297 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002298
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002299 If no rounding mode is specified, take the rounding mode from
2300 the context. This method raises the Rounded and Inexact flags
2301 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002302
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002303 See also: to_integral_value, which does exactly the same as
2304 this method except that it doesn't raise Inexact or Rounded.
2305 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002306 if self._is_special:
2307 ans = self._check_nans(context=context)
2308 if ans:
2309 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002310 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002311 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002312 return Decimal(self)
2313 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002314 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002315 if context is None:
2316 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002317 if rounding is None:
2318 rounding = context.rounding
2319 context._raise_error(Rounded)
2320 ans = self._rescale(0, rounding)
2321 if ans != self:
2322 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002323 return ans
2324
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002325 def to_integral_value(self, rounding=None, context=None):
2326 """Rounds to the nearest integer, without raising inexact, rounded."""
2327 if context is None:
2328 context = getcontext()
2329 if rounding is None:
2330 rounding = context.rounding
2331 if self._is_special:
2332 ans = self._check_nans(context=context)
2333 if ans:
2334 return ans
2335 return Decimal(self)
2336 if self._exp >= 0:
2337 return Decimal(self)
2338 else:
2339 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002340
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002341 # the method name changed, but we provide also the old one, for compatibility
2342 to_integral = to_integral_value
2343
2344 def sqrt(self, context=None):
2345 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002346 if self._is_special:
2347 ans = self._check_nans(context=context)
2348 if ans:
2349 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002350
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002351 if self._isinfinity() and self._sign == 0:
2352 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002353
2354 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002355 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002356 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002357 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002358
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002359 if context is None:
2360 context = getcontext()
2361
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002362 if self._sign == 1:
2363 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2364
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002365 # At this point self represents a positive number. Let p be
2366 # the desired precision and express self in the form c*100**e
2367 # with c a positive real number and e an integer, c and e
2368 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2369 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2370 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2371 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2372 # the closest integer to sqrt(c) with the even integer chosen
2373 # in the case of a tie.
2374 #
2375 # To ensure correct rounding in all cases, we use the
2376 # following trick: we compute the square root to an extra
2377 # place (precision p+1 instead of precision p), rounding down.
2378 # Then, if the result is inexact and its last digit is 0 or 5,
2379 # we increase the last digit to 1 or 6 respectively; if it's
2380 # exact we leave the last digit alone. Now the final round to
2381 # p places (or fewer in the case of underflow) will round
2382 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002383
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002384 # use an extra digit of precision
2385 prec = context.prec+1
2386
2387 # write argument in the form c*100**e where e = self._exp//2
2388 # is the 'ideal' exponent, to be used if the square root is
2389 # exactly representable. l is the number of 'digits' of c in
2390 # base 100, so that 100**(l-1) <= c < 100**l.
2391 op = _WorkRep(self)
2392 e = op.exp >> 1
2393 if op.exp & 1:
2394 c = op.int * 10
2395 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002396 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002397 c = op.int
2398 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002399
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002400 # rescale so that c has exactly prec base 100 'digits'
2401 shift = prec-l
2402 if shift >= 0:
2403 c *= 100**shift
2404 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002405 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002406 c, remainder = divmod(c, 100**-shift)
2407 exact = not remainder
2408 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002409
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002410 # find n = floor(sqrt(c)) using Newton's method
2411 n = 10**prec
2412 while True:
2413 q = c//n
2414 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002415 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002416 else:
2417 n = n + q >> 1
2418 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002419
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002420 if exact:
2421 # result is exact; rescale to use ideal exponent e
2422 if shift >= 0:
2423 # assert n % 10**shift == 0
2424 n //= 10**shift
2425 else:
2426 n *= 10**-shift
2427 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002428 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002429 # result is not exact; fix last digit as described above
2430 if n % 5 == 0:
2431 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002432
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002433 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002434
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002435 # round, and fit to current context
2436 context = context._shallow_copy()
2437 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002438 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002439 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002440
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002441 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002442
2443 def max(self, other, context=None):
2444 """Returns the larger value.
2445
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002446 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002447 NaN (and signals if one is sNaN). Also rounds.
2448 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002449 other = _convert_other(other, raiseit=True)
2450
2451 if context is None:
2452 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002453
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002454 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002455 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002456 # number is always returned
2457 sn = self._isnan()
2458 on = other._isnan()
2459 if sn or on:
2460 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002461 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002462 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002463 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002464 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002465
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002466 c = self.__cmp__(other)
2467 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002468 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002469 # then an ordering is applied:
2470 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002471 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002472 # positive sign and min returns the operand with the negative sign
2473 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002474 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002475 # the result. This is exactly the ordering used in compare_total.
2476 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002477
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002478 if c == -1:
2479 ans = other
2480 else:
2481 ans = self
2482
Christian Heimes2c181612007-12-17 20:04:13 +00002483 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002484
2485 def min(self, other, context=None):
2486 """Returns the smaller value.
2487
Guido van Rossumd8faa362007-04-27 19:54:29 +00002488 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002489 NaN (and signals if one is sNaN). Also rounds.
2490 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002491 other = _convert_other(other, raiseit=True)
2492
2493 if context is None:
2494 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002495
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002496 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002497 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002498 # number is always returned
2499 sn = self._isnan()
2500 on = other._isnan()
2501 if sn or on:
2502 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002503 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002504 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002505 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002506 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002507
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002508 c = self.__cmp__(other)
2509 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002510 c = self.compare_total(other)
2511
2512 if c == -1:
2513 ans = self
2514 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002515 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002516
Christian Heimes2c181612007-12-17 20:04:13 +00002517 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002518
2519 def _isinteger(self):
2520 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002521 if self._is_special:
2522 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002523 if self._exp >= 0:
2524 return True
2525 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002526 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002527
2528 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002529 """Returns True if self is even. Assumes self is an integer."""
2530 if not self or self._exp > 0:
2531 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002532 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002533
2534 def adjusted(self):
2535 """Return the adjusted exponent of self"""
2536 try:
2537 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002538 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002539 except TypeError:
2540 return 0
2541
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002542 def canonical(self, context=None):
2543 """Returns the same Decimal object.
2544
2545 As we do not have different encodings for the same number, the
2546 received object already is in its canonical form.
2547 """
2548 return self
2549
2550 def compare_signal(self, other, context=None):
2551 """Compares self to the other operand numerically.
2552
2553 It's pretty much like compare(), but all NaNs signal, with signaling
2554 NaNs taking precedence over quiet NaNs.
2555 """
2556 if context is None:
2557 context = getcontext()
2558
2559 self_is_nan = self._isnan()
2560 other_is_nan = other._isnan()
2561 if self_is_nan == 2:
2562 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002563 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002564 if other_is_nan == 2:
2565 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002566 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002567 if self_is_nan:
2568 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002569 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002570 if other_is_nan:
2571 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002572 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002573 return self.compare(other, context=context)
2574
2575 def compare_total(self, other):
2576 """Compares self to other using the abstract representations.
2577
2578 This is not like the standard compare, which use their numerical
2579 value. Note that a total ordering is defined for all possible abstract
2580 representations.
2581 """
2582 # if one is negative and the other is positive, it's easy
2583 if self._sign and not other._sign:
2584 return Dec_n1
2585 if not self._sign and other._sign:
2586 return Dec_p1
2587 sign = self._sign
2588
2589 # let's handle both NaN types
2590 self_nan = self._isnan()
2591 other_nan = other._isnan()
2592 if self_nan or other_nan:
2593 if self_nan == other_nan:
2594 if self._int < other._int:
2595 if sign:
2596 return Dec_p1
2597 else:
2598 return Dec_n1
2599 if self._int > other._int:
2600 if sign:
2601 return Dec_n1
2602 else:
2603 return Dec_p1
2604 return Dec_0
2605
2606 if sign:
2607 if self_nan == 1:
2608 return Dec_n1
2609 if other_nan == 1:
2610 return Dec_p1
2611 if self_nan == 2:
2612 return Dec_n1
2613 if other_nan == 2:
2614 return Dec_p1
2615 else:
2616 if self_nan == 1:
2617 return Dec_p1
2618 if other_nan == 1:
2619 return Dec_n1
2620 if self_nan == 2:
2621 return Dec_p1
2622 if other_nan == 2:
2623 return Dec_n1
2624
2625 if self < other:
2626 return Dec_n1
2627 if self > other:
2628 return Dec_p1
2629
2630 if self._exp < other._exp:
2631 if sign:
2632 return Dec_p1
2633 else:
2634 return Dec_n1
2635 if self._exp > other._exp:
2636 if sign:
2637 return Dec_n1
2638 else:
2639 return Dec_p1
2640 return Dec_0
2641
2642
2643 def compare_total_mag(self, other):
2644 """Compares self to other using abstract repr., ignoring sign.
2645
2646 Like compare_total, but with operand's sign ignored and assumed to be 0.
2647 """
2648 s = self.copy_abs()
2649 o = other.copy_abs()
2650 return s.compare_total(o)
2651
2652 def copy_abs(self):
2653 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002654 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002655
2656 def copy_negate(self):
2657 """Returns a copy with the sign inverted."""
2658 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002659 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002660 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002661 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002662
2663 def copy_sign(self, other):
2664 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002665 return _dec_from_triple(other._sign, self._int,
2666 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002667
2668 def exp(self, context=None):
2669 """Returns e ** self."""
2670
2671 if context is None:
2672 context = getcontext()
2673
2674 # exp(NaN) = NaN
2675 ans = self._check_nans(context=context)
2676 if ans:
2677 return ans
2678
2679 # exp(-Infinity) = 0
2680 if self._isinfinity() == -1:
2681 return Dec_0
2682
2683 # exp(0) = 1
2684 if not self:
2685 return Dec_p1
2686
2687 # exp(Infinity) = Infinity
2688 if self._isinfinity() == 1:
2689 return Decimal(self)
2690
2691 # the result is now guaranteed to be inexact (the true
2692 # mathematical result is transcendental). There's no need to
2693 # raise Rounded and Inexact here---they'll always be raised as
2694 # a result of the call to _fix.
2695 p = context.prec
2696 adj = self.adjusted()
2697
2698 # we only need to do any computation for quite a small range
2699 # of adjusted exponents---for example, -29 <= adj <= 10 for
2700 # the default context. For smaller exponent the result is
2701 # indistinguishable from 1 at the given precision, while for
2702 # larger exponent the result either overflows or underflows.
2703 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2704 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002705 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002706 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2707 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002708 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002709 elif self._sign == 0 and adj < -p:
2710 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002711 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002712 elif self._sign == 1 and adj < -p-1:
2713 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002714 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002715 # general case
2716 else:
2717 op = _WorkRep(self)
2718 c, e = op.int, op.exp
2719 if op.sign == 1:
2720 c = -c
2721
2722 # compute correctly rounded result: increase precision by
2723 # 3 digits at a time until we get an unambiguously
2724 # roundable result
2725 extra = 3
2726 while True:
2727 coeff, exp = _dexp(c, e, p+extra)
2728 if coeff % (5*10**(len(str(coeff))-p-1)):
2729 break
2730 extra += 3
2731
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002732 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002733
2734 # at this stage, ans should round correctly with *any*
2735 # rounding mode, not just with ROUND_HALF_EVEN
2736 context = context._shallow_copy()
2737 rounding = context._set_rounding(ROUND_HALF_EVEN)
2738 ans = ans._fix(context)
2739 context.rounding = rounding
2740
2741 return ans
2742
2743 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002744 """Return True if self is canonical; otherwise return False.
2745
2746 Currently, the encoding of a Decimal instance is always
2747 canonical, so this method returns True for any Decimal.
2748 """
2749 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002750
2751 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002752 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002753
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002754 A Decimal instance is considered finite if it is neither
2755 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002756 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002757 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002758
2759 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002760 """Return True if self is infinite; otherwise return False."""
2761 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002762
2763 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002764 """Return True if self is a qNaN or sNaN; otherwise return False."""
2765 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002766
2767 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002768 """Return True if self is a normal number; otherwise return False."""
2769 if self._is_special or not self:
2770 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002771 if context is None:
2772 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002773 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002774
2775 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002776 """Return True if self is a quiet NaN; otherwise return False."""
2777 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002778
2779 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002780 """Return True if self is negative; otherwise return False."""
2781 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002782
2783 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002784 """Return True if self is a signaling NaN; otherwise return False."""
2785 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002786
2787 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002788 """Return True if self is subnormal; otherwise return False."""
2789 if self._is_special or not self:
2790 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002791 if context is None:
2792 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002793 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002794
2795 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002796 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002797 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002798
2799 def _ln_exp_bound(self):
2800 """Compute a lower bound for the adjusted exponent of self.ln().
2801 In other words, compute r such that self.ln() >= 10**r. Assumes
2802 that self is finite and positive and that self != 1.
2803 """
2804
2805 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2806 adj = self._exp + len(self._int) - 1
2807 if adj >= 1:
2808 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2809 return len(str(adj*23//10)) - 1
2810 if adj <= -2:
2811 # argument <= 0.1
2812 return len(str((-1-adj)*23//10)) - 1
2813 op = _WorkRep(self)
2814 c, e = op.int, op.exp
2815 if adj == 0:
2816 # 1 < self < 10
2817 num = str(c-10**-e)
2818 den = str(c)
2819 return len(num) - len(den) - (num < den)
2820 # adj == -1, 0.1 <= self < 1
2821 return e + len(str(10**-e - c)) - 1
2822
2823
2824 def ln(self, context=None):
2825 """Returns the natural (base e) logarithm of self."""
2826
2827 if context is None:
2828 context = getcontext()
2829
2830 # ln(NaN) = NaN
2831 ans = self._check_nans(context=context)
2832 if ans:
2833 return ans
2834
2835 # ln(0.0) == -Infinity
2836 if not self:
2837 return negInf
2838
2839 # ln(Infinity) = Infinity
2840 if self._isinfinity() == 1:
2841 return Inf
2842
2843 # ln(1.0) == 0.0
2844 if self == Dec_p1:
2845 return Dec_0
2846
2847 # ln(negative) raises InvalidOperation
2848 if self._sign == 1:
2849 return context._raise_error(InvalidOperation,
2850 'ln of a negative value')
2851
2852 # result is irrational, so necessarily inexact
2853 op = _WorkRep(self)
2854 c, e = op.int, op.exp
2855 p = context.prec
2856
2857 # correctly rounded result: repeatedly increase precision by 3
2858 # until we get an unambiguously roundable result
2859 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2860 while True:
2861 coeff = _dlog(c, e, places)
2862 # assert len(str(abs(coeff)))-p >= 1
2863 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2864 break
2865 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002866 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002867
2868 context = context._shallow_copy()
2869 rounding = context._set_rounding(ROUND_HALF_EVEN)
2870 ans = ans._fix(context)
2871 context.rounding = rounding
2872 return ans
2873
2874 def _log10_exp_bound(self):
2875 """Compute a lower bound for the adjusted exponent of self.log10().
2876 In other words, find r such that self.log10() >= 10**r.
2877 Assumes that self is finite and positive and that self != 1.
2878 """
2879
2880 # For x >= 10 or x < 0.1 we only need a bound on the integer
2881 # part of log10(self), and this comes directly from the
2882 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2883 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2884 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2885
2886 adj = self._exp + len(self._int) - 1
2887 if adj >= 1:
2888 # self >= 10
2889 return len(str(adj))-1
2890 if adj <= -2:
2891 # self < 0.1
2892 return len(str(-1-adj))-1
2893 op = _WorkRep(self)
2894 c, e = op.int, op.exp
2895 if adj == 0:
2896 # 1 < self < 10
2897 num = str(c-10**-e)
2898 den = str(231*c)
2899 return len(num) - len(den) - (num < den) + 2
2900 # adj == -1, 0.1 <= self < 1
2901 num = str(10**-e-c)
2902 return len(num) + e - (num < "231") - 1
2903
2904 def log10(self, context=None):
2905 """Returns the base 10 logarithm of self."""
2906
2907 if context is None:
2908 context = getcontext()
2909
2910 # log10(NaN) = NaN
2911 ans = self._check_nans(context=context)
2912 if ans:
2913 return ans
2914
2915 # log10(0.0) == -Infinity
2916 if not self:
2917 return negInf
2918
2919 # log10(Infinity) = Infinity
2920 if self._isinfinity() == 1:
2921 return Inf
2922
2923 # log10(negative or -Infinity) raises InvalidOperation
2924 if self._sign == 1:
2925 return context._raise_error(InvalidOperation,
2926 'log10 of a negative value')
2927
2928 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002929 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002930 # answer may need rounding
2931 ans = Decimal(self._exp + len(self._int) - 1)
2932 else:
2933 # result is irrational, so necessarily inexact
2934 op = _WorkRep(self)
2935 c, e = op.int, op.exp
2936 p = context.prec
2937
2938 # correctly rounded result: repeatedly increase precision
2939 # until result is unambiguously roundable
2940 places = p-self._log10_exp_bound()+2
2941 while True:
2942 coeff = _dlog10(c, e, places)
2943 # assert len(str(abs(coeff)))-p >= 1
2944 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2945 break
2946 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002947 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002948
2949 context = context._shallow_copy()
2950 rounding = context._set_rounding(ROUND_HALF_EVEN)
2951 ans = ans._fix(context)
2952 context.rounding = rounding
2953 return ans
2954
2955 def logb(self, context=None):
2956 """ Returns the exponent of the magnitude of self's MSD.
2957
2958 The result is the integer which is the exponent of the magnitude
2959 of the most significant digit of self (as though it were truncated
2960 to a single digit while maintaining the value of that digit and
2961 without limiting the resulting exponent).
2962 """
2963 # logb(NaN) = NaN
2964 ans = self._check_nans(context=context)
2965 if ans:
2966 return ans
2967
2968 if context is None:
2969 context = getcontext()
2970
2971 # logb(+/-Inf) = +Inf
2972 if self._isinfinity():
2973 return Inf
2974
2975 # logb(0) = -Inf, DivisionByZero
2976 if not self:
2977 return context._raise_error(DivisionByZero, 'logb(0)', 1)
2978
2979 # otherwise, simply return the adjusted exponent of self, as a
2980 # Decimal. Note that no attempt is made to fit the result
2981 # into the current context.
2982 return Decimal(self.adjusted())
2983
2984 def _islogical(self):
2985 """Return True if self is a logical operand.
2986
Christian Heimes679db4a2008-01-18 09:56:22 +00002987 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002988 an exponent of 0, and a coefficient whose digits must all be
2989 either 0 or 1.
2990 """
2991 if self._sign != 0 or self._exp != 0:
2992 return False
2993 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002994 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002995 return False
2996 return True
2997
2998 def _fill_logical(self, context, opa, opb):
2999 dif = context.prec - len(opa)
3000 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003001 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003002 elif dif < 0:
3003 opa = opa[-context.prec:]
3004 dif = context.prec - len(opb)
3005 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003006 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003007 elif dif < 0:
3008 opb = opb[-context.prec:]
3009 return opa, opb
3010
3011 def logical_and(self, other, context=None):
3012 """Applies an 'and' operation between self and other's digits."""
3013 if context is None:
3014 context = getcontext()
3015 if not self._islogical() or not other._islogical():
3016 return context._raise_error(InvalidOperation)
3017
3018 # fill to context.prec
3019 (opa, opb) = self._fill_logical(context, self._int, other._int)
3020
3021 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003022 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3023 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003024
3025 def logical_invert(self, context=None):
3026 """Invert all its digits."""
3027 if context is None:
3028 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003029 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3030 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003031
3032 def logical_or(self, other, context=None):
3033 """Applies an 'or' operation between self and other's digits."""
3034 if context is None:
3035 context = getcontext()
3036 if not self._islogical() or not other._islogical():
3037 return context._raise_error(InvalidOperation)
3038
3039 # fill to context.prec
3040 (opa, opb) = self._fill_logical(context, self._int, other._int)
3041
3042 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003043 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3044 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003045
3046 def logical_xor(self, other, context=None):
3047 """Applies an 'xor' operation between self and other's digits."""
3048 if context is None:
3049 context = getcontext()
3050 if not self._islogical() or not other._islogical():
3051 return context._raise_error(InvalidOperation)
3052
3053 # fill to context.prec
3054 (opa, opb) = self._fill_logical(context, self._int, other._int)
3055
3056 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003057 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3058 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003059
3060 def max_mag(self, other, context=None):
3061 """Compares the values numerically with their sign ignored."""
3062 other = _convert_other(other, raiseit=True)
3063
3064 if context is None:
3065 context = getcontext()
3066
3067 if self._is_special or other._is_special:
3068 # If one operand is a quiet NaN and the other is number, then the
3069 # number is always returned
3070 sn = self._isnan()
3071 on = other._isnan()
3072 if sn or on:
3073 if on == 1 and sn != 2:
3074 return self._fix_nan(context)
3075 if sn == 1 and on != 2:
3076 return other._fix_nan(context)
3077 return self._check_nans(other, context)
3078
3079 c = self.copy_abs().__cmp__(other.copy_abs())
3080 if c == 0:
3081 c = self.compare_total(other)
3082
3083 if c == -1:
3084 ans = other
3085 else:
3086 ans = self
3087
Christian Heimes2c181612007-12-17 20:04:13 +00003088 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003089
3090 def min_mag(self, other, context=None):
3091 """Compares the values numerically with their sign ignored."""
3092 other = _convert_other(other, raiseit=True)
3093
3094 if context is None:
3095 context = getcontext()
3096
3097 if self._is_special or other._is_special:
3098 # If one operand is a quiet NaN and the other is number, then the
3099 # number is always returned
3100 sn = self._isnan()
3101 on = other._isnan()
3102 if sn or on:
3103 if on == 1 and sn != 2:
3104 return self._fix_nan(context)
3105 if sn == 1 and on != 2:
3106 return other._fix_nan(context)
3107 return self._check_nans(other, context)
3108
3109 c = self.copy_abs().__cmp__(other.copy_abs())
3110 if c == 0:
3111 c = self.compare_total(other)
3112
3113 if c == -1:
3114 ans = self
3115 else:
3116 ans = other
3117
Christian Heimes2c181612007-12-17 20:04:13 +00003118 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003119
3120 def next_minus(self, context=None):
3121 """Returns the largest representable number smaller than itself."""
3122 if context is None:
3123 context = getcontext()
3124
3125 ans = self._check_nans(context=context)
3126 if ans:
3127 return ans
3128
3129 if self._isinfinity() == -1:
3130 return negInf
3131 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003132 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003133
3134 context = context.copy()
3135 context._set_rounding(ROUND_FLOOR)
3136 context._ignore_all_flags()
3137 new_self = self._fix(context)
3138 if new_self != self:
3139 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003140 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3141 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003142
3143 def next_plus(self, context=None):
3144 """Returns the smallest representable number larger than itself."""
3145 if context is None:
3146 context = getcontext()
3147
3148 ans = self._check_nans(context=context)
3149 if ans:
3150 return ans
3151
3152 if self._isinfinity() == 1:
3153 return Inf
3154 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003155 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003156
3157 context = context.copy()
3158 context._set_rounding(ROUND_CEILING)
3159 context._ignore_all_flags()
3160 new_self = self._fix(context)
3161 if new_self != self:
3162 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003163 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3164 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003165
3166 def next_toward(self, other, context=None):
3167 """Returns the number closest to self, in the direction towards other.
3168
3169 The result is the closest representable number to self
3170 (excluding self) that is in the direction towards other,
3171 unless both have the same value. If the two operands are
3172 numerically equal, then the result is a copy of self with the
3173 sign set to be the same as the sign of other.
3174 """
3175 other = _convert_other(other, raiseit=True)
3176
3177 if context is None:
3178 context = getcontext()
3179
3180 ans = self._check_nans(other, context)
3181 if ans:
3182 return ans
3183
3184 comparison = self.__cmp__(other)
3185 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003186 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003187
3188 if comparison == -1:
3189 ans = self.next_plus(context)
3190 else: # comparison == 1
3191 ans = self.next_minus(context)
3192
3193 # decide which flags to raise using value of ans
3194 if ans._isinfinity():
3195 context._raise_error(Overflow,
3196 'Infinite result from next_toward',
3197 ans._sign)
3198 context._raise_error(Rounded)
3199 context._raise_error(Inexact)
3200 elif ans.adjusted() < context.Emin:
3201 context._raise_error(Underflow)
3202 context._raise_error(Subnormal)
3203 context._raise_error(Rounded)
3204 context._raise_error(Inexact)
3205 # if precision == 1 then we don't raise Clamped for a
3206 # result 0E-Etiny.
3207 if not ans:
3208 context._raise_error(Clamped)
3209
3210 return ans
3211
3212 def number_class(self, context=None):
3213 """Returns an indication of the class of self.
3214
3215 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003216 sNaN
3217 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003218 -Infinity
3219 -Normal
3220 -Subnormal
3221 -Zero
3222 +Zero
3223 +Subnormal
3224 +Normal
3225 +Infinity
3226 """
3227 if self.is_snan():
3228 return "sNaN"
3229 if self.is_qnan():
3230 return "NaN"
3231 inf = self._isinfinity()
3232 if inf == 1:
3233 return "+Infinity"
3234 if inf == -1:
3235 return "-Infinity"
3236 if self.is_zero():
3237 if self._sign:
3238 return "-Zero"
3239 else:
3240 return "+Zero"
3241 if context is None:
3242 context = getcontext()
3243 if self.is_subnormal(context=context):
3244 if self._sign:
3245 return "-Subnormal"
3246 else:
3247 return "+Subnormal"
3248 # just a normal, regular, boring number, :)
3249 if self._sign:
3250 return "-Normal"
3251 else:
3252 return "+Normal"
3253
3254 def radix(self):
3255 """Just returns 10, as this is Decimal, :)"""
3256 return Decimal(10)
3257
3258 def rotate(self, other, context=None):
3259 """Returns a rotated copy of self, value-of-other times."""
3260 if context is None:
3261 context = getcontext()
3262
3263 ans = self._check_nans(other, context)
3264 if ans:
3265 return ans
3266
3267 if other._exp != 0:
3268 return context._raise_error(InvalidOperation)
3269 if not (-context.prec <= int(other) <= context.prec):
3270 return context._raise_error(InvalidOperation)
3271
3272 if self._isinfinity():
3273 return Decimal(self)
3274
3275 # get values, pad if necessary
3276 torot = int(other)
3277 rotdig = self._int
3278 topad = context.prec - len(rotdig)
3279 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003280 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003281
3282 # let's rotate!
3283 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003284 return _dec_from_triple(self._sign,
3285 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003286
3287 def scaleb (self, other, context=None):
3288 """Returns self operand after adding the second value to its exp."""
3289 if context is None:
3290 context = getcontext()
3291
3292 ans = self._check_nans(other, context)
3293 if ans:
3294 return ans
3295
3296 if other._exp != 0:
3297 return context._raise_error(InvalidOperation)
3298 liminf = -2 * (context.Emax + context.prec)
3299 limsup = 2 * (context.Emax + context.prec)
3300 if not (liminf <= int(other) <= limsup):
3301 return context._raise_error(InvalidOperation)
3302
3303 if self._isinfinity():
3304 return Decimal(self)
3305
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003306 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003307 d = d._fix(context)
3308 return d
3309
3310 def shift(self, other, context=None):
3311 """Returns a shifted copy of self, value-of-other times."""
3312 if context is None:
3313 context = getcontext()
3314
3315 ans = self._check_nans(other, context)
3316 if ans:
3317 return ans
3318
3319 if other._exp != 0:
3320 return context._raise_error(InvalidOperation)
3321 if not (-context.prec <= int(other) <= context.prec):
3322 return context._raise_error(InvalidOperation)
3323
3324 if self._isinfinity():
3325 return Decimal(self)
3326
3327 # get values, pad if necessary
3328 torot = int(other)
3329 if not torot:
3330 return Decimal(self)
3331 rotdig = self._int
3332 topad = context.prec - len(rotdig)
3333 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003334 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003335
3336 # let's shift!
3337 if torot < 0:
3338 rotated = rotdig[:torot]
3339 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003340 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003341 rotated = rotated[-context.prec:]
3342
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003343 return _dec_from_triple(self._sign,
3344 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003345
Guido van Rossumd8faa362007-04-27 19:54:29 +00003346 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003347 def __reduce__(self):
3348 return (self.__class__, (str(self),))
3349
3350 def __copy__(self):
3351 if type(self) == Decimal:
3352 return self # I'm immutable; therefore I am my own clone
3353 return self.__class__(str(self))
3354
3355 def __deepcopy__(self, memo):
3356 if type(self) == Decimal:
3357 return self # My components are also immutable
3358 return self.__class__(str(self))
3359
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003360def _dec_from_triple(sign, coefficient, exponent, special=False):
3361 """Create a decimal instance directly, without any validation,
3362 normalization (e.g. removal of leading zeros) or argument
3363 conversion.
3364
3365 This function is for *internal use only*.
3366 """
3367
3368 self = object.__new__(Decimal)
3369 self._sign = sign
3370 self._int = coefficient
3371 self._exp = exponent
3372 self._is_special = special
3373
3374 return self
3375
Guido van Rossumd8faa362007-04-27 19:54:29 +00003376##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003377
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003378
3379# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003380rounding_functions = [name for name in Decimal.__dict__.keys()
3381 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003382for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003383 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003384 globalname = name[1:].upper()
3385 val = globals()[globalname]
3386 Decimal._pick_rounding_function[val] = name
3387
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003388del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003389
Thomas Wouters89f507f2006-12-13 04:49:30 +00003390class _ContextManager(object):
3391 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003392
Thomas Wouters89f507f2006-12-13 04:49:30 +00003393 Sets a copy of the supplied context in __enter__() and restores
3394 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003395 """
3396 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003397 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003398 def __enter__(self):
3399 self.saved_context = getcontext()
3400 setcontext(self.new_context)
3401 return self.new_context
3402 def __exit__(self, t, v, tb):
3403 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003404
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003405class Context(object):
3406 """Contains the context for a Decimal instance.
3407
3408 Contains:
3409 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003410 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003411 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003412 raised when it is caused. Otherwise, a value is
3413 substituted in.
3414 flags - When an exception is caused, flags[exception] is incremented.
3415 (Whether or not the trap_enabler is set)
3416 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003417 Emin - Minimum exponent
3418 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003419 capitals - If 1, 1*10^1 is printed as 1E+1.
3420 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003421 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003422 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003423
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003424 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003425 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003426 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003427 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003428 _ignored_flags=None):
3429 if flags is None:
3430 flags = []
3431 if _ignored_flags is None:
3432 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003433 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003434 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003435 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003436 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003437 for name, val in locals().items():
3438 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003439 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003440 else:
3441 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003442 del self.self
3443
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003444 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003445 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003446 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003447 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3448 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3449 % vars(self))
3450 names = [f.__name__ for f, v in self.flags.items() if v]
3451 s.append('flags=[' + ', '.join(names) + ']')
3452 names = [t.__name__ for t, v in self.traps.items() if v]
3453 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003454 return ', '.join(s) + ')'
3455
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003456 def clear_flags(self):
3457 """Reset all flags to zero"""
3458 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003459 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003460
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003461 def _shallow_copy(self):
3462 """Returns a shallow copy from self."""
Christian Heimes2c181612007-12-17 20:04:13 +00003463 nc = Context(self.prec, self.rounding, self.traps,
3464 self.flags, self.Emin, self.Emax,
3465 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003466 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003467
3468 def copy(self):
3469 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003470 nc = Context(self.prec, self.rounding, self.traps.copy(),
Christian Heimes2c181612007-12-17 20:04:13 +00003471 self.flags.copy(), self.Emin, self.Emax,
3472 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003473 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003474 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003475
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003476 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003477 """Handles an error
3478
3479 If the flag is in _ignored_flags, returns the default response.
3480 Otherwise, it increments the flag, then, if the corresponding
3481 trap_enabler is set, it reaises the exception. Otherwise, it returns
3482 the default value after incrementing the flag.
3483 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003484 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003485 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003486 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003487 return error().handle(self, *args)
3488
3489 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003490 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003491 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003492 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003493
3494 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003495 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003496 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003497
3498 def _ignore_all_flags(self):
3499 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003500 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003501
3502 def _ignore_flags(self, *flags):
3503 """Ignore the flags, if they are raised"""
3504 # Do not mutate-- This way, copies of a context leave the original
3505 # alone.
3506 self._ignored_flags = (self._ignored_flags + list(flags))
3507 return list(flags)
3508
3509 def _regard_flags(self, *flags):
3510 """Stop ignoring the flags, if they are raised"""
3511 if flags and isinstance(flags[0], (tuple,list)):
3512 flags = flags[0]
3513 for flag in flags:
3514 self._ignored_flags.remove(flag)
3515
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003516 def __hash__(self):
3517 """A Context cannot be hashed."""
3518 # We inherit object.__hash__, so we must deny this explicitly
Guido van Rossumd8faa362007-04-27 19:54:29 +00003519 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003520
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003521 def Etiny(self):
3522 """Returns Etiny (= Emin - prec + 1)"""
3523 return int(self.Emin - self.prec + 1)
3524
3525 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003526 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003527 return int(self.Emax - self.prec + 1)
3528
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003529 def _set_rounding(self, type):
3530 """Sets the rounding type.
3531
3532 Sets the rounding type, and returns the current (previous)
3533 rounding type. Often used like:
3534
3535 context = context.copy()
3536 # so you don't change the calling context
3537 # if an error occurs in the middle.
3538 rounding = context._set_rounding(ROUND_UP)
3539 val = self.__sub__(other, context=context)
3540 context._set_rounding(rounding)
3541
3542 This will make it round up for that operation.
3543 """
3544 rounding = self.rounding
3545 self.rounding= type
3546 return rounding
3547
Raymond Hettingerfed52962004-07-14 15:41:57 +00003548 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00003549 """Creates a new Decimal instance but using self as context.
3550
3551 This method implements the to-number operation of the
3552 IBM Decimal specification."""
3553
3554 if isinstance(num, str) and num != num.strip():
3555 return self._raise_error(ConversionSyntax,
3556 "no trailing or leading whitespace is "
3557 "permitted.")
3558
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003559 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003560 if d._isnan() and len(d._int) > self.prec - self._clamp:
3561 return self._raise_error(ConversionSyntax,
3562 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003563 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003564
Guido van Rossumd8faa362007-04-27 19:54:29 +00003565 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003566 def abs(self, a):
3567 """Returns the absolute value of the operand.
3568
3569 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003570 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003571 the plus operation on the operand.
3572
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003573 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003574 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003575 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003576 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003577 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003578 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003579 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003580 Decimal("101.5")
3581 """
3582 return a.__abs__(context=self)
3583
3584 def add(self, a, b):
3585 """Return the sum of the two operands.
3586
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003587 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003588 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003589 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003590 Decimal("1.02E+4")
3591 """
3592 return a.__add__(b, context=self)
3593
3594 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003595 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003596
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003597 def canonical(self, a):
3598 """Returns the same Decimal object.
3599
3600 As we do not have different encodings for the same number, the
3601 received object already is in its canonical form.
3602
3603 >>> ExtendedContext.canonical(Decimal('2.50'))
3604 Decimal("2.50")
3605 """
3606 return a.canonical(context=self)
3607
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003608 def compare(self, a, b):
3609 """Compares values numerically.
3610
3611 If the signs of the operands differ, a value representing each operand
3612 ('-1' if the operand is less than zero, '0' if the operand is zero or
3613 negative zero, or '1' if the operand is greater than zero) is used in
3614 place of that operand for the comparison instead of the actual
3615 operand.
3616
3617 The comparison is then effected by subtracting the second operand from
3618 the first and then returning a value according to the result of the
3619 subtraction: '-1' if the result is less than zero, '0' if the result is
3620 zero or negative zero, or '1' if the result is greater than zero.
3621
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003622 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003623 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003624 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003625 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003626 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003627 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003628 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003629 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003630 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003631 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003632 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003633 Decimal("-1")
3634 """
3635 return a.compare(b, context=self)
3636
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003637 def compare_signal(self, a, b):
3638 """Compares the values of the two operands numerically.
3639
3640 It's pretty much like compare(), but all NaNs signal, with signaling
3641 NaNs taking precedence over quiet NaNs.
3642
3643 >>> c = ExtendedContext
3644 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3645 Decimal("-1")
3646 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3647 Decimal("0")
3648 >>> c.flags[InvalidOperation] = 0
3649 >>> print(c.flags[InvalidOperation])
3650 0
3651 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3652 Decimal("NaN")
3653 >>> print(c.flags[InvalidOperation])
3654 1
3655 >>> c.flags[InvalidOperation] = 0
3656 >>> print(c.flags[InvalidOperation])
3657 0
3658 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3659 Decimal("NaN")
3660 >>> print(c.flags[InvalidOperation])
3661 1
3662 """
3663 return a.compare_signal(b, context=self)
3664
3665 def compare_total(self, a, b):
3666 """Compares two operands using their abstract representation.
3667
3668 This is not like the standard compare, which use their numerical
3669 value. Note that a total ordering is defined for all possible abstract
3670 representations.
3671
3672 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3673 Decimal("-1")
3674 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3675 Decimal("-1")
3676 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3677 Decimal("-1")
3678 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3679 Decimal("0")
3680 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3681 Decimal("1")
3682 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3683 Decimal("-1")
3684 """
3685 return a.compare_total(b)
3686
3687 def compare_total_mag(self, a, b):
3688 """Compares two operands using their abstract representation ignoring sign.
3689
3690 Like compare_total, but with operand's sign ignored and assumed to be 0.
3691 """
3692 return a.compare_total_mag(b)
3693
3694 def copy_abs(self, a):
3695 """Returns a copy of the operand with the sign set to 0.
3696
3697 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3698 Decimal("2.1")
3699 >>> ExtendedContext.copy_abs(Decimal('-100'))
3700 Decimal("100")
3701 """
3702 return a.copy_abs()
3703
3704 def copy_decimal(self, a):
3705 """Returns a copy of the decimal objet.
3706
3707 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3708 Decimal("2.1")
3709 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3710 Decimal("-1.00")
3711 """
3712 return Decimal(a)
3713
3714 def copy_negate(self, a):
3715 """Returns a copy of the operand with the sign inverted.
3716
3717 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3718 Decimal("-101.5")
3719 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3720 Decimal("101.5")
3721 """
3722 return a.copy_negate()
3723
3724 def copy_sign(self, a, b):
3725 """Copies the second operand's sign to the first one.
3726
3727 In detail, it returns a copy of the first operand with the sign
3728 equal to the sign of the second operand.
3729
3730 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3731 Decimal("1.50")
3732 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3733 Decimal("1.50")
3734 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3735 Decimal("-1.50")
3736 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3737 Decimal("-1.50")
3738 """
3739 return a.copy_sign(b)
3740
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003741 def divide(self, a, b):
3742 """Decimal division in a specified context.
3743
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003744 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003745 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003746 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003747 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003748 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003749 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003750 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003751 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003752 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003753 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003754 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003755 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003756 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003757 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003758 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003759 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003760 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003761 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003762 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003763 Decimal("1.20E+6")
3764 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003765 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003766
3767 def divide_int(self, a, b):
3768 """Divides two numbers and returns the integer part of the result.
3769
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003770 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003771 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003772 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003773 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003774 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003775 Decimal("3")
3776 """
3777 return a.__floordiv__(b, context=self)
3778
3779 def divmod(self, a, b):
3780 return a.__divmod__(b, context=self)
3781
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003782 def exp(self, a):
3783 """Returns e ** a.
3784
3785 >>> c = ExtendedContext.copy()
3786 >>> c.Emin = -999
3787 >>> c.Emax = 999
3788 >>> c.exp(Decimal('-Infinity'))
3789 Decimal("0")
3790 >>> c.exp(Decimal('-1'))
3791 Decimal("0.367879441")
3792 >>> c.exp(Decimal('0'))
3793 Decimal("1")
3794 >>> c.exp(Decimal('1'))
3795 Decimal("2.71828183")
3796 >>> c.exp(Decimal('0.693147181'))
3797 Decimal("2.00000000")
3798 >>> c.exp(Decimal('+Infinity'))
3799 Decimal("Infinity")
3800 """
3801 return a.exp(context=self)
3802
3803 def fma(self, a, b, c):
3804 """Returns a multiplied by b, plus c.
3805
3806 The first two operands are multiplied together, using multiply,
3807 the third operand is then added to the result of that
3808 multiplication, using add, all with only one final rounding.
3809
3810 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3811 Decimal("22")
3812 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3813 Decimal("-8")
3814 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3815 Decimal("1.38435736E+12")
3816 """
3817 return a.fma(b, c, context=self)
3818
3819 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003820 """Return True if the operand is canonical; otherwise return False.
3821
3822 Currently, the encoding of a Decimal instance is always
3823 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003824
3825 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003826 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003827 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003828 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003829
3830 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003831 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003832
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003833 A Decimal instance is considered finite if it is neither
3834 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003835
3836 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003837 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003838 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003839 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003840 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003841 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003842 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003843 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003844 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003845 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003846 """
3847 return a.is_finite()
3848
3849 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003850 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003851
3852 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003853 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003854 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003855 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003856 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003857 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003858 """
3859 return a.is_infinite()
3860
3861 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003862 """Return True if the operand is a qNaN or sNaN;
3863 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003864
3865 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003866 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003867 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003868 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003869 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003870 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003871 """
3872 return a.is_nan()
3873
3874 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003875 """Return True if the operand is a normal number;
3876 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003877
3878 >>> c = ExtendedContext.copy()
3879 >>> c.Emin = -999
3880 >>> c.Emax = 999
3881 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003882 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003883 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003884 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003885 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003886 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003887 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003888 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003889 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003890 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003891 """
3892 return a.is_normal(context=self)
3893
3894 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003895 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003896
3897 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003898 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003899 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003900 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003901 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003902 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003903 """
3904 return a.is_qnan()
3905
3906 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003907 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003908
3909 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003910 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003911 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003912 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003913 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003914 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003915 """
3916 return a.is_signed()
3917
3918 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003919 """Return True if the operand is a signaling NaN;
3920 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003921
3922 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003923 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003924 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003925 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003926 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003927 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003928 """
3929 return a.is_snan()
3930
3931 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003932 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003933
3934 >>> c = ExtendedContext.copy()
3935 >>> c.Emin = -999
3936 >>> c.Emax = 999
3937 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003938 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003939 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003940 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003941 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003942 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003943 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003944 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003945 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003946 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003947 """
3948 return a.is_subnormal(context=self)
3949
3950 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003951 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003952
3953 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003954 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003955 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003956 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003957 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003958 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003959 """
3960 return a.is_zero()
3961
3962 def ln(self, a):
3963 """Returns the natural (base e) logarithm of the operand.
3964
3965 >>> c = ExtendedContext.copy()
3966 >>> c.Emin = -999
3967 >>> c.Emax = 999
3968 >>> c.ln(Decimal('0'))
3969 Decimal("-Infinity")
3970 >>> c.ln(Decimal('1.000'))
3971 Decimal("0")
3972 >>> c.ln(Decimal('2.71828183'))
3973 Decimal("1.00000000")
3974 >>> c.ln(Decimal('10'))
3975 Decimal("2.30258509")
3976 >>> c.ln(Decimal('+Infinity'))
3977 Decimal("Infinity")
3978 """
3979 return a.ln(context=self)
3980
3981 def log10(self, a):
3982 """Returns the base 10 logarithm of the operand.
3983
3984 >>> c = ExtendedContext.copy()
3985 >>> c.Emin = -999
3986 >>> c.Emax = 999
3987 >>> c.log10(Decimal('0'))
3988 Decimal("-Infinity")
3989 >>> c.log10(Decimal('0.001'))
3990 Decimal("-3")
3991 >>> c.log10(Decimal('1.000'))
3992 Decimal("0")
3993 >>> c.log10(Decimal('2'))
3994 Decimal("0.301029996")
3995 >>> c.log10(Decimal('10'))
3996 Decimal("1")
3997 >>> c.log10(Decimal('70'))
3998 Decimal("1.84509804")
3999 >>> c.log10(Decimal('+Infinity'))
4000 Decimal("Infinity")
4001 """
4002 return a.log10(context=self)
4003
4004 def logb(self, a):
4005 """ Returns the exponent of the magnitude of the operand's MSD.
4006
4007 The result is the integer which is the exponent of the magnitude
4008 of the most significant digit of the operand (as though the
4009 operand were truncated to a single digit while maintaining the
4010 value of that digit and without limiting the resulting exponent).
4011
4012 >>> ExtendedContext.logb(Decimal('250'))
4013 Decimal("2")
4014 >>> ExtendedContext.logb(Decimal('2.50'))
4015 Decimal("0")
4016 >>> ExtendedContext.logb(Decimal('0.03'))
4017 Decimal("-2")
4018 >>> ExtendedContext.logb(Decimal('0'))
4019 Decimal("-Infinity")
4020 """
4021 return a.logb(context=self)
4022
4023 def logical_and(self, a, b):
4024 """Applies the logical operation 'and' between each operand's digits.
4025
4026 The operands must be both logical numbers.
4027
4028 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4029 Decimal("0")
4030 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4031 Decimal("0")
4032 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4033 Decimal("0")
4034 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4035 Decimal("1")
4036 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4037 Decimal("1000")
4038 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4039 Decimal("10")
4040 """
4041 return a.logical_and(b, context=self)
4042
4043 def logical_invert(self, a):
4044 """Invert all the digits in the operand.
4045
4046 The operand must be a logical number.
4047
4048 >>> ExtendedContext.logical_invert(Decimal('0'))
4049 Decimal("111111111")
4050 >>> ExtendedContext.logical_invert(Decimal('1'))
4051 Decimal("111111110")
4052 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4053 Decimal("0")
4054 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4055 Decimal("10101010")
4056 """
4057 return a.logical_invert(context=self)
4058
4059 def logical_or(self, a, b):
4060 """Applies the logical operation 'or' between each operand's digits.
4061
4062 The operands must be both logical numbers.
4063
4064 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4065 Decimal("0")
4066 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4067 Decimal("1")
4068 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4069 Decimal("1")
4070 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4071 Decimal("1")
4072 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4073 Decimal("1110")
4074 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4075 Decimal("1110")
4076 """
4077 return a.logical_or(b, context=self)
4078
4079 def logical_xor(self, a, b):
4080 """Applies the logical operation 'xor' between each operand's digits.
4081
4082 The operands must be both logical numbers.
4083
4084 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4085 Decimal("0")
4086 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4087 Decimal("1")
4088 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4089 Decimal("1")
4090 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4091 Decimal("0")
4092 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4093 Decimal("110")
4094 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4095 Decimal("1101")
4096 """
4097 return a.logical_xor(b, context=self)
4098
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004099 def max(self, a,b):
4100 """max compares two values numerically and returns the maximum.
4101
4102 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004103 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004104 operation. If they are numerically equal then the left-hand operand
4105 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004106 infinity) of the two operands is chosen as the result.
4107
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004108 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004109 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004110 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004111 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004112 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004113 Decimal("1")
4114 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4115 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004116 """
4117 return a.max(b, context=self)
4118
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004119 def max_mag(self, a, b):
4120 """Compares the values numerically with their sign ignored."""
4121 return a.max_mag(b, context=self)
4122
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004123 def min(self, a,b):
4124 """min compares two values numerically and returns the minimum.
4125
4126 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004127 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004128 operation. If they are numerically equal then the left-hand operand
4129 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004130 infinity) of the two operands is chosen as the result.
4131
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004132 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004133 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004134 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004135 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004136 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004137 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004138 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4139 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004140 """
4141 return a.min(b, context=self)
4142
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004143 def min_mag(self, a, b):
4144 """Compares the values numerically with their sign ignored."""
4145 return a.min_mag(b, context=self)
4146
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004147 def minus(self, a):
4148 """Minus corresponds to unary prefix minus in Python.
4149
4150 The operation is evaluated using the same rules as subtract; the
4151 operation minus(a) is calculated as subtract('0', a) where the '0'
4152 has the same exponent as the operand.
4153
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004154 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004155 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004156 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004157 Decimal("1.3")
4158 """
4159 return a.__neg__(context=self)
4160
4161 def multiply(self, a, b):
4162 """multiply multiplies two operands.
4163
4164 If either operand is a special value then the general rules apply.
4165 Otherwise, the operands are multiplied together ('long multiplication'),
4166 resulting in a number which may be as long as the sum of the lengths
4167 of the two operands.
4168
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004169 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004170 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004171 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004172 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004173 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004174 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004175 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004176 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004177 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004178 Decimal("4.28135971E+11")
4179 """
4180 return a.__mul__(b, context=self)
4181
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004182 def next_minus(self, a):
4183 """Returns the largest representable number smaller than a.
4184
4185 >>> c = ExtendedContext.copy()
4186 >>> c.Emin = -999
4187 >>> c.Emax = 999
4188 >>> ExtendedContext.next_minus(Decimal('1'))
4189 Decimal("0.999999999")
4190 >>> c.next_minus(Decimal('1E-1007'))
4191 Decimal("0E-1007")
4192 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4193 Decimal("-1.00000004")
4194 >>> c.next_minus(Decimal('Infinity'))
4195 Decimal("9.99999999E+999")
4196 """
4197 return a.next_minus(context=self)
4198
4199 def next_plus(self, a):
4200 """Returns the smallest representable number larger than a.
4201
4202 >>> c = ExtendedContext.copy()
4203 >>> c.Emin = -999
4204 >>> c.Emax = 999
4205 >>> ExtendedContext.next_plus(Decimal('1'))
4206 Decimal("1.00000001")
4207 >>> c.next_plus(Decimal('-1E-1007'))
4208 Decimal("-0E-1007")
4209 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4210 Decimal("-1.00000002")
4211 >>> c.next_plus(Decimal('-Infinity'))
4212 Decimal("-9.99999999E+999")
4213 """
4214 return a.next_plus(context=self)
4215
4216 def next_toward(self, a, b):
4217 """Returns the number closest to a, in direction towards b.
4218
4219 The result is the closest representable number from the first
4220 operand (but not the first operand) that is in the direction
4221 towards the second operand, unless the operands have the same
4222 value.
4223
4224 >>> c = ExtendedContext.copy()
4225 >>> c.Emin = -999
4226 >>> c.Emax = 999
4227 >>> c.next_toward(Decimal('1'), Decimal('2'))
4228 Decimal("1.00000001")
4229 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4230 Decimal("-0E-1007")
4231 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4232 Decimal("-1.00000002")
4233 >>> c.next_toward(Decimal('1'), Decimal('0'))
4234 Decimal("0.999999999")
4235 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4236 Decimal("0E-1007")
4237 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4238 Decimal("-1.00000004")
4239 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4240 Decimal("-0.00")
4241 """
4242 return a.next_toward(b, context=self)
4243
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004244 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004245 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004246
4247 Essentially a plus operation with all trailing zeros removed from the
4248 result.
4249
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004250 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004251 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004252 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004253 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004254 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004255 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004256 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004257 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004258 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004259 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004260 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004261 Decimal("0")
4262 """
4263 return a.normalize(context=self)
4264
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004265 def number_class(self, a):
4266 """Returns an indication of the class of the operand.
4267
4268 The class is one of the following strings:
4269 -sNaN
4270 -NaN
4271 -Infinity
4272 -Normal
4273 -Subnormal
4274 -Zero
4275 +Zero
4276 +Subnormal
4277 +Normal
4278 +Infinity
4279
4280 >>> c = Context(ExtendedContext)
4281 >>> c.Emin = -999
4282 >>> c.Emax = 999
4283 >>> c.number_class(Decimal('Infinity'))
4284 '+Infinity'
4285 >>> c.number_class(Decimal('1E-10'))
4286 '+Normal'
4287 >>> c.number_class(Decimal('2.50'))
4288 '+Normal'
4289 >>> c.number_class(Decimal('0.1E-999'))
4290 '+Subnormal'
4291 >>> c.number_class(Decimal('0'))
4292 '+Zero'
4293 >>> c.number_class(Decimal('-0'))
4294 '-Zero'
4295 >>> c.number_class(Decimal('-0.1E-999'))
4296 '-Subnormal'
4297 >>> c.number_class(Decimal('-1E-10'))
4298 '-Normal'
4299 >>> c.number_class(Decimal('-2.50'))
4300 '-Normal'
4301 >>> c.number_class(Decimal('-Infinity'))
4302 '-Infinity'
4303 >>> c.number_class(Decimal('NaN'))
4304 'NaN'
4305 >>> c.number_class(Decimal('-NaN'))
4306 'NaN'
4307 >>> c.number_class(Decimal('sNaN'))
4308 'sNaN'
4309 """
4310 return a.number_class(context=self)
4311
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004312 def plus(self, a):
4313 """Plus corresponds to unary prefix plus in Python.
4314
4315 The operation is evaluated using the same rules as add; the
4316 operation plus(a) is calculated as add('0', a) where the '0'
4317 has the same exponent as the operand.
4318
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004319 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004320 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004321 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004322 Decimal("-1.3")
4323 """
4324 return a.__pos__(context=self)
4325
4326 def power(self, a, b, modulo=None):
4327 """Raises a to the power of b, to modulo if given.
4328
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004329 With two arguments, compute a**b. If a is negative then b
4330 must be integral. The result will be inexact unless b is
4331 integral and the result is finite and can be expressed exactly
4332 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004333
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004334 With three arguments, compute (a**b) % modulo. For the
4335 three argument form, the following restrictions on the
4336 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004337
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004338 - all three arguments must be integral
4339 - b must be nonnegative
4340 - at least one of a or b must be nonzero
4341 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004342
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004343 The result of pow(a, b, modulo) is identical to the result
4344 that would be obtained by computing (a**b) % modulo with
4345 unbounded precision, but is computed more efficiently. It is
4346 always exact.
4347
4348 >>> c = ExtendedContext.copy()
4349 >>> c.Emin = -999
4350 >>> c.Emax = 999
4351 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004352 Decimal("8")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004353 >>> c.power(Decimal('-2'), Decimal('3'))
4354 Decimal("-8")
4355 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004356 Decimal("0.125")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004357 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004358 Decimal("69.7575744")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004359 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4360 Decimal("2.00000000")
4361 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004362 Decimal("0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004363 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004364 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004365 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004366 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004367 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004368 Decimal("-0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004369 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004370 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004371 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004372 Decimal("-Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004373 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004374 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004375 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004376 Decimal("NaN")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004377
4378 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4379 Decimal("11")
4380 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4381 Decimal("-11")
4382 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4383 Decimal("1")
4384 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4385 Decimal("11")
4386 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4387 Decimal("11729830")
4388 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4389 Decimal("-0")
4390 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4391 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004392 """
4393 return a.__pow__(b, modulo, context=self)
4394
4395 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004396 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004397
4398 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004399 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004400 exponent is being increased), multiplied by a positive power of ten (if
4401 the exponent is being decreased), or is unchanged (if the exponent is
4402 already equal to that of the right-hand operand).
4403
4404 Unlike other operations, if the length of the coefficient after the
4405 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004406 operation condition is raised. This guarantees that, unless there is
4407 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004408 equal to that of the right-hand operand.
4409
4410 Also unlike other operations, quantize will never raise Underflow, even
4411 if the result is subnormal and inexact.
4412
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004413 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004414 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004415 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004416 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004417 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004418 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004419 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004420 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004421 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004422 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004423 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004424 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004425 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004426 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004427 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004428 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004429 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004430 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004431 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004432 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004433 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004434 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004435 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004436 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004437 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004438 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004439 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004440 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004441 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004442 Decimal("2E+2")
4443 """
4444 return a.quantize(b, context=self)
4445
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004446 def radix(self):
4447 """Just returns 10, as this is Decimal, :)
4448
4449 >>> ExtendedContext.radix()
4450 Decimal("10")
4451 """
4452 return Decimal(10)
4453
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004454 def remainder(self, a, b):
4455 """Returns the remainder from integer division.
4456
4457 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004458 calculating integer division as described for divide-integer, rounded
4459 to precision digits if necessary. The sign of the result, if
4460 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004461
4462 This operation will fail under the same conditions as integer division
4463 (that is, if integer division on the same two operands would fail, the
4464 remainder cannot be calculated).
4465
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004466 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004467 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004468 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004469 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004470 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004471 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004472 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004473 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004474 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004475 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004476 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004477 Decimal("1.0")
4478 """
4479 return a.__mod__(b, context=self)
4480
4481 def remainder_near(self, a, b):
4482 """Returns to be "a - b * n", where n is the integer nearest the exact
4483 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004484 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004485 sign of a.
4486
4487 This operation will fail under the same conditions as integer division
4488 (that is, if integer division on the same two operands would fail, the
4489 remainder cannot be calculated).
4490
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004491 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004492 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004493 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004494 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004495 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004496 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004497 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004498 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004499 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004500 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004501 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004502 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004503 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004504 Decimal("-0.3")
4505 """
4506 return a.remainder_near(b, context=self)
4507
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004508 def rotate(self, a, b):
4509 """Returns a rotated copy of a, b times.
4510
4511 The coefficient of the result is a rotated copy of the digits in
4512 the coefficient of the first operand. The number of places of
4513 rotation is taken from the absolute value of the second operand,
4514 with the rotation being to the left if the second operand is
4515 positive or to the right otherwise.
4516
4517 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4518 Decimal("400000003")
4519 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4520 Decimal("12")
4521 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4522 Decimal("891234567")
4523 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4524 Decimal("123456789")
4525 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4526 Decimal("345678912")
4527 """
4528 return a.rotate(b, context=self)
4529
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004530 def same_quantum(self, a, b):
4531 """Returns True if the two operands have the same exponent.
4532
4533 The result is never affected by either the sign or the coefficient of
4534 either operand.
4535
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004536 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004537 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004538 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004539 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004540 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004541 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004542 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004543 True
4544 """
4545 return a.same_quantum(b)
4546
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004547 def scaleb (self, a, b):
4548 """Returns the first operand after adding the second value its exp.
4549
4550 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4551 Decimal("0.0750")
4552 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4553 Decimal("7.50")
4554 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4555 Decimal("7.50E+3")
4556 """
4557 return a.scaleb (b, context=self)
4558
4559 def shift(self, a, b):
4560 """Returns a shifted copy of a, b times.
4561
4562 The coefficient of the result is a shifted copy of the digits
4563 in the coefficient of the first operand. The number of places
4564 to shift is taken from the absolute value of the second operand,
4565 with the shift being to the left if the second operand is
4566 positive or to the right otherwise. Digits shifted into the
4567 coefficient are zeros.
4568
4569 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4570 Decimal("400000000")
4571 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4572 Decimal("0")
4573 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4574 Decimal("1234567")
4575 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4576 Decimal("123456789")
4577 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4578 Decimal("345678900")
4579 """
4580 return a.shift(b, context=self)
4581
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004582 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004583 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004584
4585 If the result must be inexact, it is rounded using the round-half-even
4586 algorithm.
4587
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004588 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004589 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004590 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004591 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004592 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004593 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004594 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004595 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004596 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004597 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004598 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004599 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004600 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004601 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004602 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004603 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004604 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004605 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004606 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004607 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004608 """
4609 return a.sqrt(context=self)
4610
4611 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004612 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004613
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004614 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004615 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004616 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004617 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004618 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004619 Decimal("-0.77")
4620 """
4621 return a.__sub__(b, context=self)
4622
4623 def to_eng_string(self, a):
4624 """Converts a number to a string, using scientific notation.
4625
4626 The operation is not affected by the context.
4627 """
4628 return a.to_eng_string(context=self)
4629
4630 def to_sci_string(self, a):
4631 """Converts a number to a string, using scientific notation.
4632
4633 The operation is not affected by the context.
4634 """
4635 return a.__str__(context=self)
4636
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004637 def to_integral_exact(self, a):
4638 """Rounds to an integer.
4639
4640 When the operand has a negative exponent, the result is the same
4641 as using the quantize() operation using the given operand as the
4642 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4643 of the operand as the precision setting; Inexact and Rounded flags
4644 are allowed in this operation. The rounding mode is taken from the
4645 context.
4646
4647 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4648 Decimal("2")
4649 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4650 Decimal("100")
4651 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4652 Decimal("100")
4653 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4654 Decimal("102")
4655 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4656 Decimal("-102")
4657 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4658 Decimal("1.0E+6")
4659 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4660 Decimal("7.89E+77")
4661 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4662 Decimal("-Infinity")
4663 """
4664 return a.to_integral_exact(context=self)
4665
4666 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004667 """Rounds to an integer.
4668
4669 When the operand has a negative exponent, the result is the same
4670 as using the quantize() operation using the given operand as the
4671 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4672 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004673 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004674
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004675 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004676 Decimal("2")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004677 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004678 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004679 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004680 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004681 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004682 Decimal("102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004683 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004684 Decimal("-102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004685 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004686 Decimal("1.0E+6")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004687 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004688 Decimal("7.89E+77")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004689 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004690 Decimal("-Infinity")
4691 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004692 return a.to_integral_value(context=self)
4693
4694 # the method name changed, but we provide also the old one, for compatibility
4695 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004696
4697class _WorkRep(object):
4698 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004699 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004700 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004701 # exp: None, int, or string
4702
4703 def __init__(self, value=None):
4704 if value is None:
4705 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004706 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004707 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004708 elif isinstance(value, Decimal):
4709 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00004710 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004711 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004712 else:
4713 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004714 self.sign = value[0]
4715 self.int = value[1]
4716 self.exp = value[2]
4717
4718 def __repr__(self):
4719 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4720
4721 __str__ = __repr__
4722
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004723
4724
Christian Heimes2c181612007-12-17 20:04:13 +00004725def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004726 """Normalizes op1, op2 to have the same exp and length of coefficient.
4727
4728 Done during addition.
4729 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004730 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004731 tmp = op2
4732 other = op1
4733 else:
4734 tmp = op1
4735 other = op2
4736
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004737 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4738 # Then adding 10**exp to tmp has the same effect (after rounding)
4739 # as adding any positive quantity smaller than 10**exp; similarly
4740 # for subtraction. So if other is smaller than 10**exp we replace
4741 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00004742 tmp_len = len(str(tmp.int))
4743 other_len = len(str(other.int))
4744 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4745 if other_len + other.exp - 1 < exp:
4746 other.int = 1
4747 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004748
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004749 tmp.int *= 10 ** (tmp.exp - other.exp)
4750 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004751 return op1, op2
4752
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004753##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004754
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004755# This function from Tim Peters was taken from here:
4756# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4757# The correction being in the function definition is for speed, and
4758# the whole function is not resolved with math.log because of avoiding
4759# the use of floats.
4760def _nbits(n, correction = {
4761 '0': 4, '1': 3, '2': 2, '3': 2,
4762 '4': 1, '5': 1, '6': 1, '7': 1,
4763 '8': 0, '9': 0, 'a': 0, 'b': 0,
4764 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4765 """Number of bits in binary representation of the positive integer n,
4766 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004767 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004768 if n < 0:
4769 raise ValueError("The argument to _nbits should be nonnegative.")
4770 hex_n = "%x" % n
4771 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004772
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004773def _sqrt_nearest(n, a):
4774 """Closest integer to the square root of the positive integer n. a is
4775 an initial approximation to the square root. Any positive integer
4776 will do for a, but the closer a is to the square root of n the
4777 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004778
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004779 """
4780 if n <= 0 or a <= 0:
4781 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4782
4783 b=0
4784 while a != b:
4785 b, a = a, a--n//a>>1
4786 return a
4787
4788def _rshift_nearest(x, shift):
4789 """Given an integer x and a nonnegative integer shift, return closest
4790 integer to x / 2**shift; use round-to-even in case of a tie.
4791
4792 """
4793 b, q = 1 << shift, x >> shift
4794 return q + (2*(x & (b-1)) + (q&1) > b)
4795
4796def _div_nearest(a, b):
4797 """Closest integer to a/b, a and b positive integers; rounds to even
4798 in the case of a tie.
4799
4800 """
4801 q, r = divmod(a, b)
4802 return q + (2*r + (q&1) > b)
4803
4804def _ilog(x, M, L = 8):
4805 """Integer approximation to M*log(x/M), with absolute error boundable
4806 in terms only of x/M.
4807
4808 Given positive integers x and M, return an integer approximation to
4809 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4810 between the approximation and the exact result is at most 22. For
4811 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4812 both cases these are upper bounds on the error; it will usually be
4813 much smaller."""
4814
4815 # The basic algorithm is the following: let log1p be the function
4816 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4817 # the reduction
4818 #
4819 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4820 #
4821 # repeatedly until the argument to log1p is small (< 2**-L in
4822 # absolute value). For small y we can use the Taylor series
4823 # expansion
4824 #
4825 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4826 #
4827 # truncating at T such that y**T is small enough. The whole
4828 # computation is carried out in a form of fixed-point arithmetic,
4829 # with a real number z being represented by an integer
4830 # approximation to z*M. To avoid loss of precision, the y below
4831 # is actually an integer approximation to 2**R*y*M, where R is the
4832 # number of reductions performed so far.
4833
4834 y = x-M
4835 # argument reduction; R = number of reductions performed
4836 R = 0
4837 while (R <= L and abs(y) << L-R >= M or
4838 R > L and abs(y) >> R-L >= M):
4839 y = _div_nearest((M*y) << 1,
4840 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4841 R += 1
4842
4843 # Taylor series with T terms
4844 T = -int(-10*len(str(M))//(3*L))
4845 yshift = _rshift_nearest(y, R)
4846 w = _div_nearest(M, T)
4847 for k in range(T-1, 0, -1):
4848 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4849
4850 return _div_nearest(w*y, M)
4851
4852def _dlog10(c, e, p):
4853 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4854 approximation to 10**p * log10(c*10**e), with an absolute error of
4855 at most 1. Assumes that c*10**e is not exactly 1."""
4856
4857 # increase precision by 2; compensate for this by dividing
4858 # final result by 100
4859 p += 2
4860
4861 # write c*10**e as d*10**f with either:
4862 # f >= 0 and 1 <= d <= 10, or
4863 # f <= 0 and 0.1 <= d <= 1.
4864 # Thus for c*10**e close to 1, f = 0
4865 l = len(str(c))
4866 f = e+l - (e+l >= 1)
4867
4868 if p > 0:
4869 M = 10**p
4870 k = e+p-f
4871 if k >= 0:
4872 c *= 10**k
4873 else:
4874 c = _div_nearest(c, 10**-k)
4875
4876 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004877 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004878 log_d = _div_nearest(log_d*M, log_10)
4879 log_tenpower = f*M # exact
4880 else:
4881 log_d = 0 # error < 2.31
4882 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4883
4884 return _div_nearest(log_tenpower+log_d, 100)
4885
4886def _dlog(c, e, p):
4887 """Given integers c, e and p with c > 0, compute an integer
4888 approximation to 10**p * log(c*10**e), with an absolute error of
4889 at most 1. Assumes that c*10**e is not exactly 1."""
4890
4891 # Increase precision by 2. The precision increase is compensated
4892 # for at the end with a division by 100.
4893 p += 2
4894
4895 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4896 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4897 # as 10**p * log(d) + 10**p*f * log(10).
4898 l = len(str(c))
4899 f = e+l - (e+l >= 1)
4900
4901 # compute approximation to 10**p*log(d), with error < 27
4902 if p > 0:
4903 k = e+p-f
4904 if k >= 0:
4905 c *= 10**k
4906 else:
4907 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4908
4909 # _ilog magnifies existing error in c by a factor of at most 10
4910 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4911 else:
4912 # p <= 0: just approximate the whole thing by 0; error < 2.31
4913 log_d = 0
4914
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004915 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004916 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004917 extra = len(str(abs(f)))-1
4918 if p + extra >= 0:
4919 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4920 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4921 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004922 else:
4923 f_log_ten = 0
4924 else:
4925 f_log_ten = 0
4926
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004927 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004928 return _div_nearest(f_log_ten + log_d, 100)
4929
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004930class _Log10Memoize(object):
4931 """Class to compute, store, and allow retrieval of, digits of the
4932 constant log(10) = 2.302585.... This constant is needed by
4933 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4934 def __init__(self):
4935 self.digits = "23025850929940456840179914546843642076011014886"
4936
4937 def getdigits(self, p):
4938 """Given an integer p >= 0, return floor(10**p)*log(10).
4939
4940 For example, self.getdigits(3) returns 2302.
4941 """
4942 # digits are stored as a string, for quick conversion to
4943 # integer in the case that we've already computed enough
4944 # digits; the stored digits should always be correct
4945 # (truncated, not rounded to nearest).
4946 if p < 0:
4947 raise ValueError("p should be nonnegative")
4948
4949 if p >= len(self.digits):
4950 # compute p+3, p+6, p+9, ... digits; continue until at
4951 # least one of the extra digits is nonzero
4952 extra = 3
4953 while True:
4954 # compute p+extra digits, correct to within 1ulp
4955 M = 10**(p+extra+2)
4956 digits = str(_div_nearest(_ilog(10*M, M), 100))
4957 if digits[-extra:] != '0'*extra:
4958 break
4959 extra += 3
4960 # keep all reliable digits so far; remove trailing zeros
4961 # and next nonzero digit
4962 self.digits = digits.rstrip('0')[:-1]
4963 return int(self.digits[:p+1])
4964
4965_log10_digits = _Log10Memoize().getdigits
4966
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004967def _iexp(x, M, L=8):
4968 """Given integers x and M, M > 0, such that x/M is small in absolute
4969 value, compute an integer approximation to M*exp(x/M). For 0 <=
4970 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4971 is usually much smaller)."""
4972
4973 # Algorithm: to compute exp(z) for a real number z, first divide z
4974 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4975 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4976 # series
4977 #
4978 # expm1(x) = x + x**2/2! + x**3/3! + ...
4979 #
4980 # Now use the identity
4981 #
4982 # expm1(2x) = expm1(x)*(expm1(x)+2)
4983 #
4984 # R times to compute the sequence expm1(z/2**R),
4985 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
4986
4987 # Find R such that x/2**R/M <= 2**-L
4988 R = _nbits((x<<L)//M)
4989
4990 # Taylor series. (2**L)**T > M
4991 T = -int(-10*len(str(M))//(3*L))
4992 y = _div_nearest(x, T)
4993 Mshift = M<<R
4994 for i in range(T-1, 0, -1):
4995 y = _div_nearest(x*(Mshift + y), Mshift * i)
4996
4997 # Expansion
4998 for k in range(R-1, -1, -1):
4999 Mshift = M<<(k+2)
5000 y = _div_nearest(y*(y+Mshift), Mshift)
5001
5002 return M+y
5003
5004def _dexp(c, e, p):
5005 """Compute an approximation to exp(c*10**e), with p decimal places of
5006 precision.
5007
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005008 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005009
5010 10**(p-1) <= d <= 10**p, and
5011 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5012
5013 In other words, d*10**f is an approximation to exp(c*10**e) with p
5014 digits of precision, and with an error in d of at most 1. This is
5015 almost, but not quite, the same as the error being < 1ulp: when d
5016 = 10**(p-1) the error could be up to 10 ulp."""
5017
5018 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5019 p += 2
5020
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005021 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005022 extra = max(0, e + len(str(c)) - 1)
5023 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005024
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005025 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005026 # rounding down
5027 shift = e+q
5028 if shift >= 0:
5029 cshift = c*10**shift
5030 else:
5031 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005032 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005033
5034 # reduce remainder back to original precision
5035 rem = _div_nearest(rem, 10**extra)
5036
5037 # error in result of _iexp < 120; error after division < 0.62
5038 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5039
5040def _dpower(xc, xe, yc, ye, p):
5041 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5042 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5043
5044 10**(p-1) <= c <= 10**p, and
5045 (c-1)*10**e < x**y < (c+1)*10**e
5046
5047 in other words, c*10**e is an approximation to x**y with p digits
5048 of precision, and with an error in c of at most 1. (This is
5049 almost, but not quite, the same as the error being < 1ulp: when c
5050 == 10**(p-1) we can only guarantee error < 10ulp.)
5051
5052 We assume that: x is positive and not equal to 1, and y is nonzero.
5053 """
5054
5055 # Find b such that 10**(b-1) <= |y| <= 10**b
5056 b = len(str(abs(yc))) + ye
5057
5058 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5059 lxc = _dlog(xc, xe, p+b+1)
5060
5061 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5062 shift = ye-b
5063 if shift >= 0:
5064 pc = lxc*yc*10**shift
5065 else:
5066 pc = _div_nearest(lxc*yc, 10**-shift)
5067
5068 if pc == 0:
5069 # we prefer a result that isn't exactly 1; this makes it
5070 # easier to compute a correctly rounded result in __pow__
5071 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5072 coeff, exp = 10**(p-1)+1, 1-p
5073 else:
5074 coeff, exp = 10**p-1, -p
5075 else:
5076 coeff, exp = _dexp(pc, -(p+1), p+1)
5077 coeff = _div_nearest(coeff, 10)
5078 exp += 1
5079
5080 return coeff, exp
5081
5082def _log10_lb(c, correction = {
5083 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5084 '6': 23, '7': 16, '8': 10, '9': 5}):
5085 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5086 if c <= 0:
5087 raise ValueError("The argument to _log10_lb should be nonnegative.")
5088 str_c = str(c)
5089 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005090
Guido van Rossumd8faa362007-04-27 19:54:29 +00005091##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005092
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005093def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005094 """Convert other to Decimal.
5095
5096 Verifies that it's ok to use in an implicit construction.
5097 """
5098 if isinstance(other, Decimal):
5099 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005100 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005101 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005102 if raiseit:
5103 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005104 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005105
Guido van Rossumd8faa362007-04-27 19:54:29 +00005106##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005107
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005108# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005109# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005110
5111DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005112 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005113 traps=[DivisionByZero, Overflow, InvalidOperation],
5114 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005115 Emax=999999999,
5116 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005117 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005118)
5119
5120# Pre-made alternate contexts offered by the specification
5121# Don't change these; the user should be able to select these
5122# contexts and be able to reproduce results from other implementations
5123# of the spec.
5124
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005125BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005126 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005127 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5128 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005129)
5130
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005131ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005132 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005133 traps=[],
5134 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005135)
5136
5137
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005138##### crud for parsing strings #############################################
5139import re
5140
5141# Regular expression used for parsing numeric strings. Additional
5142# comments:
5143#
5144# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5145# whitespace. But note that the specification disallows whitespace in
5146# a numeric string.
5147#
5148# 2. For finite numbers (not infinities and NaNs) the body of the
5149# number between the optional sign and the optional exponent must have
5150# at least one decimal digit, possibly after the decimal point. The
5151# lookahead expression '(?=\d|\.\d)' checks this.
5152#
5153# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5154# other meaning for \d than the numbers [0-9].
5155
5156import re
5157_parser = re.compile(r""" # A numeric string consists of:
5158# \s*
5159 (?P<sign>[-+])? # an optional sign, followed by either...
5160 (
5161 (?=\d|\.\d) # ...a number (with at least one digit)
5162 (?P<int>\d*) # consisting of a (possibly empty) integer part
5163 (\.(?P<frac>\d*))? # followed by an optional fractional part
5164 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5165 |
5166 Inf(inity)? # ...an infinity, or...
5167 |
5168 (?P<signal>s)? # ...an (optionally signaling)
5169 NaN # NaN
5170 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5171 )
5172# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00005173 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005174""", re.VERBOSE | re.IGNORECASE).match
5175
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005176_all_zeros = re.compile('0*$').match
5177_exact_half = re.compile('50*$').match
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005178del re
5179
5180
Guido van Rossumd8faa362007-04-27 19:54:29 +00005181##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005182
Guido van Rossumd8faa362007-04-27 19:54:29 +00005183# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005184Inf = Decimal('Inf')
5185negInf = Decimal('-Inf')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005186NaN = Decimal('NaN')
5187Dec_0 = Decimal(0)
5188Dec_p1 = Decimal(1)
5189Dec_n1 = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005190
Guido van Rossumd8faa362007-04-27 19:54:29 +00005191# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005192Infsign = (Inf, negInf)
5193
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005194
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005195
5196if __name__ == '__main__':
5197 import doctest, sys
5198 doctest.testmod(sys.modules[__name__])