blob: 873f7c069e094dbcc22113885c713386d33499e3 [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
Christian Heimes77c02eb2008-02-09 02:18:51 +0000721 def _compare_check_nans(self, other, context):
722 """Version of _check_nans used for the signaling comparisons
723 compare_signal, __le__, __lt__, __ge__, __gt__.
724
725 Signal InvalidOperation if either self or other is a (quiet
726 or signaling) NaN. Signaling NaNs take precedence over quiet
727 NaNs.
728
729 Return 0 if neither operand is a NaN.
730
731 """
732 if context is None:
733 context = getcontext()
734
735 if self._is_special or other._is_special:
736 if self.is_snan():
737 return context._raise_error(InvalidOperation,
738 'comparison involving sNaN',
739 self)
740 elif other.is_snan():
741 return context._raise_error(InvalidOperation,
742 'comparison involving sNaN',
743 other)
744 elif self.is_qnan():
745 return context._raise_error(InvalidOperation,
746 'comparison involving NaN',
747 self)
748 elif other.is_qnan():
749 return context._raise_error(InvalidOperation,
750 'comparison involving NaN',
751 other)
752 return 0
753
Jack Diederich4dafcc42006-11-28 19:15:13 +0000754 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000755 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000756
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000757 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000758 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000759 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000760
Christian Heimes77c02eb2008-02-09 02:18:51 +0000761 def _cmp(self, other):
762 """Compare the two non-NaN decimal instances self and other.
763
764 Returns -1 if self < other, 0 if self == other and 1
765 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000766
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000767 if self._is_special or other._is_special:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000768 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000769
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000770 # check for zeros; note that cmp(0, -0) should return 0
771 if not self:
772 if not other:
773 return 0
774 else:
775 return -((-1)**other._sign)
776 if not other:
777 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000778
Guido van Rossumd8faa362007-04-27 19:54:29 +0000779 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000780 if other._sign < self._sign:
781 return -1
782 if self._sign < other._sign:
783 return 1
784
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000785 self_adjusted = self.adjusted()
786 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000787 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000788 self_padded = self._int + '0'*(self._exp - other._exp)
789 other_padded = other._int + '0'*(other._exp - self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000790 return cmp(self_padded, other_padded) * (-1)**self._sign
791 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000792 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000793 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000794 return -((-1)**self._sign)
795
Christian Heimes77c02eb2008-02-09 02:18:51 +0000796 # Note: The Decimal standard doesn't cover rich comparisons for
797 # Decimals. In particular, the specification is silent on the
798 # subject of what should happen for a comparison involving a NaN.
799 # We take the following approach:
800 #
801 # == comparisons involving a NaN always return False
802 # != comparisons involving a NaN always return True
803 # <, >, <= and >= comparisons involving a (quiet or signaling)
804 # NaN signal InvalidOperation, and return False if the
Christian Heimes3feef612008-02-11 06:19:17 +0000805 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000806 #
807 # This behavior is designed to conform as closely as possible to
808 # that specified by IEEE 754.
809
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000810 def __eq__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000811 other = _convert_other(other)
812 if other is NotImplemented:
813 return other
814 if self.is_nan() or other.is_nan():
815 return False
816 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000817
818 def __ne__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000819 other = _convert_other(other)
820 if other is NotImplemented:
821 return other
822 if self.is_nan() or other.is_nan():
823 return True
824 return self._cmp(other) != 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000825
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000826
Christian Heimes77c02eb2008-02-09 02:18:51 +0000827 def __lt__(self, other, context=None):
828 other = _convert_other(other)
829 if other is NotImplemented:
830 return other
831 ans = self._compare_check_nans(other, context)
832 if ans:
833 return False
834 return self._cmp(other) < 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000835
Christian Heimes77c02eb2008-02-09 02:18:51 +0000836 def __le__(self, other, context=None):
837 other = _convert_other(other)
838 if other is NotImplemented:
839 return other
840 ans = self._compare_check_nans(other, context)
841 if ans:
842 return False
843 return self._cmp(other) <= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000844
Christian Heimes77c02eb2008-02-09 02:18:51 +0000845 def __gt__(self, other, context=None):
846 other = _convert_other(other)
847 if other is NotImplemented:
848 return other
849 ans = self._compare_check_nans(other, context)
850 if ans:
851 return False
852 return self._cmp(other) > 0
853
854 def __ge__(self, other, context=None):
855 other = _convert_other(other)
856 if other is NotImplemented:
857 return other
858 ans = self._compare_check_nans(other, context)
859 if ans:
860 return False
861 return self._cmp(other) >= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000862
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000863 def compare(self, other, context=None):
864 """Compares one to another.
865
866 -1 => a < b
867 0 => a = b
868 1 => a > b
869 NaN => one is NaN
870 Like __cmp__, but returns Decimal instances.
871 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000872 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000873
Guido van Rossumd8faa362007-04-27 19:54:29 +0000874 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000875 if (self._is_special or other and other._is_special):
876 ans = self._check_nans(other, context)
877 if ans:
878 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000879
Christian Heimes77c02eb2008-02-09 02:18:51 +0000880 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000881
882 def __hash__(self):
883 """x.__hash__() <==> hash(x)"""
884 # Decimal integers must hash the same as the ints
Christian Heimes2380ac72008-01-09 00:17:24 +0000885 #
886 # The hash of a nonspecial noninteger Decimal must depend only
887 # on the value of that Decimal, and not on its representation.
888 # For example: hash(Decimal("100E-1")) == hash(Decimal("10")).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000889 if self._is_special:
890 if self._isnan():
891 raise TypeError('Cannot hash a NaN value.')
892 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000893 if not self:
894 return 0
895 if self._isinteger():
896 op = _WorkRep(self.to_integral_value())
897 # to make computation feasible for Decimals with large
898 # exponent, we use the fact that hash(n) == hash(m) for
899 # any two nonzero integers n and m such that (i) n and m
900 # have the same sign, and (ii) n is congruent to m modulo
901 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
902 # hash((-1)**s*c*pow(10, e, 2**64-1).
903 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Christian Heimes2380ac72008-01-09 00:17:24 +0000904 # The value of a nonzero nonspecial Decimal instance is
905 # faithfully represented by the triple consisting of its sign,
906 # its adjusted exponent, and its coefficient with trailing
907 # zeros removed.
908 return hash((self._sign,
909 self._exp+len(self._int),
910 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000911
912 def as_tuple(self):
913 """Represents the number as a triple tuple.
914
915 To show the internals exactly as they are.
916 """
Christian Heimes25bb7832008-01-11 16:17:00 +0000917 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000918
919 def __repr__(self):
920 """Represents the number as an instance of Decimal."""
921 # Invariant: eval(repr(d)) == d
922 return 'Decimal("%s")' % str(self)
923
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000924 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000925 """Return string representation of the number in scientific notation.
926
927 Captures all of the information in the underlying representation.
928 """
929
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000930 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000931 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000932 if self._exp == 'F':
933 return sign + 'Infinity'
934 elif self._exp == 'n':
935 return sign + 'NaN' + self._int
936 else: # self._exp == 'N'
937 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000938
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000939 # number of digits of self._int to left of decimal point
940 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000941
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000942 # dotplace is number of digits of self._int to the left of the
943 # decimal point in the mantissa of the output string (that is,
944 # after adjusting the exponent)
945 if self._exp <= 0 and leftdigits > -6:
946 # no exponent required
947 dotplace = leftdigits
948 elif not eng:
949 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000950 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000951 elif self._int == '0':
952 # engineering notation, zero
953 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000954 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000955 # engineering notation, nonzero
956 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000957
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000958 if dotplace <= 0:
959 intpart = '0'
960 fracpart = '.' + '0'*(-dotplace) + self._int
961 elif dotplace >= len(self._int):
962 intpart = self._int+'0'*(dotplace-len(self._int))
963 fracpart = ''
964 else:
965 intpart = self._int[:dotplace]
966 fracpart = '.' + self._int[dotplace:]
967 if leftdigits == dotplace:
968 exp = ''
969 else:
970 if context is None:
971 context = getcontext()
972 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
973
974 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000975
976 def to_eng_string(self, context=None):
977 """Convert to engineering-type string.
978
979 Engineering notation has an exponent which is a multiple of 3, so there
980 are up to 3 digits left of the decimal place.
981
982 Same rules for when in exponential and when as a value as in __str__.
983 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000984 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000985
986 def __neg__(self, context=None):
987 """Returns a copy with the sign switched.
988
989 Rounds, if it has reason.
990 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000991 if self._is_special:
992 ans = self._check_nans(context=context)
993 if ans:
994 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000995
996 if not self:
997 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000998 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000999 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001000 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001001
1002 if context is None:
1003 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001004 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001005
1006 def __pos__(self, context=None):
1007 """Returns a copy, unless it is a sNaN.
1008
1009 Rounds the number (if more then precision digits)
1010 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001011 if self._is_special:
1012 ans = self._check_nans(context=context)
1013 if ans:
1014 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001015
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001016 if not self:
1017 # + (-0) = 0
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001018 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001019 else:
1020 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001021
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001022 if context is None:
1023 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001024 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001025
Christian Heimes2c181612007-12-17 20:04:13 +00001026 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001027 """Returns the absolute value of self.
1028
Christian Heimes2c181612007-12-17 20:04:13 +00001029 If the keyword argument 'round' is false, do not round. The
1030 expression self.__abs__(round=False) is equivalent to
1031 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001032 """
Christian Heimes2c181612007-12-17 20:04:13 +00001033 if not round:
1034 return self.copy_abs()
1035
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001036 if self._is_special:
1037 ans = self._check_nans(context=context)
1038 if ans:
1039 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001040
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001041 if self._sign:
1042 ans = self.__neg__(context=context)
1043 else:
1044 ans = self.__pos__(context=context)
1045
1046 return ans
1047
1048 def __add__(self, other, context=None):
1049 """Returns self + other.
1050
1051 -INF + INF (or the reverse) cause InvalidOperation errors.
1052 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001053 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001054 if other is NotImplemented:
1055 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001056
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001057 if context is None:
1058 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001059
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001060 if self._is_special or other._is_special:
1061 ans = self._check_nans(other, context)
1062 if ans:
1063 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001064
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001065 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001066 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001067 if self._sign != other._sign and other._isinfinity():
1068 return context._raise_error(InvalidOperation, '-INF + INF')
1069 return Decimal(self)
1070 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001071 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001072
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001073 exp = min(self._exp, other._exp)
1074 negativezero = 0
1075 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001076 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001077 negativezero = 1
1078
1079 if not self and not other:
1080 sign = min(self._sign, other._sign)
1081 if negativezero:
1082 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001083 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001084 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001085 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001086 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001087 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001088 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001089 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001090 return ans
1091 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001092 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001093 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001094 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001095 return ans
1096
1097 op1 = _WorkRep(self)
1098 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001099 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001100
1101 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001102 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001103 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001104 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001105 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001106 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001107 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001108 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001109 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001110 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001111 if op1.sign == 1:
1112 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001113 op1.sign, op2.sign = op2.sign, op1.sign
1114 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001115 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001116 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001117 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001118 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001119 op1.sign, op2.sign = (0, 0)
1120 else:
1121 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001122 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001123
Raymond Hettinger17931de2004-10-27 06:21:46 +00001124 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001125 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001126 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001127 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001128
1129 result.exp = op1.exp
1130 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001131 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001132 return ans
1133
1134 __radd__ = __add__
1135
1136 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001137 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001138 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001139 if other is NotImplemented:
1140 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001142 if self._is_special or other._is_special:
1143 ans = self._check_nans(other, context=context)
1144 if ans:
1145 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001146
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001147 # self - other is computed as self + other.copy_negate()
1148 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001149
1150 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001151 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001152 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001153 if other is NotImplemented:
1154 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001155
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001156 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001157
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001158 def __mul__(self, other, context=None):
1159 """Return self * other.
1160
1161 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1162 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001163 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001164 if other is NotImplemented:
1165 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001166
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001167 if context is None:
1168 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001169
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001170 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001171
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001172 if self._is_special or other._is_special:
1173 ans = self._check_nans(other, context)
1174 if ans:
1175 return ans
1176
1177 if self._isinfinity():
1178 if not other:
1179 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1180 return Infsign[resultsign]
1181
1182 if other._isinfinity():
1183 if not self:
1184 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1185 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001186
1187 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001188
1189 # Special case for multiplying by zero
1190 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001191 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001192 # Fixing in case the exponent is out of bounds
1193 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001194 return ans
1195
1196 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001197 if self._int == '1':
1198 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001199 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001200 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001201 if other._int == '1':
1202 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001203 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001204 return ans
1205
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001206 op1 = _WorkRep(self)
1207 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001208
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001209 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001210 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001211
1212 return ans
1213 __rmul__ = __mul__
1214
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001215 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001216 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001217 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001218 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001219 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001220
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001221 if context is None:
1222 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001223
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001224 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001225
1226 if self._is_special or other._is_special:
1227 ans = self._check_nans(other, context)
1228 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001229 return ans
1230
1231 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001232 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001233
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001234 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001235 return Infsign[sign]
1236
1237 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001238 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001239 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001240
1241 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001242 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001243 if not self:
1244 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001245 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001246
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001247 if not self:
1248 exp = self._exp - other._exp
1249 coeff = 0
1250 else:
1251 # OK, so neither = 0, INF or NaN
1252 shift = len(other._int) - len(self._int) + context.prec + 1
1253 exp = self._exp - other._exp - shift
1254 op1 = _WorkRep(self)
1255 op2 = _WorkRep(other)
1256 if shift >= 0:
1257 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1258 else:
1259 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1260 if remainder:
1261 # result is not exact; adjust to ensure correct rounding
1262 if coeff % 5 == 0:
1263 coeff += 1
1264 else:
1265 # result is exact; get as close to ideal exponent as possible
1266 ideal_exp = self._exp - other._exp
1267 while exp < ideal_exp and coeff % 10 == 0:
1268 coeff //= 10
1269 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001270
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001271 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001272 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001273
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001274 def _divide(self, other, context):
1275 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001276
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001277 Assumes that neither self nor other is a NaN, that self is not
1278 infinite and that other is nonzero.
1279 """
1280 sign = self._sign ^ other._sign
1281 if other._isinfinity():
1282 ideal_exp = self._exp
1283 else:
1284 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001285
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001286 expdiff = self.adjusted() - other.adjusted()
1287 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001288 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001289 self._rescale(ideal_exp, context.rounding))
1290 if expdiff <= context.prec:
1291 op1 = _WorkRep(self)
1292 op2 = _WorkRep(other)
1293 if op1.exp >= op2.exp:
1294 op1.int *= 10**(op1.exp - op2.exp)
1295 else:
1296 op2.int *= 10**(op2.exp - op1.exp)
1297 q, r = divmod(op1.int, op2.int)
1298 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001299 return (_dec_from_triple(sign, str(q), 0),
1300 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001301
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001302 # Here the quotient is too large to be representable
1303 ans = context._raise_error(DivisionImpossible,
1304 'quotient too large in //, % or divmod')
1305 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001306
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001307 def __rtruediv__(self, other, context=None):
1308 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001309 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001310 if other is NotImplemented:
1311 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001312 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001313
1314 def __divmod__(self, other, context=None):
1315 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001316 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001317 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001318 other = _convert_other(other)
1319 if other is NotImplemented:
1320 return other
1321
1322 if context is None:
1323 context = getcontext()
1324
1325 ans = self._check_nans(other, context)
1326 if ans:
1327 return (ans, ans)
1328
1329 sign = self._sign ^ other._sign
1330 if self._isinfinity():
1331 if other._isinfinity():
1332 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1333 return ans, ans
1334 else:
1335 return (Infsign[sign],
1336 context._raise_error(InvalidOperation, 'INF % x'))
1337
1338 if not other:
1339 if not self:
1340 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1341 return ans, ans
1342 else:
1343 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1344 context._raise_error(InvalidOperation, 'x % 0'))
1345
1346 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001347 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001348 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001349
1350 def __rdivmod__(self, other, context=None):
1351 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001352 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001353 if other is NotImplemented:
1354 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001355 return other.__divmod__(self, context=context)
1356
1357 def __mod__(self, other, context=None):
1358 """
1359 self % other
1360 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001361 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001362 if other is NotImplemented:
1363 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001364
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001365 if context is None:
1366 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001367
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001368 ans = self._check_nans(other, context)
1369 if ans:
1370 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001371
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001372 if self._isinfinity():
1373 return context._raise_error(InvalidOperation, 'INF % x')
1374 elif not other:
1375 if self:
1376 return context._raise_error(InvalidOperation, 'x % 0')
1377 else:
1378 return context._raise_error(DivisionUndefined, '0 % 0')
1379
1380 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001381 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001382 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001383
1384 def __rmod__(self, other, context=None):
1385 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001386 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001387 if other is NotImplemented:
1388 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001389 return other.__mod__(self, context=context)
1390
1391 def remainder_near(self, other, context=None):
1392 """
1393 Remainder nearest to 0- abs(remainder-near) <= other/2
1394 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001395 if context is None:
1396 context = getcontext()
1397
1398 other = _convert_other(other, raiseit=True)
1399
1400 ans = self._check_nans(other, context)
1401 if ans:
1402 return ans
1403
1404 # self == +/-infinity -> InvalidOperation
1405 if self._isinfinity():
1406 return context._raise_error(InvalidOperation,
1407 'remainder_near(infinity, x)')
1408
1409 # other == 0 -> either InvalidOperation or DivisionUndefined
1410 if not other:
1411 if self:
1412 return context._raise_error(InvalidOperation,
1413 'remainder_near(x, 0)')
1414 else:
1415 return context._raise_error(DivisionUndefined,
1416 'remainder_near(0, 0)')
1417
1418 # other = +/-infinity -> remainder = self
1419 if other._isinfinity():
1420 ans = Decimal(self)
1421 return ans._fix(context)
1422
1423 # self = 0 -> remainder = self, with ideal exponent
1424 ideal_exponent = min(self._exp, other._exp)
1425 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001426 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001427 return ans._fix(context)
1428
1429 # catch most cases of large or small quotient
1430 expdiff = self.adjusted() - other.adjusted()
1431 if expdiff >= context.prec + 1:
1432 # expdiff >= prec+1 => abs(self/other) > 10**prec
1433 return context._raise_error(DivisionImpossible)
1434 if expdiff <= -2:
1435 # expdiff <= -2 => abs(self/other) < 0.1
1436 ans = self._rescale(ideal_exponent, context.rounding)
1437 return ans._fix(context)
1438
1439 # adjust both arguments to have the same exponent, then divide
1440 op1 = _WorkRep(self)
1441 op2 = _WorkRep(other)
1442 if op1.exp >= op2.exp:
1443 op1.int *= 10**(op1.exp - op2.exp)
1444 else:
1445 op2.int *= 10**(op2.exp - op1.exp)
1446 q, r = divmod(op1.int, op2.int)
1447 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1448 # 10**ideal_exponent. Apply correction to ensure that
1449 # abs(remainder) <= abs(other)/2
1450 if 2*r + (q&1) > op2.int:
1451 r -= op2.int
1452 q += 1
1453
1454 if q >= 10**context.prec:
1455 return context._raise_error(DivisionImpossible)
1456
1457 # result has same sign as self unless r is negative
1458 sign = self._sign
1459 if r < 0:
1460 sign = 1-sign
1461 r = -r
1462
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001463 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001464 return ans._fix(context)
1465
1466 def __floordiv__(self, other, context=None):
1467 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001468 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001469 if other is NotImplemented:
1470 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001471
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001472 if context is None:
1473 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001474
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001475 ans = self._check_nans(other, context)
1476 if ans:
1477 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001478
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001479 if self._isinfinity():
1480 if other._isinfinity():
1481 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001482 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001483 return Infsign[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001484
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001485 if not other:
1486 if self:
1487 return context._raise_error(DivisionByZero, 'x // 0',
1488 self._sign ^ other._sign)
1489 else:
1490 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001491
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001492 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001493
1494 def __rfloordiv__(self, other, context=None):
1495 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001496 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001497 if other is NotImplemented:
1498 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001499 return other.__floordiv__(self, context=context)
1500
1501 def __float__(self):
1502 """Float representation."""
1503 return float(str(self))
1504
1505 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001506 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001507 if self._is_special:
1508 if self._isnan():
1509 context = getcontext()
1510 return context._raise_error(InvalidContext)
1511 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001512 raise OverflowError("Cannot convert infinity to int")
1513 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001514 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001515 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001516 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001517 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001518
Christian Heimes969fe572008-01-25 11:23:10 +00001519 __trunc__ = __int__
1520
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001521 def _fix_nan(self, context):
1522 """Decapitate the payload of a NaN to fit the context"""
1523 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001524
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001525 # maximum length of payload is precision if _clamp=0,
1526 # precision-1 if _clamp=1.
1527 max_payload_len = context.prec - context._clamp
1528 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001529 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1530 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001531 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001532
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001533 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001534 """Round if it is necessary to keep self within prec precision.
1535
1536 Rounds and fixes the exponent. Does not raise on a sNaN.
1537
1538 Arguments:
1539 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001540 context - context used.
1541 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001542
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001543 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001544 if self._isnan():
1545 # decapitate payload if necessary
1546 return self._fix_nan(context)
1547 else:
1548 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001549 return Decimal(self)
1550
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001551 # if self is zero then exponent should be between Etiny and
1552 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1553 Etiny = context.Etiny()
1554 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001555 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001556 exp_max = [context.Emax, Etop][context._clamp]
1557 new_exp = min(max(self._exp, Etiny), exp_max)
1558 if new_exp != self._exp:
1559 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001560 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001561 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001562 return Decimal(self)
1563
1564 # exp_min is the smallest allowable exponent of the result,
1565 # equal to max(self.adjusted()-context.prec+1, Etiny)
1566 exp_min = len(self._int) + self._exp - context.prec
1567 if exp_min > Etop:
1568 # overflow: exp_min > Etop iff self.adjusted() > Emax
1569 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001570 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001571 return context._raise_error(Overflow, 'above Emax', self._sign)
1572 self_is_subnormal = exp_min < Etiny
1573 if self_is_subnormal:
1574 context._raise_error(Subnormal)
1575 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001576
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001577 # round if self has too many digits
1578 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001579 context._raise_error(Rounded)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001580 digits = len(self._int) + self._exp - exp_min
1581 if digits < 0:
1582 self = _dec_from_triple(self._sign, '1', exp_min-1)
1583 digits = 0
1584 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1585 changed = this_function(digits)
1586 coeff = self._int[:digits] or '0'
1587 if changed == 1:
1588 coeff = str(int(coeff)+1)
1589 ans = _dec_from_triple(self._sign, coeff, exp_min)
1590
1591 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001592 context._raise_error(Inexact)
1593 if self_is_subnormal:
1594 context._raise_error(Underflow)
1595 if not ans:
1596 # raise Clamped on underflow to 0
1597 context._raise_error(Clamped)
1598 elif len(ans._int) == context.prec+1:
1599 # we get here only if rescaling rounds the
1600 # cofficient up to exactly 10**context.prec
1601 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001602 ans = _dec_from_triple(ans._sign,
1603 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001604 else:
1605 # Inexact and Rounded have already been raised
1606 ans = context._raise_error(Overflow, 'above Emax',
1607 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001608 return ans
1609
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001610 # fold down if _clamp == 1 and self has too few digits
1611 if context._clamp == 1 and self._exp > Etop:
1612 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001613 self_padded = self._int + '0'*(self._exp - Etop)
1614 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001615
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001616 # here self was representable to begin with; return unchanged
1617 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001618
1619 _pick_rounding_function = {}
1620
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001621 # for each of the rounding functions below:
1622 # self is a finite, nonzero Decimal
1623 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001624 #
1625 # each function returns either -1, 0, or 1, as follows:
1626 # 1 indicates that self should be rounded up (away from zero)
1627 # 0 indicates that self should be truncated, and that all the
1628 # digits to be truncated are zeros (so the value is unchanged)
1629 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001630
1631 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001632 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001633 if _all_zeros(self._int, prec):
1634 return 0
1635 else:
1636 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001637
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001638 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001639 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001640 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001641
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001642 def _round_half_up(self, prec):
1643 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001644 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001645 return 1
1646 elif _all_zeros(self._int, prec):
1647 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001648 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001649 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001650
1651 def _round_half_down(self, prec):
1652 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001653 if _exact_half(self._int, prec):
1654 return -1
1655 else:
1656 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001657
1658 def _round_half_even(self, prec):
1659 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001660 if _exact_half(self._int, prec) and \
1661 (prec == 0 or self._int[prec-1] in '02468'):
1662 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001663 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001664 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001665
1666 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001667 """Rounds up (not away from 0 if negative.)"""
1668 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001669 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001670 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001671 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001672
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001673 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001674 """Rounds down (not towards 0 if negative)"""
1675 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001676 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001677 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001678 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001679
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001680 def _round_05up(self, prec):
1681 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001682 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001683 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001684 else:
1685 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001686
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001687 def fma(self, other, third, context=None):
1688 """Fused multiply-add.
1689
1690 Returns self*other+third with no rounding of the intermediate
1691 product self*other.
1692
1693 self and other are multiplied together, with no rounding of
1694 the result. The third operand is then added to the result,
1695 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001696 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001697
1698 other = _convert_other(other, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001699
1700 # compute product; raise InvalidOperation if either operand is
1701 # a signaling NaN or if the product is zero times infinity.
1702 if self._is_special or other._is_special:
1703 if context is None:
1704 context = getcontext()
1705 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001706 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001707 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001708 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001709 if self._exp == 'n':
1710 product = self
1711 elif other._exp == 'n':
1712 product = other
1713 elif self._exp == 'F':
1714 if not other:
1715 return context._raise_error(InvalidOperation,
1716 'INF * 0 in fma')
1717 product = Infsign[self._sign ^ other._sign]
1718 elif other._exp == 'F':
1719 if not self:
1720 return context._raise_error(InvalidOperation,
1721 '0 * INF in fma')
1722 product = Infsign[self._sign ^ other._sign]
1723 else:
1724 product = _dec_from_triple(self._sign ^ other._sign,
1725 str(int(self._int) * int(other._int)),
1726 self._exp + other._exp)
1727
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001728 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001729 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001730
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001731 def _power_modulo(self, other, modulo, context=None):
1732 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001733
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001734 # if can't convert other and modulo to Decimal, raise
1735 # TypeError; there's no point returning NotImplemented (no
1736 # equivalent of __rpow__ for three argument pow)
1737 other = _convert_other(other, raiseit=True)
1738 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001739
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001740 if context is None:
1741 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001742
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001743 # deal with NaNs: if there are any sNaNs then first one wins,
1744 # (i.e. behaviour for NaNs is identical to that of fma)
1745 self_is_nan = self._isnan()
1746 other_is_nan = other._isnan()
1747 modulo_is_nan = modulo._isnan()
1748 if self_is_nan or other_is_nan or modulo_is_nan:
1749 if self_is_nan == 2:
1750 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001751 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001752 if other_is_nan == 2:
1753 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001754 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001755 if modulo_is_nan == 2:
1756 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001757 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001758 if self_is_nan:
1759 return self._fix_nan(context)
1760 if other_is_nan:
1761 return other._fix_nan(context)
1762 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001763
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001764 # check inputs: we apply same restrictions as Python's pow()
1765 if not (self._isinteger() and
1766 other._isinteger() and
1767 modulo._isinteger()):
1768 return context._raise_error(InvalidOperation,
1769 'pow() 3rd argument not allowed '
1770 'unless all arguments are integers')
1771 if other < 0:
1772 return context._raise_error(InvalidOperation,
1773 'pow() 2nd argument cannot be '
1774 'negative when 3rd argument specified')
1775 if not modulo:
1776 return context._raise_error(InvalidOperation,
1777 'pow() 3rd argument cannot be 0')
1778
1779 # additional restriction for decimal: the modulus must be less
1780 # than 10**prec in absolute value
1781 if modulo.adjusted() >= context.prec:
1782 return context._raise_error(InvalidOperation,
1783 'insufficient precision: pow() 3rd '
1784 'argument must not have more than '
1785 'precision digits')
1786
1787 # define 0**0 == NaN, for consistency with two-argument pow
1788 # (even though it hurts!)
1789 if not other and not self:
1790 return context._raise_error(InvalidOperation,
1791 'at least one of pow() 1st argument '
1792 'and 2nd argument must be nonzero ;'
1793 '0**0 is not defined')
1794
1795 # compute sign of result
1796 if other._iseven():
1797 sign = 0
1798 else:
1799 sign = self._sign
1800
1801 # convert modulo to a Python integer, and self and other to
1802 # Decimal integers (i.e. force their exponents to be >= 0)
1803 modulo = abs(int(modulo))
1804 base = _WorkRep(self.to_integral_value())
1805 exponent = _WorkRep(other.to_integral_value())
1806
1807 # compute result using integer pow()
1808 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1809 for i in range(exponent.exp):
1810 base = pow(base, 10, modulo)
1811 base = pow(base, exponent.int, modulo)
1812
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001813 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001814
1815 def _power_exact(self, other, p):
1816 """Attempt to compute self**other exactly.
1817
1818 Given Decimals self and other and an integer p, attempt to
1819 compute an exact result for the power self**other, with p
1820 digits of precision. Return None if self**other is not
1821 exactly representable in p digits.
1822
1823 Assumes that elimination of special cases has already been
1824 performed: self and other must both be nonspecial; self must
1825 be positive and not numerically equal to 1; other must be
1826 nonzero. For efficiency, other._exp should not be too large,
1827 so that 10**abs(other._exp) is a feasible calculation."""
1828
1829 # In the comments below, we write x for the value of self and
1830 # y for the value of other. Write x = xc*10**xe and y =
1831 # yc*10**ye.
1832
1833 # The main purpose of this method is to identify the *failure*
1834 # of x**y to be exactly representable with as little effort as
1835 # possible. So we look for cheap and easy tests that
1836 # eliminate the possibility of x**y being exact. Only if all
1837 # these tests are passed do we go on to actually compute x**y.
1838
1839 # Here's the main idea. First normalize both x and y. We
1840 # express y as a rational m/n, with m and n relatively prime
1841 # and n>0. Then for x**y to be exactly representable (at
1842 # *any* precision), xc must be the nth power of a positive
1843 # integer and xe must be divisible by n. If m is negative
1844 # then additionally xc must be a power of either 2 or 5, hence
1845 # a power of 2**n or 5**n.
1846 #
1847 # There's a limit to how small |y| can be: if y=m/n as above
1848 # then:
1849 #
1850 # (1) if xc != 1 then for the result to be representable we
1851 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1852 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1853 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1854 # representable.
1855 #
1856 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1857 # |y| < 1/|xe| then the result is not representable.
1858 #
1859 # Note that since x is not equal to 1, at least one of (1) and
1860 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1861 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1862 #
1863 # There's also a limit to how large y can be, at least if it's
1864 # positive: the normalized result will have coefficient xc**y,
1865 # so if it's representable then xc**y < 10**p, and y <
1866 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1867 # not exactly representable.
1868
1869 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1870 # so |y| < 1/xe and the result is not representable.
1871 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1872 # < 1/nbits(xc).
1873
1874 x = _WorkRep(self)
1875 xc, xe = x.int, x.exp
1876 while xc % 10 == 0:
1877 xc //= 10
1878 xe += 1
1879
1880 y = _WorkRep(other)
1881 yc, ye = y.int, y.exp
1882 while yc % 10 == 0:
1883 yc //= 10
1884 ye += 1
1885
1886 # case where xc == 1: result is 10**(xe*y), with xe*y
1887 # required to be an integer
1888 if xc == 1:
1889 if ye >= 0:
1890 exponent = xe*yc*10**ye
1891 else:
1892 exponent, remainder = divmod(xe*yc, 10**-ye)
1893 if remainder:
1894 return None
1895 if y.sign == 1:
1896 exponent = -exponent
1897 # if other is a nonnegative integer, use ideal exponent
1898 if other._isinteger() and other._sign == 0:
1899 ideal_exponent = self._exp*int(other)
1900 zeros = min(exponent-ideal_exponent, p-1)
1901 else:
1902 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001903 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001904
1905 # case where y is negative: xc must be either a power
1906 # of 2 or a power of 5.
1907 if y.sign == 1:
1908 last_digit = xc % 10
1909 if last_digit in (2,4,6,8):
1910 # quick test for power of 2
1911 if xc & -xc != xc:
1912 return None
1913 # now xc is a power of 2; e is its exponent
1914 e = _nbits(xc)-1
1915 # find e*y and xe*y; both must be integers
1916 if ye >= 0:
1917 y_as_int = yc*10**ye
1918 e = e*y_as_int
1919 xe = xe*y_as_int
1920 else:
1921 ten_pow = 10**-ye
1922 e, remainder = divmod(e*yc, ten_pow)
1923 if remainder:
1924 return None
1925 xe, remainder = divmod(xe*yc, ten_pow)
1926 if remainder:
1927 return None
1928
1929 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1930 return None
1931 xc = 5**e
1932
1933 elif last_digit == 5:
1934 # e >= log_5(xc) if xc is a power of 5; we have
1935 # equality all the way up to xc=5**2658
1936 e = _nbits(xc)*28//65
1937 xc, remainder = divmod(5**e, xc)
1938 if remainder:
1939 return None
1940 while xc % 5 == 0:
1941 xc //= 5
1942 e -= 1
1943 if ye >= 0:
1944 y_as_integer = yc*10**ye
1945 e = e*y_as_integer
1946 xe = xe*y_as_integer
1947 else:
1948 ten_pow = 10**-ye
1949 e, remainder = divmod(e*yc, ten_pow)
1950 if remainder:
1951 return None
1952 xe, remainder = divmod(xe*yc, ten_pow)
1953 if remainder:
1954 return None
1955 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1956 return None
1957 xc = 2**e
1958 else:
1959 return None
1960
1961 if xc >= 10**p:
1962 return None
1963 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001964 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001965
1966 # now y is positive; find m and n such that y = m/n
1967 if ye >= 0:
1968 m, n = yc*10**ye, 1
1969 else:
1970 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1971 return None
1972 xc_bits = _nbits(xc)
1973 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1974 return None
1975 m, n = yc, 10**(-ye)
1976 while m % 2 == n % 2 == 0:
1977 m //= 2
1978 n //= 2
1979 while m % 5 == n % 5 == 0:
1980 m //= 5
1981 n //= 5
1982
1983 # compute nth root of xc*10**xe
1984 if n > 1:
1985 # if 1 < xc < 2**n then xc isn't an nth power
1986 if xc != 1 and xc_bits <= n:
1987 return None
1988
1989 xe, rem = divmod(xe, n)
1990 if rem != 0:
1991 return None
1992
1993 # compute nth root of xc using Newton's method
1994 a = 1 << -(-_nbits(xc)//n) # initial estimate
1995 while True:
1996 q, r = divmod(xc, a**(n-1))
1997 if a <= q:
1998 break
1999 else:
2000 a = (a*(n-1) + q)//n
2001 if not (a == q and r == 0):
2002 return None
2003 xc = a
2004
2005 # now xc*10**xe is the nth root of the original xc*10**xe
2006 # compute mth power of xc*10**xe
2007
2008 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2009 # 10**p and the result is not representable.
2010 if xc > 1 and m > p*100//_log10_lb(xc):
2011 return None
2012 xc = xc**m
2013 xe *= m
2014 if xc > 10**p:
2015 return None
2016
2017 # by this point the result *is* exactly representable
2018 # adjust the exponent to get as close as possible to the ideal
2019 # exponent, if necessary
2020 str_xc = str(xc)
2021 if other._isinteger() and other._sign == 0:
2022 ideal_exponent = self._exp*int(other)
2023 zeros = min(xe-ideal_exponent, p-len(str_xc))
2024 else:
2025 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002026 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002027
2028 def __pow__(self, other, modulo=None, context=None):
2029 """Return self ** other [ % modulo].
2030
2031 With two arguments, compute self**other.
2032
2033 With three arguments, compute (self**other) % modulo. For the
2034 three argument form, the following restrictions on the
2035 arguments hold:
2036
2037 - all three arguments must be integral
2038 - other must be nonnegative
2039 - either self or other (or both) must be nonzero
2040 - modulo must be nonzero and must have at most p digits,
2041 where p is the context precision.
2042
2043 If any of these restrictions is violated the InvalidOperation
2044 flag is raised.
2045
2046 The result of pow(self, other, modulo) is identical to the
2047 result that would be obtained by computing (self**other) %
2048 modulo with unbounded precision, but is computed more
2049 efficiently. It is always exact.
2050 """
2051
2052 if modulo is not None:
2053 return self._power_modulo(other, modulo, context)
2054
2055 other = _convert_other(other)
2056 if other is NotImplemented:
2057 return other
2058
2059 if context is None:
2060 context = getcontext()
2061
2062 # either argument is a NaN => result is NaN
2063 ans = self._check_nans(other, context)
2064 if ans:
2065 return ans
2066
2067 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2068 if not other:
2069 if not self:
2070 return context._raise_error(InvalidOperation, '0 ** 0')
2071 else:
2072 return Dec_p1
2073
2074 # result has sign 1 iff self._sign is 1 and other is an odd integer
2075 result_sign = 0
2076 if self._sign == 1:
2077 if other._isinteger():
2078 if not other._iseven():
2079 result_sign = 1
2080 else:
2081 # -ve**noninteger = NaN
2082 # (-0)**noninteger = 0**noninteger
2083 if self:
2084 return context._raise_error(InvalidOperation,
2085 'x ** y with x negative and y not an integer')
2086 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002087 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002088
2089 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2090 if not self:
2091 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002092 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002093 else:
2094 return Infsign[result_sign]
2095
2096 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002097 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002098 if other._sign == 0:
2099 return Infsign[result_sign]
2100 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002101 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002102
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002103 # 1**other = 1, but the choice of exponent and the flags
2104 # depend on the exponent of self, and on whether other is a
2105 # positive integer, a negative integer, or neither
2106 if self == Dec_p1:
2107 if other._isinteger():
2108 # exp = max(self._exp*max(int(other), 0),
2109 # 1-context.prec) but evaluating int(other) directly
2110 # is dangerous until we know other is small (other
2111 # could be 1e999999999)
2112 if other._sign == 1:
2113 multiplier = 0
2114 elif other > context.prec:
2115 multiplier = context.prec
2116 else:
2117 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002118
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002119 exp = self._exp * multiplier
2120 if exp < 1-context.prec:
2121 exp = 1-context.prec
2122 context._raise_error(Rounded)
2123 else:
2124 context._raise_error(Inexact)
2125 context._raise_error(Rounded)
2126 exp = 1-context.prec
2127
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002128 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002129
2130 # compute adjusted exponent of self
2131 self_adj = self.adjusted()
2132
2133 # self ** infinity is infinity if self > 1, 0 if self < 1
2134 # self ** -infinity is infinity if self < 1, 0 if self > 1
2135 if other._isinfinity():
2136 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002137 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002138 else:
2139 return Infsign[result_sign]
2140
2141 # from here on, the result always goes through the call
2142 # to _fix at the end of this function.
2143 ans = None
2144
2145 # crude test to catch cases of extreme overflow/underflow. If
2146 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2147 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2148 # self**other >= 10**(Emax+1), so overflow occurs. The test
2149 # for underflow is similar.
2150 bound = self._log10_exp_bound() + other.adjusted()
2151 if (self_adj >= 0) == (other._sign == 0):
2152 # self > 1 and other +ve, or self < 1 and other -ve
2153 # possibility of overflow
2154 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002155 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002156 else:
2157 # self > 1 and other -ve, or self < 1 and other +ve
2158 # possibility of underflow to 0
2159 Etiny = context.Etiny()
2160 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002161 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002162
2163 # try for an exact result with precision +1
2164 if ans is None:
2165 ans = self._power_exact(other, context.prec + 1)
2166 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002167 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002168
2169 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2170 if ans is None:
2171 p = context.prec
2172 x = _WorkRep(self)
2173 xc, xe = x.int, x.exp
2174 y = _WorkRep(other)
2175 yc, ye = y.int, y.exp
2176 if y.sign == 1:
2177 yc = -yc
2178
2179 # compute correctly rounded result: start with precision +3,
2180 # then increase precision until result is unambiguously roundable
2181 extra = 3
2182 while True:
2183 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2184 if coeff % (5*10**(len(str(coeff))-p-1)):
2185 break
2186 extra += 3
2187
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002188 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002189
2190 # the specification says that for non-integer other we need to
2191 # raise Inexact, even when the result is actually exact. In
2192 # the same way, we need to raise Underflow here if the result
2193 # is subnormal. (The call to _fix will take care of raising
2194 # Rounded and Subnormal, as usual.)
2195 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002196 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002197 # pad with zeros up to length context.prec+1 if necessary
2198 if len(ans._int) <= context.prec:
2199 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002200 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2201 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002202 if ans.adjusted() < context.Emin:
2203 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002204
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002205 # unlike exp, ln and log10, the power function respects the
2206 # rounding mode; no need to use ROUND_HALF_EVEN here
2207 ans = ans._fix(context)
2208 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002209
2210 def __rpow__(self, other, context=None):
2211 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002212 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002213 if other is NotImplemented:
2214 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002215 return other.__pow__(self, context=context)
2216
2217 def normalize(self, context=None):
2218 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002219
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002220 if context is None:
2221 context = getcontext()
2222
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002223 if self._is_special:
2224 ans = self._check_nans(context=context)
2225 if ans:
2226 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002227
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002228 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002229 if dup._isinfinity():
2230 return dup
2231
2232 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002233 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002234 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002235 end = len(dup._int)
2236 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002237 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002238 exp += 1
2239 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002240 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002241
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002242 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002243 """Quantize self so its exponent is the same as that of exp.
2244
2245 Similar to self._rescale(exp._exp) but with error checking.
2246 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002247 exp = _convert_other(exp, raiseit=True)
2248
2249 if context is None:
2250 context = getcontext()
2251 if rounding is None:
2252 rounding = context.rounding
2253
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002254 if self._is_special or exp._is_special:
2255 ans = self._check_nans(exp, context)
2256 if ans:
2257 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002258
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002259 if exp._isinfinity() or self._isinfinity():
2260 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002261 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002262 return context._raise_error(InvalidOperation,
2263 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002264
2265 # if we're not watching exponents, do a simple rescale
2266 if not watchexp:
2267 ans = self._rescale(exp._exp, rounding)
2268 # raise Inexact and Rounded where appropriate
2269 if ans._exp > self._exp:
2270 context._raise_error(Rounded)
2271 if ans != self:
2272 context._raise_error(Inexact)
2273 return ans
2274
2275 # exp._exp should be between Etiny and Emax
2276 if not (context.Etiny() <= exp._exp <= context.Emax):
2277 return context._raise_error(InvalidOperation,
2278 'target exponent out of bounds in quantize')
2279
2280 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002281 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002282 return ans._fix(context)
2283
2284 self_adjusted = self.adjusted()
2285 if self_adjusted > context.Emax:
2286 return context._raise_error(InvalidOperation,
2287 'exponent of quantize result too large for current context')
2288 if self_adjusted - exp._exp + 1 > context.prec:
2289 return context._raise_error(InvalidOperation,
2290 'quantize result has too many digits for current context')
2291
2292 ans = self._rescale(exp._exp, rounding)
2293 if ans.adjusted() > context.Emax:
2294 return context._raise_error(InvalidOperation,
2295 'exponent of quantize result too large for current context')
2296 if len(ans._int) > context.prec:
2297 return context._raise_error(InvalidOperation,
2298 'quantize result has too many digits for current context')
2299
2300 # raise appropriate flags
2301 if ans._exp > self._exp:
2302 context._raise_error(Rounded)
2303 if ans != self:
2304 context._raise_error(Inexact)
2305 if ans and ans.adjusted() < context.Emin:
2306 context._raise_error(Subnormal)
2307
2308 # call to fix takes care of any necessary folddown
2309 ans = ans._fix(context)
2310 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002311
2312 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002313 """Return True if self and other have the same exponent; otherwise
2314 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002315
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002316 If either operand is a special value, the following rules are used:
2317 * return True if both operands are infinities
2318 * return True if both operands are NaNs
2319 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002320 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002321 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002322 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002323 return (self.is_nan() and other.is_nan() or
2324 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002325 return self._exp == other._exp
2326
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002327 def _rescale(self, exp, rounding):
2328 """Rescale self so that the exponent is exp, either by padding with zeros
2329 or by truncating digits, using the given rounding mode.
2330
2331 Specials are returned without change. This operation is
2332 quiet: it raises no flags, and uses no information from the
2333 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002334
2335 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002336 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002337 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002338 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002339 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002340 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002341 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002342
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002343 if self._exp >= exp:
2344 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002345 return _dec_from_triple(self._sign,
2346 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002347
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002348 # too many digits; round and lose data. If self.adjusted() <
2349 # exp-1, replace self by 10**(exp-1) before rounding
2350 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002351 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002352 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002353 digits = 0
2354 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002355 changed = this_function(digits)
2356 coeff = self._int[:digits] or '0'
2357 if changed == 1:
2358 coeff = str(int(coeff)+1)
2359 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002360
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002361 def to_integral_exact(self, rounding=None, context=None):
2362 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002363
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002364 If no rounding mode is specified, take the rounding mode from
2365 the context. This method raises the Rounded and Inexact flags
2366 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002367
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002368 See also: to_integral_value, which does exactly the same as
2369 this method except that it doesn't raise Inexact or Rounded.
2370 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002371 if self._is_special:
2372 ans = self._check_nans(context=context)
2373 if ans:
2374 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002375 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002376 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002377 return Decimal(self)
2378 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002379 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002380 if context is None:
2381 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002382 if rounding is None:
2383 rounding = context.rounding
2384 context._raise_error(Rounded)
2385 ans = self._rescale(0, rounding)
2386 if ans != self:
2387 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002388 return ans
2389
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002390 def to_integral_value(self, rounding=None, context=None):
2391 """Rounds to the nearest integer, without raising inexact, rounded."""
2392 if context is None:
2393 context = getcontext()
2394 if rounding is None:
2395 rounding = context.rounding
2396 if self._is_special:
2397 ans = self._check_nans(context=context)
2398 if ans:
2399 return ans
2400 return Decimal(self)
2401 if self._exp >= 0:
2402 return Decimal(self)
2403 else:
2404 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002405
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002406 # the method name changed, but we provide also the old one, for compatibility
2407 to_integral = to_integral_value
2408
2409 def sqrt(self, context=None):
2410 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002411 if self._is_special:
2412 ans = self._check_nans(context=context)
2413 if ans:
2414 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002415
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002416 if self._isinfinity() and self._sign == 0:
2417 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002418
2419 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002420 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002421 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002422 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002423
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002424 if context is None:
2425 context = getcontext()
2426
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002427 if self._sign == 1:
2428 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2429
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002430 # At this point self represents a positive number. Let p be
2431 # the desired precision and express self in the form c*100**e
2432 # with c a positive real number and e an integer, c and e
2433 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2434 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2435 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2436 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2437 # the closest integer to sqrt(c) with the even integer chosen
2438 # in the case of a tie.
2439 #
2440 # To ensure correct rounding in all cases, we use the
2441 # following trick: we compute the square root to an extra
2442 # place (precision p+1 instead of precision p), rounding down.
2443 # Then, if the result is inexact and its last digit is 0 or 5,
2444 # we increase the last digit to 1 or 6 respectively; if it's
2445 # exact we leave the last digit alone. Now the final round to
2446 # p places (or fewer in the case of underflow) will round
2447 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002448
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002449 # use an extra digit of precision
2450 prec = context.prec+1
2451
2452 # write argument in the form c*100**e where e = self._exp//2
2453 # is the 'ideal' exponent, to be used if the square root is
2454 # exactly representable. l is the number of 'digits' of c in
2455 # base 100, so that 100**(l-1) <= c < 100**l.
2456 op = _WorkRep(self)
2457 e = op.exp >> 1
2458 if op.exp & 1:
2459 c = op.int * 10
2460 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002461 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002462 c = op.int
2463 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002464
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002465 # rescale so that c has exactly prec base 100 'digits'
2466 shift = prec-l
2467 if shift >= 0:
2468 c *= 100**shift
2469 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002470 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002471 c, remainder = divmod(c, 100**-shift)
2472 exact = not remainder
2473 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002474
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002475 # find n = floor(sqrt(c)) using Newton's method
2476 n = 10**prec
2477 while True:
2478 q = c//n
2479 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002480 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002481 else:
2482 n = n + q >> 1
2483 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002484
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002485 if exact:
2486 # result is exact; rescale to use ideal exponent e
2487 if shift >= 0:
2488 # assert n % 10**shift == 0
2489 n //= 10**shift
2490 else:
2491 n *= 10**-shift
2492 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002493 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002494 # result is not exact; fix last digit as described above
2495 if n % 5 == 0:
2496 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002497
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002498 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002499
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002500 # round, and fit to current context
2501 context = context._shallow_copy()
2502 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002503 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002504 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002505
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002506 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002507
2508 def max(self, other, context=None):
2509 """Returns the larger value.
2510
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002511 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002512 NaN (and signals if one is sNaN). Also rounds.
2513 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002514 other = _convert_other(other, raiseit=True)
2515
2516 if context is None:
2517 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002518
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002519 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002520 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002521 # number is always returned
2522 sn = self._isnan()
2523 on = other._isnan()
2524 if sn or on:
2525 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002526 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002527 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002528 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002529 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002530
Christian Heimes77c02eb2008-02-09 02:18:51 +00002531 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002532 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002533 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002534 # then an ordering is applied:
2535 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002536 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002537 # positive sign and min returns the operand with the negative sign
2538 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002539 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002540 # the result. This is exactly the ordering used in compare_total.
2541 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002542
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002543 if c == -1:
2544 ans = other
2545 else:
2546 ans = self
2547
Christian Heimes2c181612007-12-17 20:04:13 +00002548 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002549
2550 def min(self, other, context=None):
2551 """Returns the smaller value.
2552
Guido van Rossumd8faa362007-04-27 19:54:29 +00002553 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002554 NaN (and signals if one is sNaN). Also rounds.
2555 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002556 other = _convert_other(other, raiseit=True)
2557
2558 if context is None:
2559 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002560
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002561 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002562 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002563 # number is always returned
2564 sn = self._isnan()
2565 on = other._isnan()
2566 if sn or on:
2567 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002568 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002569 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002570 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002571 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002572
Christian Heimes77c02eb2008-02-09 02:18:51 +00002573 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002574 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002575 c = self.compare_total(other)
2576
2577 if c == -1:
2578 ans = self
2579 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002580 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002581
Christian Heimes2c181612007-12-17 20:04:13 +00002582 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002583
2584 def _isinteger(self):
2585 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002586 if self._is_special:
2587 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002588 if self._exp >= 0:
2589 return True
2590 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002591 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002592
2593 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002594 """Returns True if self is even. Assumes self is an integer."""
2595 if not self or self._exp > 0:
2596 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002597 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002598
2599 def adjusted(self):
2600 """Return the adjusted exponent of self"""
2601 try:
2602 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002603 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002604 except TypeError:
2605 return 0
2606
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002607 def canonical(self, context=None):
2608 """Returns the same Decimal object.
2609
2610 As we do not have different encodings for the same number, the
2611 received object already is in its canonical form.
2612 """
2613 return self
2614
2615 def compare_signal(self, other, context=None):
2616 """Compares self to the other operand numerically.
2617
2618 It's pretty much like compare(), but all NaNs signal, with signaling
2619 NaNs taking precedence over quiet NaNs.
2620 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002621 other = _convert_other(other, raiseit = True)
2622 ans = self._compare_check_nans(other, context)
2623 if ans:
2624 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002625 return self.compare(other, context=context)
2626
2627 def compare_total(self, other):
2628 """Compares self to other using the abstract representations.
2629
2630 This is not like the standard compare, which use their numerical
2631 value. Note that a total ordering is defined for all possible abstract
2632 representations.
2633 """
2634 # if one is negative and the other is positive, it's easy
2635 if self._sign and not other._sign:
2636 return Dec_n1
2637 if not self._sign and other._sign:
2638 return Dec_p1
2639 sign = self._sign
2640
2641 # let's handle both NaN types
2642 self_nan = self._isnan()
2643 other_nan = other._isnan()
2644 if self_nan or other_nan:
2645 if self_nan == other_nan:
2646 if self._int < other._int:
2647 if sign:
2648 return Dec_p1
2649 else:
2650 return Dec_n1
2651 if self._int > other._int:
2652 if sign:
2653 return Dec_n1
2654 else:
2655 return Dec_p1
2656 return Dec_0
2657
2658 if sign:
2659 if self_nan == 1:
2660 return Dec_n1
2661 if other_nan == 1:
2662 return Dec_p1
2663 if self_nan == 2:
2664 return Dec_n1
2665 if other_nan == 2:
2666 return Dec_p1
2667 else:
2668 if self_nan == 1:
2669 return Dec_p1
2670 if other_nan == 1:
2671 return Dec_n1
2672 if self_nan == 2:
2673 return Dec_p1
2674 if other_nan == 2:
2675 return Dec_n1
2676
2677 if self < other:
2678 return Dec_n1
2679 if self > other:
2680 return Dec_p1
2681
2682 if self._exp < other._exp:
2683 if sign:
2684 return Dec_p1
2685 else:
2686 return Dec_n1
2687 if self._exp > other._exp:
2688 if sign:
2689 return Dec_n1
2690 else:
2691 return Dec_p1
2692 return Dec_0
2693
2694
2695 def compare_total_mag(self, other):
2696 """Compares self to other using abstract repr., ignoring sign.
2697
2698 Like compare_total, but with operand's sign ignored and assumed to be 0.
2699 """
2700 s = self.copy_abs()
2701 o = other.copy_abs()
2702 return s.compare_total(o)
2703
2704 def copy_abs(self):
2705 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002706 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002707
2708 def copy_negate(self):
2709 """Returns a copy with the sign inverted."""
2710 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002711 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002712 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002713 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002714
2715 def copy_sign(self, other):
2716 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002717 return _dec_from_triple(other._sign, self._int,
2718 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002719
2720 def exp(self, context=None):
2721 """Returns e ** self."""
2722
2723 if context is None:
2724 context = getcontext()
2725
2726 # exp(NaN) = NaN
2727 ans = self._check_nans(context=context)
2728 if ans:
2729 return ans
2730
2731 # exp(-Infinity) = 0
2732 if self._isinfinity() == -1:
2733 return Dec_0
2734
2735 # exp(0) = 1
2736 if not self:
2737 return Dec_p1
2738
2739 # exp(Infinity) = Infinity
2740 if self._isinfinity() == 1:
2741 return Decimal(self)
2742
2743 # the result is now guaranteed to be inexact (the true
2744 # mathematical result is transcendental). There's no need to
2745 # raise Rounded and Inexact here---they'll always be raised as
2746 # a result of the call to _fix.
2747 p = context.prec
2748 adj = self.adjusted()
2749
2750 # we only need to do any computation for quite a small range
2751 # of adjusted exponents---for example, -29 <= adj <= 10 for
2752 # the default context. For smaller exponent the result is
2753 # indistinguishable from 1 at the given precision, while for
2754 # larger exponent the result either overflows or underflows.
2755 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2756 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002757 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002758 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2759 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002760 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002761 elif self._sign == 0 and adj < -p:
2762 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002763 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002764 elif self._sign == 1 and adj < -p-1:
2765 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002766 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002767 # general case
2768 else:
2769 op = _WorkRep(self)
2770 c, e = op.int, op.exp
2771 if op.sign == 1:
2772 c = -c
2773
2774 # compute correctly rounded result: increase precision by
2775 # 3 digits at a time until we get an unambiguously
2776 # roundable result
2777 extra = 3
2778 while True:
2779 coeff, exp = _dexp(c, e, p+extra)
2780 if coeff % (5*10**(len(str(coeff))-p-1)):
2781 break
2782 extra += 3
2783
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002784 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002785
2786 # at this stage, ans should round correctly with *any*
2787 # rounding mode, not just with ROUND_HALF_EVEN
2788 context = context._shallow_copy()
2789 rounding = context._set_rounding(ROUND_HALF_EVEN)
2790 ans = ans._fix(context)
2791 context.rounding = rounding
2792
2793 return ans
2794
2795 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002796 """Return True if self is canonical; otherwise return False.
2797
2798 Currently, the encoding of a Decimal instance is always
2799 canonical, so this method returns True for any Decimal.
2800 """
2801 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002802
2803 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002804 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002805
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002806 A Decimal instance is considered finite if it is neither
2807 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002808 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002809 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002810
2811 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002812 """Return True if self is infinite; otherwise return False."""
2813 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002814
2815 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002816 """Return True if self is a qNaN or sNaN; otherwise return False."""
2817 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002818
2819 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002820 """Return True if self is a normal number; otherwise return False."""
2821 if self._is_special or not self:
2822 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002823 if context is None:
2824 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002825 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002826
2827 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002828 """Return True if self is a quiet NaN; otherwise return False."""
2829 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002830
2831 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002832 """Return True if self is negative; otherwise return False."""
2833 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002834
2835 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002836 """Return True if self is a signaling NaN; otherwise return False."""
2837 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002838
2839 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002840 """Return True if self is subnormal; otherwise return False."""
2841 if self._is_special or not self:
2842 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002843 if context is None:
2844 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002845 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002846
2847 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002848 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002849 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002850
2851 def _ln_exp_bound(self):
2852 """Compute a lower bound for the adjusted exponent of self.ln().
2853 In other words, compute r such that self.ln() >= 10**r. Assumes
2854 that self is finite and positive and that self != 1.
2855 """
2856
2857 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2858 adj = self._exp + len(self._int) - 1
2859 if adj >= 1:
2860 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2861 return len(str(adj*23//10)) - 1
2862 if adj <= -2:
2863 # argument <= 0.1
2864 return len(str((-1-adj)*23//10)) - 1
2865 op = _WorkRep(self)
2866 c, e = op.int, op.exp
2867 if adj == 0:
2868 # 1 < self < 10
2869 num = str(c-10**-e)
2870 den = str(c)
2871 return len(num) - len(den) - (num < den)
2872 # adj == -1, 0.1 <= self < 1
2873 return e + len(str(10**-e - c)) - 1
2874
2875
2876 def ln(self, context=None):
2877 """Returns the natural (base e) logarithm of self."""
2878
2879 if context is None:
2880 context = getcontext()
2881
2882 # ln(NaN) = NaN
2883 ans = self._check_nans(context=context)
2884 if ans:
2885 return ans
2886
2887 # ln(0.0) == -Infinity
2888 if not self:
2889 return negInf
2890
2891 # ln(Infinity) = Infinity
2892 if self._isinfinity() == 1:
2893 return Inf
2894
2895 # ln(1.0) == 0.0
2896 if self == Dec_p1:
2897 return Dec_0
2898
2899 # ln(negative) raises InvalidOperation
2900 if self._sign == 1:
2901 return context._raise_error(InvalidOperation,
2902 'ln of a negative value')
2903
2904 # result is irrational, so necessarily inexact
2905 op = _WorkRep(self)
2906 c, e = op.int, op.exp
2907 p = context.prec
2908
2909 # correctly rounded result: repeatedly increase precision by 3
2910 # until we get an unambiguously roundable result
2911 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2912 while True:
2913 coeff = _dlog(c, e, places)
2914 # assert len(str(abs(coeff)))-p >= 1
2915 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2916 break
2917 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002918 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002919
2920 context = context._shallow_copy()
2921 rounding = context._set_rounding(ROUND_HALF_EVEN)
2922 ans = ans._fix(context)
2923 context.rounding = rounding
2924 return ans
2925
2926 def _log10_exp_bound(self):
2927 """Compute a lower bound for the adjusted exponent of self.log10().
2928 In other words, find r such that self.log10() >= 10**r.
2929 Assumes that self is finite and positive and that self != 1.
2930 """
2931
2932 # For x >= 10 or x < 0.1 we only need a bound on the integer
2933 # part of log10(self), and this comes directly from the
2934 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2935 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2936 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2937
2938 adj = self._exp + len(self._int) - 1
2939 if adj >= 1:
2940 # self >= 10
2941 return len(str(adj))-1
2942 if adj <= -2:
2943 # self < 0.1
2944 return len(str(-1-adj))-1
2945 op = _WorkRep(self)
2946 c, e = op.int, op.exp
2947 if adj == 0:
2948 # 1 < self < 10
2949 num = str(c-10**-e)
2950 den = str(231*c)
2951 return len(num) - len(den) - (num < den) + 2
2952 # adj == -1, 0.1 <= self < 1
2953 num = str(10**-e-c)
2954 return len(num) + e - (num < "231") - 1
2955
2956 def log10(self, context=None):
2957 """Returns the base 10 logarithm of self."""
2958
2959 if context is None:
2960 context = getcontext()
2961
2962 # log10(NaN) = NaN
2963 ans = self._check_nans(context=context)
2964 if ans:
2965 return ans
2966
2967 # log10(0.0) == -Infinity
2968 if not self:
2969 return negInf
2970
2971 # log10(Infinity) = Infinity
2972 if self._isinfinity() == 1:
2973 return Inf
2974
2975 # log10(negative or -Infinity) raises InvalidOperation
2976 if self._sign == 1:
2977 return context._raise_error(InvalidOperation,
2978 'log10 of a negative value')
2979
2980 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002981 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002982 # answer may need rounding
2983 ans = Decimal(self._exp + len(self._int) - 1)
2984 else:
2985 # result is irrational, so necessarily inexact
2986 op = _WorkRep(self)
2987 c, e = op.int, op.exp
2988 p = context.prec
2989
2990 # correctly rounded result: repeatedly increase precision
2991 # until result is unambiguously roundable
2992 places = p-self._log10_exp_bound()+2
2993 while True:
2994 coeff = _dlog10(c, e, places)
2995 # assert len(str(abs(coeff)))-p >= 1
2996 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2997 break
2998 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002999 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003000
3001 context = context._shallow_copy()
3002 rounding = context._set_rounding(ROUND_HALF_EVEN)
3003 ans = ans._fix(context)
3004 context.rounding = rounding
3005 return ans
3006
3007 def logb(self, context=None):
3008 """ Returns the exponent of the magnitude of self's MSD.
3009
3010 The result is the integer which is the exponent of the magnitude
3011 of the most significant digit of self (as though it were truncated
3012 to a single digit while maintaining the value of that digit and
3013 without limiting the resulting exponent).
3014 """
3015 # logb(NaN) = NaN
3016 ans = self._check_nans(context=context)
3017 if ans:
3018 return ans
3019
3020 if context is None:
3021 context = getcontext()
3022
3023 # logb(+/-Inf) = +Inf
3024 if self._isinfinity():
3025 return Inf
3026
3027 # logb(0) = -Inf, DivisionByZero
3028 if not self:
3029 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3030
3031 # otherwise, simply return the adjusted exponent of self, as a
3032 # Decimal. Note that no attempt is made to fit the result
3033 # into the current context.
3034 return Decimal(self.adjusted())
3035
3036 def _islogical(self):
3037 """Return True if self is a logical operand.
3038
Christian Heimes679db4a2008-01-18 09:56:22 +00003039 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003040 an exponent of 0, and a coefficient whose digits must all be
3041 either 0 or 1.
3042 """
3043 if self._sign != 0 or self._exp != 0:
3044 return False
3045 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003046 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003047 return False
3048 return True
3049
3050 def _fill_logical(self, context, opa, opb):
3051 dif = context.prec - len(opa)
3052 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003053 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003054 elif dif < 0:
3055 opa = opa[-context.prec:]
3056 dif = context.prec - len(opb)
3057 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003058 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003059 elif dif < 0:
3060 opb = opb[-context.prec:]
3061 return opa, opb
3062
3063 def logical_and(self, other, context=None):
3064 """Applies an 'and' operation between self and other's digits."""
3065 if context is None:
3066 context = getcontext()
3067 if not self._islogical() or not other._islogical():
3068 return context._raise_error(InvalidOperation)
3069
3070 # fill to context.prec
3071 (opa, opb) = self._fill_logical(context, self._int, other._int)
3072
3073 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003074 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3075 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003076
3077 def logical_invert(self, context=None):
3078 """Invert all its digits."""
3079 if context is None:
3080 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003081 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3082 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003083
3084 def logical_or(self, other, context=None):
3085 """Applies an 'or' operation between self and other's digits."""
3086 if context is None:
3087 context = getcontext()
3088 if not self._islogical() or not other._islogical():
3089 return context._raise_error(InvalidOperation)
3090
3091 # fill to context.prec
3092 (opa, opb) = self._fill_logical(context, self._int, other._int)
3093
3094 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003095 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3096 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003097
3098 def logical_xor(self, other, context=None):
3099 """Applies an 'xor' operation between self and other's digits."""
3100 if context is None:
3101 context = getcontext()
3102 if not self._islogical() or not other._islogical():
3103 return context._raise_error(InvalidOperation)
3104
3105 # fill to context.prec
3106 (opa, opb) = self._fill_logical(context, self._int, other._int)
3107
3108 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003109 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3110 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003111
3112 def max_mag(self, other, context=None):
3113 """Compares the values numerically with their sign ignored."""
3114 other = _convert_other(other, raiseit=True)
3115
3116 if context is None:
3117 context = getcontext()
3118
3119 if self._is_special or other._is_special:
3120 # If one operand is a quiet NaN and the other is number, then the
3121 # number is always returned
3122 sn = self._isnan()
3123 on = other._isnan()
3124 if sn or on:
3125 if on == 1 and sn != 2:
3126 return self._fix_nan(context)
3127 if sn == 1 and on != 2:
3128 return other._fix_nan(context)
3129 return self._check_nans(other, context)
3130
Christian Heimes77c02eb2008-02-09 02:18:51 +00003131 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003132 if c == 0:
3133 c = self.compare_total(other)
3134
3135 if c == -1:
3136 ans = other
3137 else:
3138 ans = self
3139
Christian Heimes2c181612007-12-17 20:04:13 +00003140 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003141
3142 def min_mag(self, other, context=None):
3143 """Compares the values numerically with their sign ignored."""
3144 other = _convert_other(other, raiseit=True)
3145
3146 if context is None:
3147 context = getcontext()
3148
3149 if self._is_special or other._is_special:
3150 # If one operand is a quiet NaN and the other is number, then the
3151 # number is always returned
3152 sn = self._isnan()
3153 on = other._isnan()
3154 if sn or on:
3155 if on == 1 and sn != 2:
3156 return self._fix_nan(context)
3157 if sn == 1 and on != 2:
3158 return other._fix_nan(context)
3159 return self._check_nans(other, context)
3160
Christian Heimes77c02eb2008-02-09 02:18:51 +00003161 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003162 if c == 0:
3163 c = self.compare_total(other)
3164
3165 if c == -1:
3166 ans = self
3167 else:
3168 ans = other
3169
Christian Heimes2c181612007-12-17 20:04:13 +00003170 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003171
3172 def next_minus(self, context=None):
3173 """Returns the largest representable number smaller than itself."""
3174 if context is None:
3175 context = getcontext()
3176
3177 ans = self._check_nans(context=context)
3178 if ans:
3179 return ans
3180
3181 if self._isinfinity() == -1:
3182 return negInf
3183 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003184 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003185
3186 context = context.copy()
3187 context._set_rounding(ROUND_FLOOR)
3188 context._ignore_all_flags()
3189 new_self = self._fix(context)
3190 if new_self != self:
3191 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003192 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3193 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003194
3195 def next_plus(self, context=None):
3196 """Returns the smallest representable number larger than itself."""
3197 if context is None:
3198 context = getcontext()
3199
3200 ans = self._check_nans(context=context)
3201 if ans:
3202 return ans
3203
3204 if self._isinfinity() == 1:
3205 return Inf
3206 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003207 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003208
3209 context = context.copy()
3210 context._set_rounding(ROUND_CEILING)
3211 context._ignore_all_flags()
3212 new_self = self._fix(context)
3213 if new_self != self:
3214 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003215 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3216 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003217
3218 def next_toward(self, other, context=None):
3219 """Returns the number closest to self, in the direction towards other.
3220
3221 The result is the closest representable number to self
3222 (excluding self) that is in the direction towards other,
3223 unless both have the same value. If the two operands are
3224 numerically equal, then the result is a copy of self with the
3225 sign set to be the same as the sign of other.
3226 """
3227 other = _convert_other(other, raiseit=True)
3228
3229 if context is None:
3230 context = getcontext()
3231
3232 ans = self._check_nans(other, context)
3233 if ans:
3234 return ans
3235
Christian Heimes77c02eb2008-02-09 02:18:51 +00003236 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003237 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003238 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003239
3240 if comparison == -1:
3241 ans = self.next_plus(context)
3242 else: # comparison == 1
3243 ans = self.next_minus(context)
3244
3245 # decide which flags to raise using value of ans
3246 if ans._isinfinity():
3247 context._raise_error(Overflow,
3248 'Infinite result from next_toward',
3249 ans._sign)
3250 context._raise_error(Rounded)
3251 context._raise_error(Inexact)
3252 elif ans.adjusted() < context.Emin:
3253 context._raise_error(Underflow)
3254 context._raise_error(Subnormal)
3255 context._raise_error(Rounded)
3256 context._raise_error(Inexact)
3257 # if precision == 1 then we don't raise Clamped for a
3258 # result 0E-Etiny.
3259 if not ans:
3260 context._raise_error(Clamped)
3261
3262 return ans
3263
3264 def number_class(self, context=None):
3265 """Returns an indication of the class of self.
3266
3267 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003268 sNaN
3269 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003270 -Infinity
3271 -Normal
3272 -Subnormal
3273 -Zero
3274 +Zero
3275 +Subnormal
3276 +Normal
3277 +Infinity
3278 """
3279 if self.is_snan():
3280 return "sNaN"
3281 if self.is_qnan():
3282 return "NaN"
3283 inf = self._isinfinity()
3284 if inf == 1:
3285 return "+Infinity"
3286 if inf == -1:
3287 return "-Infinity"
3288 if self.is_zero():
3289 if self._sign:
3290 return "-Zero"
3291 else:
3292 return "+Zero"
3293 if context is None:
3294 context = getcontext()
3295 if self.is_subnormal(context=context):
3296 if self._sign:
3297 return "-Subnormal"
3298 else:
3299 return "+Subnormal"
3300 # just a normal, regular, boring number, :)
3301 if self._sign:
3302 return "-Normal"
3303 else:
3304 return "+Normal"
3305
3306 def radix(self):
3307 """Just returns 10, as this is Decimal, :)"""
3308 return Decimal(10)
3309
3310 def rotate(self, other, context=None):
3311 """Returns a rotated 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 rotdig = self._int
3330 topad = context.prec - len(rotdig)
3331 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003332 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003333
3334 # let's rotate!
3335 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003336 return _dec_from_triple(self._sign,
3337 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003338
3339 def scaleb (self, other, context=None):
3340 """Returns self operand after adding the second value to its exp."""
3341 if context is None:
3342 context = getcontext()
3343
3344 ans = self._check_nans(other, context)
3345 if ans:
3346 return ans
3347
3348 if other._exp != 0:
3349 return context._raise_error(InvalidOperation)
3350 liminf = -2 * (context.Emax + context.prec)
3351 limsup = 2 * (context.Emax + context.prec)
3352 if not (liminf <= int(other) <= limsup):
3353 return context._raise_error(InvalidOperation)
3354
3355 if self._isinfinity():
3356 return Decimal(self)
3357
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003358 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003359 d = d._fix(context)
3360 return d
3361
3362 def shift(self, other, context=None):
3363 """Returns a shifted copy of self, value-of-other times."""
3364 if context is None:
3365 context = getcontext()
3366
3367 ans = self._check_nans(other, context)
3368 if ans:
3369 return ans
3370
3371 if other._exp != 0:
3372 return context._raise_error(InvalidOperation)
3373 if not (-context.prec <= int(other) <= context.prec):
3374 return context._raise_error(InvalidOperation)
3375
3376 if self._isinfinity():
3377 return Decimal(self)
3378
3379 # get values, pad if necessary
3380 torot = int(other)
3381 if not torot:
3382 return Decimal(self)
3383 rotdig = self._int
3384 topad = context.prec - len(rotdig)
3385 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003386 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003387
3388 # let's shift!
3389 if torot < 0:
3390 rotated = rotdig[:torot]
3391 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003392 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003393 rotated = rotated[-context.prec:]
3394
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003395 return _dec_from_triple(self._sign,
3396 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003397
Guido van Rossumd8faa362007-04-27 19:54:29 +00003398 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003399 def __reduce__(self):
3400 return (self.__class__, (str(self),))
3401
3402 def __copy__(self):
3403 if type(self) == Decimal:
3404 return self # I'm immutable; therefore I am my own clone
3405 return self.__class__(str(self))
3406
3407 def __deepcopy__(self, memo):
3408 if type(self) == Decimal:
3409 return self # My components are also immutable
3410 return self.__class__(str(self))
3411
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003412def _dec_from_triple(sign, coefficient, exponent, special=False):
3413 """Create a decimal instance directly, without any validation,
3414 normalization (e.g. removal of leading zeros) or argument
3415 conversion.
3416
3417 This function is for *internal use only*.
3418 """
3419
3420 self = object.__new__(Decimal)
3421 self._sign = sign
3422 self._int = coefficient
3423 self._exp = exponent
3424 self._is_special = special
3425
3426 return self
3427
Guido van Rossumd8faa362007-04-27 19:54:29 +00003428##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003429
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003430
3431# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003432rounding_functions = [name for name in Decimal.__dict__.keys()
3433 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003434for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003435 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003436 globalname = name[1:].upper()
3437 val = globals()[globalname]
3438 Decimal._pick_rounding_function[val] = name
3439
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003440del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003441
Thomas Wouters89f507f2006-12-13 04:49:30 +00003442class _ContextManager(object):
3443 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003444
Thomas Wouters89f507f2006-12-13 04:49:30 +00003445 Sets a copy of the supplied context in __enter__() and restores
3446 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003447 """
3448 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003449 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003450 def __enter__(self):
3451 self.saved_context = getcontext()
3452 setcontext(self.new_context)
3453 return self.new_context
3454 def __exit__(self, t, v, tb):
3455 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003456
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003457class Context(object):
3458 """Contains the context for a Decimal instance.
3459
3460 Contains:
3461 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003462 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003463 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003464 raised when it is caused. Otherwise, a value is
3465 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003466 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003467 (Whether or not the trap_enabler is set)
3468 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003469 Emin - Minimum exponent
3470 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003471 capitals - If 1, 1*10^1 is printed as 1E+1.
3472 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003473 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003474 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003475
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003476 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003477 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003478 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003479 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003480 _ignored_flags=None):
3481 if flags is None:
3482 flags = []
3483 if _ignored_flags is None:
3484 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003485 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003486 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003487 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003488 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003489 for name, val in locals().items():
3490 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003491 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003492 else:
3493 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003494 del self.self
3495
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003496 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003497 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003498 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003499 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3500 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3501 % vars(self))
3502 names = [f.__name__ for f, v in self.flags.items() if v]
3503 s.append('flags=[' + ', '.join(names) + ']')
3504 names = [t.__name__ for t, v in self.traps.items() if v]
3505 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003506 return ', '.join(s) + ')'
3507
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003508 def clear_flags(self):
3509 """Reset all flags to zero"""
3510 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003511 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003512
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003513 def _shallow_copy(self):
3514 """Returns a shallow copy from self."""
Christian Heimes2c181612007-12-17 20:04:13 +00003515 nc = Context(self.prec, self.rounding, self.traps,
3516 self.flags, self.Emin, self.Emax,
3517 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003518 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003519
3520 def copy(self):
3521 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003522 nc = Context(self.prec, self.rounding, self.traps.copy(),
Christian Heimes2c181612007-12-17 20:04:13 +00003523 self.flags.copy(), self.Emin, self.Emax,
3524 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003525 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003526 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003527
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003528 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003529 """Handles an error
3530
3531 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003532 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003533 trap_enabler is set, it reaises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00003534 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003535 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003536 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003537 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003538 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003539 return error().handle(self, *args)
3540
Raymond Hettinger86173da2008-02-01 20:38:12 +00003541 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003542 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003543 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003544 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003545
3546 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003547 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003548 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003549
3550 def _ignore_all_flags(self):
3551 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003552 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003553
3554 def _ignore_flags(self, *flags):
3555 """Ignore the flags, if they are raised"""
3556 # Do not mutate-- This way, copies of a context leave the original
3557 # alone.
3558 self._ignored_flags = (self._ignored_flags + list(flags))
3559 return list(flags)
3560
3561 def _regard_flags(self, *flags):
3562 """Stop ignoring the flags, if they are raised"""
3563 if flags and isinstance(flags[0], (tuple,list)):
3564 flags = flags[0]
3565 for flag in flags:
3566 self._ignored_flags.remove(flag)
3567
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003568 def __hash__(self):
3569 """A Context cannot be hashed."""
3570 # We inherit object.__hash__, so we must deny this explicitly
Guido van Rossumd8faa362007-04-27 19:54:29 +00003571 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003572
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003573 def Etiny(self):
3574 """Returns Etiny (= Emin - prec + 1)"""
3575 return int(self.Emin - self.prec + 1)
3576
3577 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003578 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003579 return int(self.Emax - self.prec + 1)
3580
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003581 def _set_rounding(self, type):
3582 """Sets the rounding type.
3583
3584 Sets the rounding type, and returns the current (previous)
3585 rounding type. Often used like:
3586
3587 context = context.copy()
3588 # so you don't change the calling context
3589 # if an error occurs in the middle.
3590 rounding = context._set_rounding(ROUND_UP)
3591 val = self.__sub__(other, context=context)
3592 context._set_rounding(rounding)
3593
3594 This will make it round up for that operation.
3595 """
3596 rounding = self.rounding
3597 self.rounding= type
3598 return rounding
3599
Raymond Hettingerfed52962004-07-14 15:41:57 +00003600 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00003601 """Creates a new Decimal instance but using self as context.
3602
3603 This method implements the to-number operation of the
3604 IBM Decimal specification."""
3605
3606 if isinstance(num, str) and num != num.strip():
3607 return self._raise_error(ConversionSyntax,
3608 "no trailing or leading whitespace is "
3609 "permitted.")
3610
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003611 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003612 if d._isnan() and len(d._int) > self.prec - self._clamp:
3613 return self._raise_error(ConversionSyntax,
3614 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003615 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003616
Guido van Rossumd8faa362007-04-27 19:54:29 +00003617 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003618 def abs(self, a):
3619 """Returns the absolute value of the operand.
3620
3621 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003622 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003623 the plus operation on the operand.
3624
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003625 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003626 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003627 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003628 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003629 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003630 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003631 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003632 Decimal("101.5")
3633 """
3634 return a.__abs__(context=self)
3635
3636 def add(self, a, b):
3637 """Return the sum of the two operands.
3638
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003639 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003640 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003641 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003642 Decimal("1.02E+4")
3643 """
3644 return a.__add__(b, context=self)
3645
3646 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003647 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003648
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003649 def canonical(self, a):
3650 """Returns the same Decimal object.
3651
3652 As we do not have different encodings for the same number, the
3653 received object already is in its canonical form.
3654
3655 >>> ExtendedContext.canonical(Decimal('2.50'))
3656 Decimal("2.50")
3657 """
3658 return a.canonical(context=self)
3659
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003660 def compare(self, a, b):
3661 """Compares values numerically.
3662
3663 If the signs of the operands differ, a value representing each operand
3664 ('-1' if the operand is less than zero, '0' if the operand is zero or
3665 negative zero, or '1' if the operand is greater than zero) is used in
3666 place of that operand for the comparison instead of the actual
3667 operand.
3668
3669 The comparison is then effected by subtracting the second operand from
3670 the first and then returning a value according to the result of the
3671 subtraction: '-1' if the result is less than zero, '0' if the result is
3672 zero or negative zero, or '1' if the result is greater than zero.
3673
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003674 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003675 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003676 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003677 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003678 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003679 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003680 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003681 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003682 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003683 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003684 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003685 Decimal("-1")
3686 """
3687 return a.compare(b, context=self)
3688
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003689 def compare_signal(self, a, b):
3690 """Compares the values of the two operands numerically.
3691
3692 It's pretty much like compare(), but all NaNs signal, with signaling
3693 NaNs taking precedence over quiet NaNs.
3694
3695 >>> c = ExtendedContext
3696 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3697 Decimal("-1")
3698 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3699 Decimal("0")
3700 >>> c.flags[InvalidOperation] = 0
3701 >>> print(c.flags[InvalidOperation])
3702 0
3703 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3704 Decimal("NaN")
3705 >>> print(c.flags[InvalidOperation])
3706 1
3707 >>> c.flags[InvalidOperation] = 0
3708 >>> print(c.flags[InvalidOperation])
3709 0
3710 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3711 Decimal("NaN")
3712 >>> print(c.flags[InvalidOperation])
3713 1
3714 """
3715 return a.compare_signal(b, context=self)
3716
3717 def compare_total(self, a, b):
3718 """Compares two operands using their abstract representation.
3719
3720 This is not like the standard compare, which use their numerical
3721 value. Note that a total ordering is defined for all possible abstract
3722 representations.
3723
3724 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3725 Decimal("-1")
3726 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3727 Decimal("-1")
3728 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3729 Decimal("-1")
3730 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3731 Decimal("0")
3732 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3733 Decimal("1")
3734 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3735 Decimal("-1")
3736 """
3737 return a.compare_total(b)
3738
3739 def compare_total_mag(self, a, b):
3740 """Compares two operands using their abstract representation ignoring sign.
3741
3742 Like compare_total, but with operand's sign ignored and assumed to be 0.
3743 """
3744 return a.compare_total_mag(b)
3745
3746 def copy_abs(self, a):
3747 """Returns a copy of the operand with the sign set to 0.
3748
3749 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3750 Decimal("2.1")
3751 >>> ExtendedContext.copy_abs(Decimal('-100'))
3752 Decimal("100")
3753 """
3754 return a.copy_abs()
3755
3756 def copy_decimal(self, a):
3757 """Returns a copy of the decimal objet.
3758
3759 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3760 Decimal("2.1")
3761 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3762 Decimal("-1.00")
3763 """
3764 return Decimal(a)
3765
3766 def copy_negate(self, a):
3767 """Returns a copy of the operand with the sign inverted.
3768
3769 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3770 Decimal("-101.5")
3771 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3772 Decimal("101.5")
3773 """
3774 return a.copy_negate()
3775
3776 def copy_sign(self, a, b):
3777 """Copies the second operand's sign to the first one.
3778
3779 In detail, it returns a copy of the first operand with the sign
3780 equal to the sign of the second operand.
3781
3782 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3783 Decimal("1.50")
3784 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3785 Decimal("1.50")
3786 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3787 Decimal("-1.50")
3788 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3789 Decimal("-1.50")
3790 """
3791 return a.copy_sign(b)
3792
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003793 def divide(self, a, b):
3794 """Decimal division in a specified context.
3795
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003796 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003797 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003798 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003799 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003800 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003801 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003802 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003803 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003804 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003805 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003806 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003807 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003808 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003809 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003810 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003811 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003812 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003813 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003814 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003815 Decimal("1.20E+6")
3816 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003817 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003818
3819 def divide_int(self, a, b):
3820 """Divides two numbers and returns the integer part of the result.
3821
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003822 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003823 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003824 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003825 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003826 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003827 Decimal("3")
3828 """
3829 return a.__floordiv__(b, context=self)
3830
3831 def divmod(self, a, b):
3832 return a.__divmod__(b, context=self)
3833
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003834 def exp(self, a):
3835 """Returns e ** a.
3836
3837 >>> c = ExtendedContext.copy()
3838 >>> c.Emin = -999
3839 >>> c.Emax = 999
3840 >>> c.exp(Decimal('-Infinity'))
3841 Decimal("0")
3842 >>> c.exp(Decimal('-1'))
3843 Decimal("0.367879441")
3844 >>> c.exp(Decimal('0'))
3845 Decimal("1")
3846 >>> c.exp(Decimal('1'))
3847 Decimal("2.71828183")
3848 >>> c.exp(Decimal('0.693147181'))
3849 Decimal("2.00000000")
3850 >>> c.exp(Decimal('+Infinity'))
3851 Decimal("Infinity")
3852 """
3853 return a.exp(context=self)
3854
3855 def fma(self, a, b, c):
3856 """Returns a multiplied by b, plus c.
3857
3858 The first two operands are multiplied together, using multiply,
3859 the third operand is then added to the result of that
3860 multiplication, using add, all with only one final rounding.
3861
3862 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3863 Decimal("22")
3864 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3865 Decimal("-8")
3866 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3867 Decimal("1.38435736E+12")
3868 """
3869 return a.fma(b, c, context=self)
3870
3871 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003872 """Return True if the operand is canonical; otherwise return False.
3873
3874 Currently, the encoding of a Decimal instance is always
3875 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003876
3877 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003878 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003879 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003880 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003881
3882 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003883 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003884
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003885 A Decimal instance is considered finite if it is neither
3886 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003887
3888 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003889 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003890 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003891 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003892 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003893 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003894 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003895 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003896 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003897 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003898 """
3899 return a.is_finite()
3900
3901 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003902 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003903
3904 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003905 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003906 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003907 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003908 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003909 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003910 """
3911 return a.is_infinite()
3912
3913 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003914 """Return True if the operand is a qNaN or sNaN;
3915 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003916
3917 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003918 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003919 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003920 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003921 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003922 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003923 """
3924 return a.is_nan()
3925
3926 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003927 """Return True if the operand is a normal number;
3928 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003929
3930 >>> c = ExtendedContext.copy()
3931 >>> c.Emin = -999
3932 >>> c.Emax = 999
3933 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003934 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003935 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003936 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003937 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003938 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003939 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003940 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003941 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003942 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003943 """
3944 return a.is_normal(context=self)
3945
3946 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003947 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003948
3949 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003950 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003951 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003952 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003953 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003954 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003955 """
3956 return a.is_qnan()
3957
3958 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003959 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003960
3961 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003962 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003963 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003964 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003965 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003966 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003967 """
3968 return a.is_signed()
3969
3970 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003971 """Return True if the operand is a signaling NaN;
3972 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003973
3974 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003975 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003976 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003977 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003978 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003979 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003980 """
3981 return a.is_snan()
3982
3983 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003984 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003985
3986 >>> c = ExtendedContext.copy()
3987 >>> c.Emin = -999
3988 >>> c.Emax = 999
3989 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003990 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003991 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003992 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003993 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003994 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003995 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003996 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003997 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003998 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003999 """
4000 return a.is_subnormal(context=self)
4001
4002 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004003 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004004
4005 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004006 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004007 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004008 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004009 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004010 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004011 """
4012 return a.is_zero()
4013
4014 def ln(self, a):
4015 """Returns the natural (base e) logarithm of the operand.
4016
4017 >>> c = ExtendedContext.copy()
4018 >>> c.Emin = -999
4019 >>> c.Emax = 999
4020 >>> c.ln(Decimal('0'))
4021 Decimal("-Infinity")
4022 >>> c.ln(Decimal('1.000'))
4023 Decimal("0")
4024 >>> c.ln(Decimal('2.71828183'))
4025 Decimal("1.00000000")
4026 >>> c.ln(Decimal('10'))
4027 Decimal("2.30258509")
4028 >>> c.ln(Decimal('+Infinity'))
4029 Decimal("Infinity")
4030 """
4031 return a.ln(context=self)
4032
4033 def log10(self, a):
4034 """Returns the base 10 logarithm of the operand.
4035
4036 >>> c = ExtendedContext.copy()
4037 >>> c.Emin = -999
4038 >>> c.Emax = 999
4039 >>> c.log10(Decimal('0'))
4040 Decimal("-Infinity")
4041 >>> c.log10(Decimal('0.001'))
4042 Decimal("-3")
4043 >>> c.log10(Decimal('1.000'))
4044 Decimal("0")
4045 >>> c.log10(Decimal('2'))
4046 Decimal("0.301029996")
4047 >>> c.log10(Decimal('10'))
4048 Decimal("1")
4049 >>> c.log10(Decimal('70'))
4050 Decimal("1.84509804")
4051 >>> c.log10(Decimal('+Infinity'))
4052 Decimal("Infinity")
4053 """
4054 return a.log10(context=self)
4055
4056 def logb(self, a):
4057 """ Returns the exponent of the magnitude of the operand's MSD.
4058
4059 The result is the integer which is the exponent of the magnitude
4060 of the most significant digit of the operand (as though the
4061 operand were truncated to a single digit while maintaining the
4062 value of that digit and without limiting the resulting exponent).
4063
4064 >>> ExtendedContext.logb(Decimal('250'))
4065 Decimal("2")
4066 >>> ExtendedContext.logb(Decimal('2.50'))
4067 Decimal("0")
4068 >>> ExtendedContext.logb(Decimal('0.03'))
4069 Decimal("-2")
4070 >>> ExtendedContext.logb(Decimal('0'))
4071 Decimal("-Infinity")
4072 """
4073 return a.logb(context=self)
4074
4075 def logical_and(self, a, b):
4076 """Applies the logical operation 'and' between each operand's digits.
4077
4078 The operands must be both logical numbers.
4079
4080 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4081 Decimal("0")
4082 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4083 Decimal("0")
4084 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4085 Decimal("0")
4086 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4087 Decimal("1")
4088 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4089 Decimal("1000")
4090 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4091 Decimal("10")
4092 """
4093 return a.logical_and(b, context=self)
4094
4095 def logical_invert(self, a):
4096 """Invert all the digits in the operand.
4097
4098 The operand must be a logical number.
4099
4100 >>> ExtendedContext.logical_invert(Decimal('0'))
4101 Decimal("111111111")
4102 >>> ExtendedContext.logical_invert(Decimal('1'))
4103 Decimal("111111110")
4104 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4105 Decimal("0")
4106 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4107 Decimal("10101010")
4108 """
4109 return a.logical_invert(context=self)
4110
4111 def logical_or(self, a, b):
4112 """Applies the logical operation 'or' between each operand's digits.
4113
4114 The operands must be both logical numbers.
4115
4116 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4117 Decimal("0")
4118 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4119 Decimal("1")
4120 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4121 Decimal("1")
4122 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4123 Decimal("1")
4124 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4125 Decimal("1110")
4126 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4127 Decimal("1110")
4128 """
4129 return a.logical_or(b, context=self)
4130
4131 def logical_xor(self, a, b):
4132 """Applies the logical operation 'xor' between each operand's digits.
4133
4134 The operands must be both logical numbers.
4135
4136 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4137 Decimal("0")
4138 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4139 Decimal("1")
4140 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4141 Decimal("1")
4142 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4143 Decimal("0")
4144 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4145 Decimal("110")
4146 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4147 Decimal("1101")
4148 """
4149 return a.logical_xor(b, context=self)
4150
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004151 def max(self, a,b):
4152 """max compares two values numerically and returns the maximum.
4153
4154 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004155 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004156 operation. If they are numerically equal then the left-hand operand
4157 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004158 infinity) of the two operands is chosen as the result.
4159
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004160 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004161 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004162 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004163 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004164 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004165 Decimal("1")
4166 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4167 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004168 """
4169 return a.max(b, context=self)
4170
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004171 def max_mag(self, a, b):
4172 """Compares the values numerically with their sign ignored."""
4173 return a.max_mag(b, context=self)
4174
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004175 def min(self, a,b):
4176 """min compares two values numerically and returns the minimum.
4177
4178 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004179 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004180 operation. If they are numerically equal then the left-hand operand
4181 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004182 infinity) of the two operands is chosen as the result.
4183
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004184 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004185 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004186 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004187 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004188 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004189 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004190 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4191 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004192 """
4193 return a.min(b, context=self)
4194
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004195 def min_mag(self, a, b):
4196 """Compares the values numerically with their sign ignored."""
4197 return a.min_mag(b, context=self)
4198
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004199 def minus(self, a):
4200 """Minus corresponds to unary prefix minus in Python.
4201
4202 The operation is evaluated using the same rules as subtract; the
4203 operation minus(a) is calculated as subtract('0', a) where the '0'
4204 has the same exponent as the operand.
4205
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004206 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004207 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004208 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004209 Decimal("1.3")
4210 """
4211 return a.__neg__(context=self)
4212
4213 def multiply(self, a, b):
4214 """multiply multiplies two operands.
4215
4216 If either operand is a special value then the general rules apply.
4217 Otherwise, the operands are multiplied together ('long multiplication'),
4218 resulting in a number which may be as long as the sum of the lengths
4219 of the two operands.
4220
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004221 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004222 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004223 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004224 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004225 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004226 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004227 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004228 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004229 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004230 Decimal("4.28135971E+11")
4231 """
4232 return a.__mul__(b, context=self)
4233
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004234 def next_minus(self, a):
4235 """Returns the largest representable number smaller than a.
4236
4237 >>> c = ExtendedContext.copy()
4238 >>> c.Emin = -999
4239 >>> c.Emax = 999
4240 >>> ExtendedContext.next_minus(Decimal('1'))
4241 Decimal("0.999999999")
4242 >>> c.next_minus(Decimal('1E-1007'))
4243 Decimal("0E-1007")
4244 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4245 Decimal("-1.00000004")
4246 >>> c.next_minus(Decimal('Infinity'))
4247 Decimal("9.99999999E+999")
4248 """
4249 return a.next_minus(context=self)
4250
4251 def next_plus(self, a):
4252 """Returns the smallest representable number larger than a.
4253
4254 >>> c = ExtendedContext.copy()
4255 >>> c.Emin = -999
4256 >>> c.Emax = 999
4257 >>> ExtendedContext.next_plus(Decimal('1'))
4258 Decimal("1.00000001")
4259 >>> c.next_plus(Decimal('-1E-1007'))
4260 Decimal("-0E-1007")
4261 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4262 Decimal("-1.00000002")
4263 >>> c.next_plus(Decimal('-Infinity'))
4264 Decimal("-9.99999999E+999")
4265 """
4266 return a.next_plus(context=self)
4267
4268 def next_toward(self, a, b):
4269 """Returns the number closest to a, in direction towards b.
4270
4271 The result is the closest representable number from the first
4272 operand (but not the first operand) that is in the direction
4273 towards the second operand, unless the operands have the same
4274 value.
4275
4276 >>> c = ExtendedContext.copy()
4277 >>> c.Emin = -999
4278 >>> c.Emax = 999
4279 >>> c.next_toward(Decimal('1'), Decimal('2'))
4280 Decimal("1.00000001")
4281 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4282 Decimal("-0E-1007")
4283 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4284 Decimal("-1.00000002")
4285 >>> c.next_toward(Decimal('1'), Decimal('0'))
4286 Decimal("0.999999999")
4287 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4288 Decimal("0E-1007")
4289 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4290 Decimal("-1.00000004")
4291 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4292 Decimal("-0.00")
4293 """
4294 return a.next_toward(b, context=self)
4295
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004296 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004297 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004298
4299 Essentially a plus operation with all trailing zeros removed from the
4300 result.
4301
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004302 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004303 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004304 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004305 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004306 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004307 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004308 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004309 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004310 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004311 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004312 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004313 Decimal("0")
4314 """
4315 return a.normalize(context=self)
4316
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004317 def number_class(self, a):
4318 """Returns an indication of the class of the operand.
4319
4320 The class is one of the following strings:
4321 -sNaN
4322 -NaN
4323 -Infinity
4324 -Normal
4325 -Subnormal
4326 -Zero
4327 +Zero
4328 +Subnormal
4329 +Normal
4330 +Infinity
4331
4332 >>> c = Context(ExtendedContext)
4333 >>> c.Emin = -999
4334 >>> c.Emax = 999
4335 >>> c.number_class(Decimal('Infinity'))
4336 '+Infinity'
4337 >>> c.number_class(Decimal('1E-10'))
4338 '+Normal'
4339 >>> c.number_class(Decimal('2.50'))
4340 '+Normal'
4341 >>> c.number_class(Decimal('0.1E-999'))
4342 '+Subnormal'
4343 >>> c.number_class(Decimal('0'))
4344 '+Zero'
4345 >>> c.number_class(Decimal('-0'))
4346 '-Zero'
4347 >>> c.number_class(Decimal('-0.1E-999'))
4348 '-Subnormal'
4349 >>> c.number_class(Decimal('-1E-10'))
4350 '-Normal'
4351 >>> c.number_class(Decimal('-2.50'))
4352 '-Normal'
4353 >>> c.number_class(Decimal('-Infinity'))
4354 '-Infinity'
4355 >>> c.number_class(Decimal('NaN'))
4356 'NaN'
4357 >>> c.number_class(Decimal('-NaN'))
4358 'NaN'
4359 >>> c.number_class(Decimal('sNaN'))
4360 'sNaN'
4361 """
4362 return a.number_class(context=self)
4363
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004364 def plus(self, a):
4365 """Plus corresponds to unary prefix plus in Python.
4366
4367 The operation is evaluated using the same rules as add; the
4368 operation plus(a) is calculated as add('0', a) where the '0'
4369 has the same exponent as the operand.
4370
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004371 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004372 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004373 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004374 Decimal("-1.3")
4375 """
4376 return a.__pos__(context=self)
4377
4378 def power(self, a, b, modulo=None):
4379 """Raises a to the power of b, to modulo if given.
4380
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004381 With two arguments, compute a**b. If a is negative then b
4382 must be integral. The result will be inexact unless b is
4383 integral and the result is finite and can be expressed exactly
4384 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004385
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004386 With three arguments, compute (a**b) % modulo. For the
4387 three argument form, the following restrictions on the
4388 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004389
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004390 - all three arguments must be integral
4391 - b must be nonnegative
4392 - at least one of a or b must be nonzero
4393 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004394
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004395 The result of pow(a, b, modulo) is identical to the result
4396 that would be obtained by computing (a**b) % modulo with
4397 unbounded precision, but is computed more efficiently. It is
4398 always exact.
4399
4400 >>> c = ExtendedContext.copy()
4401 >>> c.Emin = -999
4402 >>> c.Emax = 999
4403 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004404 Decimal("8")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004405 >>> c.power(Decimal('-2'), Decimal('3'))
4406 Decimal("-8")
4407 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004408 Decimal("0.125")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004409 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004410 Decimal("69.7575744")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004411 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4412 Decimal("2.00000000")
4413 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004414 Decimal("0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004415 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004416 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004417 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004418 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004419 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004420 Decimal("-0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004421 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004422 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004423 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004424 Decimal("-Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004425 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004426 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004427 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004428 Decimal("NaN")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004429
4430 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4431 Decimal("11")
4432 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4433 Decimal("-11")
4434 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4435 Decimal("1")
4436 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4437 Decimal("11")
4438 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4439 Decimal("11729830")
4440 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4441 Decimal("-0")
4442 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4443 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004444 """
4445 return a.__pow__(b, modulo, context=self)
4446
4447 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004448 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004449
4450 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004451 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004452 exponent is being increased), multiplied by a positive power of ten (if
4453 the exponent is being decreased), or is unchanged (if the exponent is
4454 already equal to that of the right-hand operand).
4455
4456 Unlike other operations, if the length of the coefficient after the
4457 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004458 operation condition is raised. This guarantees that, unless there is
4459 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004460 equal to that of the right-hand operand.
4461
4462 Also unlike other operations, quantize will never raise Underflow, even
4463 if the result is subnormal and inexact.
4464
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004465 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004466 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004467 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004468 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004469 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004470 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004471 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004472 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004473 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004474 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004475 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004476 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004477 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004478 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004479 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004480 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004481 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004482 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004483 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004484 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004485 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004486 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004487 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004488 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004489 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004490 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004491 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004492 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004493 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004494 Decimal("2E+2")
4495 """
4496 return a.quantize(b, context=self)
4497
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004498 def radix(self):
4499 """Just returns 10, as this is Decimal, :)
4500
4501 >>> ExtendedContext.radix()
4502 Decimal("10")
4503 """
4504 return Decimal(10)
4505
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004506 def remainder(self, a, b):
4507 """Returns the remainder from integer division.
4508
4509 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004510 calculating integer division as described for divide-integer, rounded
4511 to precision digits if necessary. The sign of the result, if
4512 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004513
4514 This operation will fail under the same conditions as integer division
4515 (that is, if integer division on the same two operands would fail, the
4516 remainder cannot be calculated).
4517
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004518 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004519 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004520 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004521 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004522 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004523 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004524 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004525 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004526 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004527 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004528 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004529 Decimal("1.0")
4530 """
4531 return a.__mod__(b, context=self)
4532
4533 def remainder_near(self, a, b):
4534 """Returns to be "a - b * n", where n is the integer nearest the exact
4535 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004536 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004537 sign of a.
4538
4539 This operation will fail under the same conditions as integer division
4540 (that is, if integer division on the same two operands would fail, the
4541 remainder cannot be calculated).
4542
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004543 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004544 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004545 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004546 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004547 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004548 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004549 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004550 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004551 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004552 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004553 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004554 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004555 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004556 Decimal("-0.3")
4557 """
4558 return a.remainder_near(b, context=self)
4559
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004560 def rotate(self, a, b):
4561 """Returns a rotated copy of a, b times.
4562
4563 The coefficient of the result is a rotated copy of the digits in
4564 the coefficient of the first operand. The number of places of
4565 rotation is taken from the absolute value of the second operand,
4566 with the rotation being to the left if the second operand is
4567 positive or to the right otherwise.
4568
4569 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4570 Decimal("400000003")
4571 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4572 Decimal("12")
4573 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4574 Decimal("891234567")
4575 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4576 Decimal("123456789")
4577 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4578 Decimal("345678912")
4579 """
4580 return a.rotate(b, context=self)
4581
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004582 def same_quantum(self, a, b):
4583 """Returns True if the two operands have the same exponent.
4584
4585 The result is never affected by either the sign or the coefficient of
4586 either operand.
4587
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004588 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004589 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004590 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004591 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004592 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004593 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004594 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004595 True
4596 """
4597 return a.same_quantum(b)
4598
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004599 def scaleb (self, a, b):
4600 """Returns the first operand after adding the second value its exp.
4601
4602 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4603 Decimal("0.0750")
4604 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4605 Decimal("7.50")
4606 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4607 Decimal("7.50E+3")
4608 """
4609 return a.scaleb (b, context=self)
4610
4611 def shift(self, a, b):
4612 """Returns a shifted copy of a, b times.
4613
4614 The coefficient of the result is a shifted copy of the digits
4615 in the coefficient of the first operand. The number of places
4616 to shift is taken from the absolute value of the second operand,
4617 with the shift being to the left if the second operand is
4618 positive or to the right otherwise. Digits shifted into the
4619 coefficient are zeros.
4620
4621 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4622 Decimal("400000000")
4623 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4624 Decimal("0")
4625 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4626 Decimal("1234567")
4627 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4628 Decimal("123456789")
4629 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4630 Decimal("345678900")
4631 """
4632 return a.shift(b, context=self)
4633
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004634 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004635 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004636
4637 If the result must be inexact, it is rounded using the round-half-even
4638 algorithm.
4639
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004640 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004641 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004642 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004643 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004644 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004645 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004646 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004647 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004648 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004649 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004650 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004651 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004652 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004653 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004654 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004655 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004656 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004657 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004658 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004659 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004660 """
4661 return a.sqrt(context=self)
4662
4663 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004664 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004665
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004666 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004667 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004668 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004669 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004670 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004671 Decimal("-0.77")
4672 """
4673 return a.__sub__(b, context=self)
4674
4675 def to_eng_string(self, a):
4676 """Converts a number to a string, using scientific notation.
4677
4678 The operation is not affected by the context.
4679 """
4680 return a.to_eng_string(context=self)
4681
4682 def to_sci_string(self, a):
4683 """Converts a number to a string, using scientific notation.
4684
4685 The operation is not affected by the context.
4686 """
4687 return a.__str__(context=self)
4688
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004689 def to_integral_exact(self, a):
4690 """Rounds to an integer.
4691
4692 When the operand has a negative exponent, the result is the same
4693 as using the quantize() operation using the given operand as the
4694 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4695 of the operand as the precision setting; Inexact and Rounded flags
4696 are allowed in this operation. The rounding mode is taken from the
4697 context.
4698
4699 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4700 Decimal("2")
4701 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4702 Decimal("100")
4703 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4704 Decimal("100")
4705 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4706 Decimal("102")
4707 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4708 Decimal("-102")
4709 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4710 Decimal("1.0E+6")
4711 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4712 Decimal("7.89E+77")
4713 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4714 Decimal("-Infinity")
4715 """
4716 return a.to_integral_exact(context=self)
4717
4718 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004719 """Rounds to an integer.
4720
4721 When the operand has a negative exponent, the result is the same
4722 as using the quantize() operation using the given operand as the
4723 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4724 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004725 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004726
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004727 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004728 Decimal("2")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004729 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004730 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004731 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004732 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004733 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004734 Decimal("102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004735 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004736 Decimal("-102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004737 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004738 Decimal("1.0E+6")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004739 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004740 Decimal("7.89E+77")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004741 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004742 Decimal("-Infinity")
4743 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004744 return a.to_integral_value(context=self)
4745
4746 # the method name changed, but we provide also the old one, for compatibility
4747 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004748
4749class _WorkRep(object):
4750 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004751 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004752 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004753 # exp: None, int, or string
4754
4755 def __init__(self, value=None):
4756 if value is None:
4757 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004758 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004759 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004760 elif isinstance(value, Decimal):
4761 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00004762 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004763 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004764 else:
4765 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004766 self.sign = value[0]
4767 self.int = value[1]
4768 self.exp = value[2]
4769
4770 def __repr__(self):
4771 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4772
4773 __str__ = __repr__
4774
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004775
4776
Christian Heimes2c181612007-12-17 20:04:13 +00004777def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004778 """Normalizes op1, op2 to have the same exp and length of coefficient.
4779
4780 Done during addition.
4781 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004782 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004783 tmp = op2
4784 other = op1
4785 else:
4786 tmp = op1
4787 other = op2
4788
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004789 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4790 # Then adding 10**exp to tmp has the same effect (after rounding)
4791 # as adding any positive quantity smaller than 10**exp; similarly
4792 # for subtraction. So if other is smaller than 10**exp we replace
4793 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00004794 tmp_len = len(str(tmp.int))
4795 other_len = len(str(other.int))
4796 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4797 if other_len + other.exp - 1 < exp:
4798 other.int = 1
4799 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004800
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004801 tmp.int *= 10 ** (tmp.exp - other.exp)
4802 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004803 return op1, op2
4804
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004805##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004806
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004807# This function from Tim Peters was taken from here:
4808# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4809# The correction being in the function definition is for speed, and
4810# the whole function is not resolved with math.log because of avoiding
4811# the use of floats.
4812def _nbits(n, correction = {
4813 '0': 4, '1': 3, '2': 2, '3': 2,
4814 '4': 1, '5': 1, '6': 1, '7': 1,
4815 '8': 0, '9': 0, 'a': 0, 'b': 0,
4816 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4817 """Number of bits in binary representation of the positive integer n,
4818 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004819 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004820 if n < 0:
4821 raise ValueError("The argument to _nbits should be nonnegative.")
4822 hex_n = "%x" % n
4823 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004824
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004825def _sqrt_nearest(n, a):
4826 """Closest integer to the square root of the positive integer n. a is
4827 an initial approximation to the square root. Any positive integer
4828 will do for a, but the closer a is to the square root of n the
4829 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004830
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004831 """
4832 if n <= 0 or a <= 0:
4833 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4834
4835 b=0
4836 while a != b:
4837 b, a = a, a--n//a>>1
4838 return a
4839
4840def _rshift_nearest(x, shift):
4841 """Given an integer x and a nonnegative integer shift, return closest
4842 integer to x / 2**shift; use round-to-even in case of a tie.
4843
4844 """
4845 b, q = 1 << shift, x >> shift
4846 return q + (2*(x & (b-1)) + (q&1) > b)
4847
4848def _div_nearest(a, b):
4849 """Closest integer to a/b, a and b positive integers; rounds to even
4850 in the case of a tie.
4851
4852 """
4853 q, r = divmod(a, b)
4854 return q + (2*r + (q&1) > b)
4855
4856def _ilog(x, M, L = 8):
4857 """Integer approximation to M*log(x/M), with absolute error boundable
4858 in terms only of x/M.
4859
4860 Given positive integers x and M, return an integer approximation to
4861 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4862 between the approximation and the exact result is at most 22. For
4863 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4864 both cases these are upper bounds on the error; it will usually be
4865 much smaller."""
4866
4867 # The basic algorithm is the following: let log1p be the function
4868 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4869 # the reduction
4870 #
4871 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4872 #
4873 # repeatedly until the argument to log1p is small (< 2**-L in
4874 # absolute value). For small y we can use the Taylor series
4875 # expansion
4876 #
4877 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4878 #
4879 # truncating at T such that y**T is small enough. The whole
4880 # computation is carried out in a form of fixed-point arithmetic,
4881 # with a real number z being represented by an integer
4882 # approximation to z*M. To avoid loss of precision, the y below
4883 # is actually an integer approximation to 2**R*y*M, where R is the
4884 # number of reductions performed so far.
4885
4886 y = x-M
4887 # argument reduction; R = number of reductions performed
4888 R = 0
4889 while (R <= L and abs(y) << L-R >= M or
4890 R > L and abs(y) >> R-L >= M):
4891 y = _div_nearest((M*y) << 1,
4892 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4893 R += 1
4894
4895 # Taylor series with T terms
4896 T = -int(-10*len(str(M))//(3*L))
4897 yshift = _rshift_nearest(y, R)
4898 w = _div_nearest(M, T)
4899 for k in range(T-1, 0, -1):
4900 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4901
4902 return _div_nearest(w*y, M)
4903
4904def _dlog10(c, e, p):
4905 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4906 approximation to 10**p * log10(c*10**e), with an absolute error of
4907 at most 1. Assumes that c*10**e is not exactly 1."""
4908
4909 # increase precision by 2; compensate for this by dividing
4910 # final result by 100
4911 p += 2
4912
4913 # write c*10**e as d*10**f with either:
4914 # f >= 0 and 1 <= d <= 10, or
4915 # f <= 0 and 0.1 <= d <= 1.
4916 # Thus for c*10**e close to 1, f = 0
4917 l = len(str(c))
4918 f = e+l - (e+l >= 1)
4919
4920 if p > 0:
4921 M = 10**p
4922 k = e+p-f
4923 if k >= 0:
4924 c *= 10**k
4925 else:
4926 c = _div_nearest(c, 10**-k)
4927
4928 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004929 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004930 log_d = _div_nearest(log_d*M, log_10)
4931 log_tenpower = f*M # exact
4932 else:
4933 log_d = 0 # error < 2.31
4934 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4935
4936 return _div_nearest(log_tenpower+log_d, 100)
4937
4938def _dlog(c, e, p):
4939 """Given integers c, e and p with c > 0, compute an integer
4940 approximation to 10**p * log(c*10**e), with an absolute error of
4941 at most 1. Assumes that c*10**e is not exactly 1."""
4942
4943 # Increase precision by 2. The precision increase is compensated
4944 # for at the end with a division by 100.
4945 p += 2
4946
4947 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4948 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4949 # as 10**p * log(d) + 10**p*f * log(10).
4950 l = len(str(c))
4951 f = e+l - (e+l >= 1)
4952
4953 # compute approximation to 10**p*log(d), with error < 27
4954 if p > 0:
4955 k = e+p-f
4956 if k >= 0:
4957 c *= 10**k
4958 else:
4959 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4960
4961 # _ilog magnifies existing error in c by a factor of at most 10
4962 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4963 else:
4964 # p <= 0: just approximate the whole thing by 0; error < 2.31
4965 log_d = 0
4966
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004967 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004968 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004969 extra = len(str(abs(f)))-1
4970 if p + extra >= 0:
4971 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4972 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4973 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004974 else:
4975 f_log_ten = 0
4976 else:
4977 f_log_ten = 0
4978
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004979 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004980 return _div_nearest(f_log_ten + log_d, 100)
4981
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004982class _Log10Memoize(object):
4983 """Class to compute, store, and allow retrieval of, digits of the
4984 constant log(10) = 2.302585.... This constant is needed by
4985 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4986 def __init__(self):
4987 self.digits = "23025850929940456840179914546843642076011014886"
4988
4989 def getdigits(self, p):
4990 """Given an integer p >= 0, return floor(10**p)*log(10).
4991
4992 For example, self.getdigits(3) returns 2302.
4993 """
4994 # digits are stored as a string, for quick conversion to
4995 # integer in the case that we've already computed enough
4996 # digits; the stored digits should always be correct
4997 # (truncated, not rounded to nearest).
4998 if p < 0:
4999 raise ValueError("p should be nonnegative")
5000
5001 if p >= len(self.digits):
5002 # compute p+3, p+6, p+9, ... digits; continue until at
5003 # least one of the extra digits is nonzero
5004 extra = 3
5005 while True:
5006 # compute p+extra digits, correct to within 1ulp
5007 M = 10**(p+extra+2)
5008 digits = str(_div_nearest(_ilog(10*M, M), 100))
5009 if digits[-extra:] != '0'*extra:
5010 break
5011 extra += 3
5012 # keep all reliable digits so far; remove trailing zeros
5013 # and next nonzero digit
5014 self.digits = digits.rstrip('0')[:-1]
5015 return int(self.digits[:p+1])
5016
5017_log10_digits = _Log10Memoize().getdigits
5018
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005019def _iexp(x, M, L=8):
5020 """Given integers x and M, M > 0, such that x/M is small in absolute
5021 value, compute an integer approximation to M*exp(x/M). For 0 <=
5022 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5023 is usually much smaller)."""
5024
5025 # Algorithm: to compute exp(z) for a real number z, first divide z
5026 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5027 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5028 # series
5029 #
5030 # expm1(x) = x + x**2/2! + x**3/3! + ...
5031 #
5032 # Now use the identity
5033 #
5034 # expm1(2x) = expm1(x)*(expm1(x)+2)
5035 #
5036 # R times to compute the sequence expm1(z/2**R),
5037 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5038
5039 # Find R such that x/2**R/M <= 2**-L
5040 R = _nbits((x<<L)//M)
5041
5042 # Taylor series. (2**L)**T > M
5043 T = -int(-10*len(str(M))//(3*L))
5044 y = _div_nearest(x, T)
5045 Mshift = M<<R
5046 for i in range(T-1, 0, -1):
5047 y = _div_nearest(x*(Mshift + y), Mshift * i)
5048
5049 # Expansion
5050 for k in range(R-1, -1, -1):
5051 Mshift = M<<(k+2)
5052 y = _div_nearest(y*(y+Mshift), Mshift)
5053
5054 return M+y
5055
5056def _dexp(c, e, p):
5057 """Compute an approximation to exp(c*10**e), with p decimal places of
5058 precision.
5059
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005060 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005061
5062 10**(p-1) <= d <= 10**p, and
5063 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5064
5065 In other words, d*10**f is an approximation to exp(c*10**e) with p
5066 digits of precision, and with an error in d of at most 1. This is
5067 almost, but not quite, the same as the error being < 1ulp: when d
5068 = 10**(p-1) the error could be up to 10 ulp."""
5069
5070 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5071 p += 2
5072
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005073 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005074 extra = max(0, e + len(str(c)) - 1)
5075 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005076
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005077 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005078 # rounding down
5079 shift = e+q
5080 if shift >= 0:
5081 cshift = c*10**shift
5082 else:
5083 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005084 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005085
5086 # reduce remainder back to original precision
5087 rem = _div_nearest(rem, 10**extra)
5088
5089 # error in result of _iexp < 120; error after division < 0.62
5090 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5091
5092def _dpower(xc, xe, yc, ye, p):
5093 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5094 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5095
5096 10**(p-1) <= c <= 10**p, and
5097 (c-1)*10**e < x**y < (c+1)*10**e
5098
5099 in other words, c*10**e is an approximation to x**y with p digits
5100 of precision, and with an error in c of at most 1. (This is
5101 almost, but not quite, the same as the error being < 1ulp: when c
5102 == 10**(p-1) we can only guarantee error < 10ulp.)
5103
5104 We assume that: x is positive and not equal to 1, and y is nonzero.
5105 """
5106
5107 # Find b such that 10**(b-1) <= |y| <= 10**b
5108 b = len(str(abs(yc))) + ye
5109
5110 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5111 lxc = _dlog(xc, xe, p+b+1)
5112
5113 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5114 shift = ye-b
5115 if shift >= 0:
5116 pc = lxc*yc*10**shift
5117 else:
5118 pc = _div_nearest(lxc*yc, 10**-shift)
5119
5120 if pc == 0:
5121 # we prefer a result that isn't exactly 1; this makes it
5122 # easier to compute a correctly rounded result in __pow__
5123 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5124 coeff, exp = 10**(p-1)+1, 1-p
5125 else:
5126 coeff, exp = 10**p-1, -p
5127 else:
5128 coeff, exp = _dexp(pc, -(p+1), p+1)
5129 coeff = _div_nearest(coeff, 10)
5130 exp += 1
5131
5132 return coeff, exp
5133
5134def _log10_lb(c, correction = {
5135 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5136 '6': 23, '7': 16, '8': 10, '9': 5}):
5137 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5138 if c <= 0:
5139 raise ValueError("The argument to _log10_lb should be nonnegative.")
5140 str_c = str(c)
5141 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005142
Guido van Rossumd8faa362007-04-27 19:54:29 +00005143##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005144
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005145def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005146 """Convert other to Decimal.
5147
5148 Verifies that it's ok to use in an implicit construction.
5149 """
5150 if isinstance(other, Decimal):
5151 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005152 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005153 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005154 if raiseit:
5155 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005156 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005157
Guido van Rossumd8faa362007-04-27 19:54:29 +00005158##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005159
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005160# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005161# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005162
5163DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005164 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005165 traps=[DivisionByZero, Overflow, InvalidOperation],
5166 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005167 Emax=999999999,
5168 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005169 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005170)
5171
5172# Pre-made alternate contexts offered by the specification
5173# Don't change these; the user should be able to select these
5174# contexts and be able to reproduce results from other implementations
5175# of the spec.
5176
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005177BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005178 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005179 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5180 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005181)
5182
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005183ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005184 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005185 traps=[],
5186 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005187)
5188
5189
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005190##### crud for parsing strings #############################################
5191import re
5192
5193# Regular expression used for parsing numeric strings. Additional
5194# comments:
5195#
5196# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5197# whitespace. But note that the specification disallows whitespace in
5198# a numeric string.
5199#
5200# 2. For finite numbers (not infinities and NaNs) the body of the
5201# number between the optional sign and the optional exponent must have
5202# at least one decimal digit, possibly after the decimal point. The
5203# lookahead expression '(?=\d|\.\d)' checks this.
5204#
5205# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5206# other meaning for \d than the numbers [0-9].
5207
5208import re
5209_parser = re.compile(r""" # A numeric string consists of:
5210# \s*
5211 (?P<sign>[-+])? # an optional sign, followed by either...
5212 (
5213 (?=\d|\.\d) # ...a number (with at least one digit)
5214 (?P<int>\d*) # consisting of a (possibly empty) integer part
5215 (\.(?P<frac>\d*))? # followed by an optional fractional part
5216 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5217 |
5218 Inf(inity)? # ...an infinity, or...
5219 |
5220 (?P<signal>s)? # ...an (optionally signaling)
5221 NaN # NaN
5222 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5223 )
5224# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00005225 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005226""", re.VERBOSE | re.IGNORECASE).match
5227
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005228_all_zeros = re.compile('0*$').match
5229_exact_half = re.compile('50*$').match
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005230del re
5231
5232
Guido van Rossumd8faa362007-04-27 19:54:29 +00005233##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005234
Guido van Rossumd8faa362007-04-27 19:54:29 +00005235# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005236Inf = Decimal('Inf')
5237negInf = Decimal('-Inf')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005238NaN = Decimal('NaN')
5239Dec_0 = Decimal(0)
5240Dec_p1 = Decimal(1)
5241Dec_n1 = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005242
Guido van Rossumd8faa362007-04-27 19:54:29 +00005243# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005244Infsign = (Inf, negInf)
5245
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005246
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005247
5248if __name__ == '__main__':
5249 import doctest, sys
5250 doctest.testmod(sys.modules[__name__])