blob: b25f6e61916ee2065dba606569697d5c37d8cf71 [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
Guido van Rossumd8faa362007-04-27 19:54:29 +0000140# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000141ROUND_DOWN = 'ROUND_DOWN'
142ROUND_HALF_UP = 'ROUND_HALF_UP'
143ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
144ROUND_CEILING = 'ROUND_CEILING'
145ROUND_FLOOR = 'ROUND_FLOOR'
146ROUND_UP = 'ROUND_UP'
147ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000148ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000149
Guido van Rossumd8faa362007-04-27 19:54:29 +0000150# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000151
152class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000153 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000154
155 Used exceptions derive from this.
156 If an exception derives from another exception besides this (such as
157 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
158 called if the others are present. This isn't actually used for
159 anything, though.
160
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000161 handle -- Called when context._raise_error is called and the
162 trap_enabler is set. First argument is self, second is the
163 context. More arguments can be given, those being after
164 the explanation in _raise_error (For example,
165 context._raise_error(NewError, '(-x)!', self._sign) would
166 call NewError().handle(context, self._sign).)
167
168 To define a new exception, it should be sufficient to have it derive
169 from DecimalException.
170 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000171 def handle(self, context, *args):
172 pass
173
174
175class Clamped(DecimalException):
176 """Exponent of a 0 changed to fit bounds.
177
178 This occurs and signals clamped if the exponent of a result has been
179 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000180 representation. This may occur when the exponent of a zero result would
181 be outside the bounds of a representation, or when a large normal
182 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000183 this latter case, the exponent is reduced to fit and the corresponding
184 number of zero digits are appended to the coefficient ("fold-down").
185 """
186
187
188class InvalidOperation(DecimalException):
189 """An invalid operation was performed.
190
191 Various bad things cause this:
192
193 Something creates a signaling NaN
194 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000195 0 * (+-)INF
196 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000197 x % 0
198 (+-)INF % x
199 x._rescale( non-integer )
200 sqrt(-x) , x > 0
201 0 ** 0
202 x ** (non-integer)
203 x ** (+-)INF
204 An operand is invalid
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000205
206 The result of the operation after these is a quiet positive NaN,
207 except when the cause is a signaling NaN, in which case the result is
208 also a quiet NaN, but with the original sign, and an optional
209 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000210 """
211 def handle(self, context, *args):
212 if args:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000213 if args[0] == 1: # sNaN, must drop 's' but keep diagnostics
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000214 ans = _dec_from_triple(args[1]._sign, args[1]._int, 'n', True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000215 return ans._fix_nan(context)
216 elif args[0] == 2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000217 return _dec_from_triple(args[1], args[2], 'n', True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000218 return NaN
219
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000220
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000221class ConversionSyntax(InvalidOperation):
222 """Trying to convert badly formed string.
223
224 This occurs and signals invalid-operation if an string is being
225 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000226 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000227 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000228 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000229 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000230
231class DivisionByZero(DecimalException, ZeroDivisionError):
232 """Division by 0.
233
234 This occurs and signals division-by-zero if division of a finite number
235 by zero was attempted (during a divide-integer or divide operation, or a
236 power operation with negative right-hand operand), and the dividend was
237 not zero.
238
239 The result of the operation is [sign,inf], where sign is the exclusive
240 or of the signs of the operands for divide, or is 1 for an odd power of
241 -0, for power.
242 """
243
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000244 def handle(self, context, sign, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000245 return Infsign[sign]
246
247class DivisionImpossible(InvalidOperation):
248 """Cannot perform the division adequately.
249
250 This occurs and signals invalid-operation if the integer result of a
251 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000252 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000253 """
254
255 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000256 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000257
258class DivisionUndefined(InvalidOperation, ZeroDivisionError):
259 """Undefined result of division.
260
261 This occurs and signals invalid-operation if division by zero was
262 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000263 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000264 """
265
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000266 def handle(self, context, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000267 return NaN
268
269class Inexact(DecimalException):
270 """Had to round, losing information.
271
272 This occurs and signals inexact whenever the result of an operation is
273 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000274 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000275 result in all cases is unchanged.
276
277 The inexact signal may be tested (or trapped) to determine if a given
278 operation (or sequence of operations) was inexact.
279 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000280 pass
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 Hettinger5aa478b2004-07-09 10:02:53 +0000307 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000308
309class Subnormal(DecimalException):
310 """Exponent < Emin before rounding.
311
312 This occurs and signals subnormal whenever the result of a conversion or
313 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000314 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000315
316 The subnormal signal may be tested (or trapped) to determine if a given
317 or operation (or sequence of operations) yielded a subnormal result.
318 """
319 pass
320
321class Overflow(Inexact, Rounded):
322 """Numerical overflow.
323
324 This occurs and signals overflow if the adjusted exponent of a result
325 (from a conversion or from an operation that is not an attempt to divide
326 by zero), after rounding, would be greater than the largest value that
327 can be handled by the implementation (the value Emax).
328
329 The result depends on the rounding mode:
330
331 For round-half-up and round-half-even (and for round-half-down and
332 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000333 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000334 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000335 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000336 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000337 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000338 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000339 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000340 will also be raised.
341 """
342
343 def handle(self, context, sign, *args):
344 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000345 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000346 return Infsign[sign]
347 if sign == 0:
348 if context.rounding == ROUND_CEILING:
349 return Infsign[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000350 return _dec_from_triple(sign, '9'*context.prec,
351 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000352 if sign == 1:
353 if context.rounding == ROUND_FLOOR:
354 return Infsign[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000355 return _dec_from_triple(sign, '9'*context.prec,
356 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000357
358
359class Underflow(Inexact, Rounded, Subnormal):
360 """Numerical underflow with result rounded to 0.
361
362 This occurs and signals underflow if a result is inexact and the
363 adjusted exponent of the result would be smaller (more negative) than
364 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000365 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000366
367 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000368 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000369 in 0 with the sign of the intermediate result and an exponent of Etiny.
370
371 In all cases, Inexact, Rounded, and Subnormal will also be raised.
372 """
373
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000374# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000375_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000376 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000377
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000378# Map conditions (per the spec) to signals
379_condition_map = {ConversionSyntax:InvalidOperation,
380 DivisionImpossible:InvalidOperation,
381 DivisionUndefined:InvalidOperation,
382 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000383
Guido van Rossumd8faa362007-04-27 19:54:29 +0000384##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000385
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000386# The getcontext() and setcontext() function manage access to a thread-local
387# current context. Py2.4 offers direct support for thread locals. If that
388# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000389# work for older Pythons. If threads are not part of the build, create a
390# mock threading object with threading.local() returning the module namespace.
391
392try:
393 import threading
394except ImportError:
395 # Python was compiled without threads; create a mock object instead
396 import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +0000397 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000398 def local(self, sys=sys):
399 return sys.modules[__name__]
400 threading = MockThreading()
401 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000402
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000403try:
404 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000405
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000406except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000407
Guido van Rossumd8faa362007-04-27 19:54:29 +0000408 # To fix reloading, force it to create a new context
409 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000410 if hasattr(threading.currentThread(), '__decimal_context__'):
411 del threading.currentThread().__decimal_context__
412
413 def setcontext(context):
414 """Set this thread's context to context."""
415 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000416 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000417 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000418 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000419
420 def getcontext():
421 """Returns this thread's context.
422
423 If this thread does not yet have a context, returns
424 a new context and sets this thread's context.
425 New contexts are copies of DefaultContext.
426 """
427 try:
428 return threading.currentThread().__decimal_context__
429 except AttributeError:
430 context = Context()
431 threading.currentThread().__decimal_context__ = context
432 return context
433
434else:
435
436 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000437 if hasattr(local, '__decimal_context__'):
438 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000439
440 def getcontext(_local=local):
441 """Returns this thread's context.
442
443 If this thread does not yet have a context, returns
444 a new context and sets this thread's context.
445 New contexts are copies of DefaultContext.
446 """
447 try:
448 return _local.__decimal_context__
449 except AttributeError:
450 context = Context()
451 _local.__decimal_context__ = context
452 return context
453
454 def setcontext(context, _local=local):
455 """Set this thread's context to context."""
456 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000457 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000458 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000459 _local.__decimal_context__ = context
460
461 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000462
Thomas Wouters89f507f2006-12-13 04:49:30 +0000463def localcontext(ctx=None):
464 """Return a context manager for a copy of the supplied context
465
466 Uses a copy of the current context if no context is specified
467 The returned context manager creates a local decimal context
468 in a with statement:
469 def sin(x):
470 with localcontext() as ctx:
471 ctx.prec += 2
472 # Rest of sin calculation algorithm
473 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000474 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000475
476 def sin(x):
477 with localcontext(ExtendedContext):
478 # Rest of sin calculation algorithm
479 # uses the Extended Context from the
480 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000481 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000482
483 """
484 # The string below can't be included in the docstring until Python 2.6
485 # as the doctest module doesn't understand __future__ statements
486 """
487 >>> from __future__ import with_statement
Guido van Rossum7131f842007-02-09 20:13:25 +0000488 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000489 28
490 >>> with localcontext():
491 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000492 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000493 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000494 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000495 30
496 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000497 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000498 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000499 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000500 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000501 28
502 """
503 if ctx is None: ctx = getcontext()
504 return _ContextManager(ctx)
505
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000506
Guido van Rossumd8faa362007-04-27 19:54:29 +0000507##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000508
Guido van Rossuma13f4a12007-12-10 20:04:04 +0000509class Decimal(_numbers.Real, _numbers.Inexact):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000510 """Floating point class for decimal arithmetic."""
511
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000512 __slots__ = ('_exp','_int','_sign', '_is_special')
513 # Generally, the value of the Decimal instance is given by
514 # (-1)**_sign * _int * 10**_exp
515 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000516
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000517 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000518 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000519 """Create a decimal point instance.
520
521 >>> Decimal('3.14') # string input
522 Decimal("3.14")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000523 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000524 Decimal("3.14")
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000525 >>> Decimal(314) # int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000526 Decimal("314")
527 >>> Decimal(Decimal(314)) # another decimal instance
528 Decimal("314")
529 """
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):
544 m = _parser(value)
545 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
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000665 1 if NaN (it could be a normal quiet NaN or a phantom one)
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',
711 1, self)
712 if other_is_nan == 2:
713 return context._raise_error(InvalidOperation, 'sNaN',
714 1, other)
715 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000716 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000717
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000718 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000719 return 0
720
Jack Diederich4dafcc42006-11-28 19:15:13 +0000721 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000722 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000723
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000724 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000725 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000726 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000727
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000728 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000729 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000730 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000731 # Never return NotImplemented
732 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000733
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000734 if self._is_special or other._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000735 # check for nans, without raising on a signaling nan
736 if self._isnan() or other._isnan():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000737 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000738
739 # INF = INF
740 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000741
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000742 # check for zeros; note that cmp(0, -0) should return 0
743 if not self:
744 if not other:
745 return 0
746 else:
747 return -((-1)**other._sign)
748 if not other:
749 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000750
Guido van Rossumd8faa362007-04-27 19:54:29 +0000751 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000752 if other._sign < self._sign:
753 return -1
754 if self._sign < other._sign:
755 return 1
756
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000757 self_adjusted = self.adjusted()
758 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000759 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000760 self_padded = self._int + '0'*(self._exp - other._exp)
761 other_padded = other._int + '0'*(other._exp - self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000762 return cmp(self_padded, other_padded) * (-1)**self._sign
763 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000764 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000765 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000766 return -((-1)**self._sign)
767
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000768 def __eq__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000769 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000770 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000771 return self.__cmp__(other) == 0
772
773 def __ne__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000774 if not isinstance(other, (Decimal, int)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000775 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000776 return self.__cmp__(other) != 0
777
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000778 def __lt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000779 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000780 return NotImplemented
781 return self.__cmp__(other) < 0
782
783 def __le__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000784 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000785 return NotImplemented
786 return self.__cmp__(other) <= 0
787
788 def __gt__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000789 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000790 return NotImplemented
791 return self.__cmp__(other) > 0
792
793 def __ge__(self, other):
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000794 if not isinstance(other, (Decimal, int)):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000795 return NotImplemented
796 return self.__cmp__(other) >= 0
797
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000798 def compare(self, other, context=None):
799 """Compares one to another.
800
801 -1 => a < b
802 0 => a = b
803 1 => a > b
804 NaN => one is NaN
805 Like __cmp__, but returns Decimal instances.
806 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000807 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000808
Guido van Rossumd8faa362007-04-27 19:54:29 +0000809 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000810 if (self._is_special or other and other._is_special):
811 ans = self._check_nans(other, context)
812 if ans:
813 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000814
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000815 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000816
817 def __hash__(self):
818 """x.__hash__() <==> hash(x)"""
819 # Decimal integers must hash the same as the ints
820 # Non-integer decimals are normalized and hashed as strings
Thomas Wouters477c8d52006-05-27 19:21:47 +0000821 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000822 if self._is_special:
823 if self._isnan():
824 raise TypeError('Cannot hash a NaN value.')
825 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000826 if not self:
827 return 0
828 if self._isinteger():
829 op = _WorkRep(self.to_integral_value())
830 # to make computation feasible for Decimals with large
831 # exponent, we use the fact that hash(n) == hash(m) for
832 # any two nonzero integers n and m such that (i) n and m
833 # have the same sign, and (ii) n is congruent to m modulo
834 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
835 # hash((-1)**s*c*pow(10, e, 2**64-1).
836 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000837 return hash(str(self.normalize()))
838
839 def as_tuple(self):
840 """Represents the number as a triple tuple.
841
842 To show the internals exactly as they are.
843 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000844 return (self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000845
846 def __repr__(self):
847 """Represents the number as an instance of Decimal."""
848 # Invariant: eval(repr(d)) == d
849 return 'Decimal("%s")' % str(self)
850
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000851 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000852 """Return string representation of the number in scientific notation.
853
854 Captures all of the information in the underlying representation.
855 """
856
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000857 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000858 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000859 if self._exp == 'F':
860 return sign + 'Infinity'
861 elif self._exp == 'n':
862 return sign + 'NaN' + self._int
863 else: # self._exp == 'N'
864 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000865
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000866 # number of digits of self._int to left of decimal point
867 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000868
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000869 # dotplace is number of digits of self._int to the left of the
870 # decimal point in the mantissa of the output string (that is,
871 # after adjusting the exponent)
872 if self._exp <= 0 and leftdigits > -6:
873 # no exponent required
874 dotplace = leftdigits
875 elif not eng:
876 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000877 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000878 elif self._int == '0':
879 # engineering notation, zero
880 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000881 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000882 # engineering notation, nonzero
883 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000884
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000885 if dotplace <= 0:
886 intpart = '0'
887 fracpart = '.' + '0'*(-dotplace) + self._int
888 elif dotplace >= len(self._int):
889 intpart = self._int+'0'*(dotplace-len(self._int))
890 fracpart = ''
891 else:
892 intpart = self._int[:dotplace]
893 fracpart = '.' + self._int[dotplace:]
894 if leftdigits == dotplace:
895 exp = ''
896 else:
897 if context is None:
898 context = getcontext()
899 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
900
901 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000902
903 def to_eng_string(self, context=None):
904 """Convert to engineering-type string.
905
906 Engineering notation has an exponent which is a multiple of 3, so there
907 are up to 3 digits left of the decimal place.
908
909 Same rules for when in exponential and when as a value as in __str__.
910 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000911 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000912
913 def __neg__(self, context=None):
914 """Returns a copy with the sign switched.
915
916 Rounds, if it has reason.
917 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000918 if self._is_special:
919 ans = self._check_nans(context=context)
920 if ans:
921 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000922
923 if not self:
924 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000925 ans = self.copy_sign(Dec_0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000926 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000927 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000928
929 if context is None:
930 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +0000931 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000932
933 def __pos__(self, context=None):
934 """Returns a copy, unless it is a sNaN.
935
936 Rounds the number (if more then precision digits)
937 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000938 if self._is_special:
939 ans = self._check_nans(context=context)
940 if ans:
941 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000942
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000943 if not self:
944 # + (-0) = 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000945 ans = self.copy_sign(Dec_0)
946 else:
947 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000948
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000949 if context is None:
950 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +0000951 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000952
Christian Heimes2c181612007-12-17 20:04:13 +0000953 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000954 """Returns the absolute value of self.
955
Christian Heimes2c181612007-12-17 20:04:13 +0000956 If the keyword argument 'round' is false, do not round. The
957 expression self.__abs__(round=False) is equivalent to
958 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000959 """
Christian Heimes2c181612007-12-17 20:04:13 +0000960 if not round:
961 return self.copy_abs()
962
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000963 if self._is_special:
964 ans = self._check_nans(context=context)
965 if ans:
966 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000967
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000968 if self._sign:
969 ans = self.__neg__(context=context)
970 else:
971 ans = self.__pos__(context=context)
972
973 return ans
974
975 def __add__(self, other, context=None):
976 """Returns self + other.
977
978 -INF + INF (or the reverse) cause InvalidOperation errors.
979 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000980 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000981 if other is NotImplemented:
982 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000983
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000984 if context is None:
985 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000986
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000987 if self._is_special or other._is_special:
988 ans = self._check_nans(other, context)
989 if ans:
990 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000991
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000992 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000993 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000994 if self._sign != other._sign and other._isinfinity():
995 return context._raise_error(InvalidOperation, '-INF + INF')
996 return Decimal(self)
997 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000998 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000999
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000 exp = min(self._exp, other._exp)
1001 negativezero = 0
1002 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001003 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001004 negativezero = 1
1005
1006 if not self and not other:
1007 sign = min(self._sign, other._sign)
1008 if negativezero:
1009 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001010 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001011 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001012 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001013 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001014 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001015 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001016 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001017 return ans
1018 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001019 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001020 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001021 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001022 return ans
1023
1024 op1 = _WorkRep(self)
1025 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001026 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001027
1028 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001029 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001030 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001031 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001032 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001033 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001034 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001035 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001036 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001037 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001038 if op1.sign == 1:
1039 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001040 op1.sign, op2.sign = op2.sign, op1.sign
1041 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001042 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001043 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001044 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001045 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001046 op1.sign, op2.sign = (0, 0)
1047 else:
1048 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001049 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001050
Raymond Hettinger17931de2004-10-27 06:21:46 +00001051 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001052 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001053 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001054 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055
1056 result.exp = op1.exp
1057 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001058 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001059 return ans
1060
1061 __radd__ = __add__
1062
1063 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001064 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001065 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001066 if other is NotImplemented:
1067 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001068
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001069 if self._is_special or other._is_special:
1070 ans = self._check_nans(other, context=context)
1071 if ans:
1072 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001073
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001074 # self - other is computed as self + other.copy_negate()
1075 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001076
1077 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001078 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001079 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001080 if other is NotImplemented:
1081 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001082
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001083 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001084
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001085 def __mul__(self, other, context=None):
1086 """Return self * other.
1087
1088 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1089 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001090 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001091 if other is NotImplemented:
1092 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001093
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001094 if context is None:
1095 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001096
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001097 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001098
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001099 if self._is_special or other._is_special:
1100 ans = self._check_nans(other, context)
1101 if ans:
1102 return ans
1103
1104 if self._isinfinity():
1105 if not other:
1106 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1107 return Infsign[resultsign]
1108
1109 if other._isinfinity():
1110 if not self:
1111 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1112 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001113
1114 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001115
1116 # Special case for multiplying by zero
1117 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001118 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001119 # Fixing in case the exponent is out of bounds
1120 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001121 return ans
1122
1123 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001124 if self._int == '1':
1125 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001126 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001127 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001128 if other._int == '1':
1129 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001130 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001131 return ans
1132
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001133 op1 = _WorkRep(self)
1134 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001135
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001136 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001137 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001138
1139 return ans
1140 __rmul__ = __mul__
1141
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001142 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001143 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001144 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001145 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001146 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001147
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001148 if context is None:
1149 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001150
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001151 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001152
1153 if self._is_special or other._is_special:
1154 ans = self._check_nans(other, context)
1155 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001156 return ans
1157
1158 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001159 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001160
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001161 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001162 return Infsign[sign]
1163
1164 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001165 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001166 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001167
1168 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001169 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001170 if not self:
1171 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001172 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001173
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001174 if not self:
1175 exp = self._exp - other._exp
1176 coeff = 0
1177 else:
1178 # OK, so neither = 0, INF or NaN
1179 shift = len(other._int) - len(self._int) + context.prec + 1
1180 exp = self._exp - other._exp - shift
1181 op1 = _WorkRep(self)
1182 op2 = _WorkRep(other)
1183 if shift >= 0:
1184 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1185 else:
1186 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1187 if remainder:
1188 # result is not exact; adjust to ensure correct rounding
1189 if coeff % 5 == 0:
1190 coeff += 1
1191 else:
1192 # result is exact; get as close to ideal exponent as possible
1193 ideal_exp = self._exp - other._exp
1194 while exp < ideal_exp and coeff % 10 == 0:
1195 coeff //= 10
1196 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001197
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001198 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001199 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001200
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001201 def _divide(self, other, context):
1202 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001203
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001204 Assumes that neither self nor other is a NaN, that self is not
1205 infinite and that other is nonzero.
1206 """
1207 sign = self._sign ^ other._sign
1208 if other._isinfinity():
1209 ideal_exp = self._exp
1210 else:
1211 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001212
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001213 expdiff = self.adjusted() - other.adjusted()
1214 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001215 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001216 self._rescale(ideal_exp, context.rounding))
1217 if expdiff <= context.prec:
1218 op1 = _WorkRep(self)
1219 op2 = _WorkRep(other)
1220 if op1.exp >= op2.exp:
1221 op1.int *= 10**(op1.exp - op2.exp)
1222 else:
1223 op2.int *= 10**(op2.exp - op1.exp)
1224 q, r = divmod(op1.int, op2.int)
1225 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001226 return (_dec_from_triple(sign, str(q), 0),
1227 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001228
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001229 # Here the quotient is too large to be representable
1230 ans = context._raise_error(DivisionImpossible,
1231 'quotient too large in //, % or divmod')
1232 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001233
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001234 def __rtruediv__(self, other, context=None):
1235 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001236 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001237 if other is NotImplemented:
1238 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001239 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001240
1241 def __divmod__(self, other, context=None):
1242 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001243 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001244 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001245 other = _convert_other(other)
1246 if other is NotImplemented:
1247 return other
1248
1249 if context is None:
1250 context = getcontext()
1251
1252 ans = self._check_nans(other, context)
1253 if ans:
1254 return (ans, ans)
1255
1256 sign = self._sign ^ other._sign
1257 if self._isinfinity():
1258 if other._isinfinity():
1259 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1260 return ans, ans
1261 else:
1262 return (Infsign[sign],
1263 context._raise_error(InvalidOperation, 'INF % x'))
1264
1265 if not other:
1266 if not self:
1267 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1268 return ans, ans
1269 else:
1270 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1271 context._raise_error(InvalidOperation, 'x % 0'))
1272
1273 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001274 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001275 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001276
1277 def __rdivmod__(self, other, context=None):
1278 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001279 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001280 if other is NotImplemented:
1281 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001282 return other.__divmod__(self, context=context)
1283
1284 def __mod__(self, other, context=None):
1285 """
1286 self % other
1287 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001288 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001289 if other is NotImplemented:
1290 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001291
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001292 if context is None:
1293 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001294
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001295 ans = self._check_nans(other, context)
1296 if ans:
1297 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001298
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001299 if self._isinfinity():
1300 return context._raise_error(InvalidOperation, 'INF % x')
1301 elif not other:
1302 if self:
1303 return context._raise_error(InvalidOperation, 'x % 0')
1304 else:
1305 return context._raise_error(DivisionUndefined, '0 % 0')
1306
1307 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001308 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001309 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001310
1311 def __rmod__(self, other, context=None):
1312 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001313 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001314 if other is NotImplemented:
1315 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001316 return other.__mod__(self, context=context)
1317
1318 def remainder_near(self, other, context=None):
1319 """
1320 Remainder nearest to 0- abs(remainder-near) <= other/2
1321 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001322 if context is None:
1323 context = getcontext()
1324
1325 other = _convert_other(other, raiseit=True)
1326
1327 ans = self._check_nans(other, context)
1328 if ans:
1329 return ans
1330
1331 # self == +/-infinity -> InvalidOperation
1332 if self._isinfinity():
1333 return context._raise_error(InvalidOperation,
1334 'remainder_near(infinity, x)')
1335
1336 # other == 0 -> either InvalidOperation or DivisionUndefined
1337 if not other:
1338 if self:
1339 return context._raise_error(InvalidOperation,
1340 'remainder_near(x, 0)')
1341 else:
1342 return context._raise_error(DivisionUndefined,
1343 'remainder_near(0, 0)')
1344
1345 # other = +/-infinity -> remainder = self
1346 if other._isinfinity():
1347 ans = Decimal(self)
1348 return ans._fix(context)
1349
1350 # self = 0 -> remainder = self, with ideal exponent
1351 ideal_exponent = min(self._exp, other._exp)
1352 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001353 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001354 return ans._fix(context)
1355
1356 # catch most cases of large or small quotient
1357 expdiff = self.adjusted() - other.adjusted()
1358 if expdiff >= context.prec + 1:
1359 # expdiff >= prec+1 => abs(self/other) > 10**prec
1360 return context._raise_error(DivisionImpossible)
1361 if expdiff <= -2:
1362 # expdiff <= -2 => abs(self/other) < 0.1
1363 ans = self._rescale(ideal_exponent, context.rounding)
1364 return ans._fix(context)
1365
1366 # adjust both arguments to have the same exponent, then divide
1367 op1 = _WorkRep(self)
1368 op2 = _WorkRep(other)
1369 if op1.exp >= op2.exp:
1370 op1.int *= 10**(op1.exp - op2.exp)
1371 else:
1372 op2.int *= 10**(op2.exp - op1.exp)
1373 q, r = divmod(op1.int, op2.int)
1374 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1375 # 10**ideal_exponent. Apply correction to ensure that
1376 # abs(remainder) <= abs(other)/2
1377 if 2*r + (q&1) > op2.int:
1378 r -= op2.int
1379 q += 1
1380
1381 if q >= 10**context.prec:
1382 return context._raise_error(DivisionImpossible)
1383
1384 # result has same sign as self unless r is negative
1385 sign = self._sign
1386 if r < 0:
1387 sign = 1-sign
1388 r = -r
1389
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001390 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001391 return ans._fix(context)
1392
1393 def __floordiv__(self, other, context=None):
1394 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001395 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001396 if other is NotImplemented:
1397 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001398
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001399 if context is None:
1400 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001401
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001402 ans = self._check_nans(other, context)
1403 if ans:
1404 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001405
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001406 if self._isinfinity():
1407 if other._isinfinity():
1408 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001409 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001410 return Infsign[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001411
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001412 if not other:
1413 if self:
1414 return context._raise_error(DivisionByZero, 'x // 0',
1415 self._sign ^ other._sign)
1416 else:
1417 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001418
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001419 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001420
1421 def __rfloordiv__(self, other, context=None):
1422 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001423 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001424 if other is NotImplemented:
1425 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001426 return other.__floordiv__(self, context=context)
1427
1428 def __float__(self):
1429 """Float representation."""
1430 return float(str(self))
1431
1432 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001433 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001434 if self._is_special:
1435 if self._isnan():
1436 context = getcontext()
1437 return context._raise_error(InvalidContext)
1438 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001439 raise OverflowError("Cannot convert infinity to int")
1440 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001441 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001442 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001443 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001444 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001445
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001446 def _fix_nan(self, context):
1447 """Decapitate the payload of a NaN to fit the context"""
1448 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001449
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001450 # maximum length of payload is precision if _clamp=0,
1451 # precision-1 if _clamp=1.
1452 max_payload_len = context.prec - context._clamp
1453 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001454 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1455 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001456 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001457
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001458 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001459 """Round if it is necessary to keep self within prec precision.
1460
1461 Rounds and fixes the exponent. Does not raise on a sNaN.
1462
1463 Arguments:
1464 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001465 context - context used.
1466 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001467
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001468 if context is None:
1469 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001470
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001471 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001472 if self._isnan():
1473 # decapitate payload if necessary
1474 return self._fix_nan(context)
1475 else:
1476 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001477 return Decimal(self)
1478
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001479 # if self is zero then exponent should be between Etiny and
1480 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1481 Etiny = context.Etiny()
1482 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001483 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001484 exp_max = [context.Emax, Etop][context._clamp]
1485 new_exp = min(max(self._exp, Etiny), exp_max)
1486 if new_exp != self._exp:
1487 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001488 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001489 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001490 return Decimal(self)
1491
1492 # exp_min is the smallest allowable exponent of the result,
1493 # equal to max(self.adjusted()-context.prec+1, Etiny)
1494 exp_min = len(self._int) + self._exp - context.prec
1495 if exp_min > Etop:
1496 # overflow: exp_min > Etop iff self.adjusted() > Emax
1497 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001498 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001499 return context._raise_error(Overflow, 'above Emax', self._sign)
1500 self_is_subnormal = exp_min < Etiny
1501 if self_is_subnormal:
1502 context._raise_error(Subnormal)
1503 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001504
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001505 # round if self has too many digits
1506 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001507 context._raise_error(Rounded)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001508 digits = len(self._int) + self._exp - exp_min
1509 if digits < 0:
1510 self = _dec_from_triple(self._sign, '1', exp_min-1)
1511 digits = 0
1512 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1513 changed = this_function(digits)
1514 coeff = self._int[:digits] or '0'
1515 if changed == 1:
1516 coeff = str(int(coeff)+1)
1517 ans = _dec_from_triple(self._sign, coeff, exp_min)
1518
1519 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001520 context._raise_error(Inexact)
1521 if self_is_subnormal:
1522 context._raise_error(Underflow)
1523 if not ans:
1524 # raise Clamped on underflow to 0
1525 context._raise_error(Clamped)
1526 elif len(ans._int) == context.prec+1:
1527 # we get here only if rescaling rounds the
1528 # cofficient up to exactly 10**context.prec
1529 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001530 ans = _dec_from_triple(ans._sign,
1531 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001532 else:
1533 # Inexact and Rounded have already been raised
1534 ans = context._raise_error(Overflow, 'above Emax',
1535 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001536 return ans
1537
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001538 # fold down if _clamp == 1 and self has too few digits
1539 if context._clamp == 1 and self._exp > Etop:
1540 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001541 self_padded = self._int + '0'*(self._exp - Etop)
1542 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001543
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001544 # here self was representable to begin with; return unchanged
1545 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001546
1547 _pick_rounding_function = {}
1548
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001549 # for each of the rounding functions below:
1550 # self is a finite, nonzero Decimal
1551 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001552 #
1553 # each function returns either -1, 0, or 1, as follows:
1554 # 1 indicates that self should be rounded up (away from zero)
1555 # 0 indicates that self should be truncated, and that all the
1556 # digits to be truncated are zeros (so the value is unchanged)
1557 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001558
1559 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001560 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001561 if _all_zeros(self._int, prec):
1562 return 0
1563 else:
1564 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001565
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001566 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001567 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001568 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001569
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001570 def _round_half_up(self, prec):
1571 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001572 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001573 return 1
1574 elif _all_zeros(self._int, prec):
1575 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001576 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001577 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001578
1579 def _round_half_down(self, prec):
1580 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001581 if _exact_half(self._int, prec):
1582 return -1
1583 else:
1584 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001585
1586 def _round_half_even(self, prec):
1587 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001588 if _exact_half(self._int, prec) and \
1589 (prec == 0 or self._int[prec-1] in '02468'):
1590 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001591 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001592 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001593
1594 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001595 """Rounds up (not away from 0 if negative.)"""
1596 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001597 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001598 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001599 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001600
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001601 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001602 """Rounds down (not towards 0 if negative)"""
1603 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001604 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001605 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001606 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001607
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001608 def _round_05up(self, prec):
1609 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001610 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001611 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001612 else:
1613 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001614
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001615 def fma(self, other, third, context=None):
1616 """Fused multiply-add.
1617
1618 Returns self*other+third with no rounding of the intermediate
1619 product self*other.
1620
1621 self and other are multiplied together, with no rounding of
1622 the result. The third operand is then added to the result,
1623 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001624 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001625
1626 other = _convert_other(other, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001627
1628 # compute product; raise InvalidOperation if either operand is
1629 # a signaling NaN or if the product is zero times infinity.
1630 if self._is_special or other._is_special:
1631 if context is None:
1632 context = getcontext()
1633 if self._exp == 'N':
1634 return context._raise_error(InvalidOperation, 'sNaN',
1635 1, self)
1636 if other._exp == 'N':
1637 return context._raise_error(InvalidOperation, 'sNaN',
1638 1, other)
1639 if self._exp == 'n':
1640 product = self
1641 elif other._exp == 'n':
1642 product = other
1643 elif self._exp == 'F':
1644 if not other:
1645 return context._raise_error(InvalidOperation,
1646 'INF * 0 in fma')
1647 product = Infsign[self._sign ^ other._sign]
1648 elif other._exp == 'F':
1649 if not self:
1650 return context._raise_error(InvalidOperation,
1651 '0 * INF in fma')
1652 product = Infsign[self._sign ^ other._sign]
1653 else:
1654 product = _dec_from_triple(self._sign ^ other._sign,
1655 str(int(self._int) * int(other._int)),
1656 self._exp + other._exp)
1657
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001658 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001659 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001660
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001661 def _power_modulo(self, other, modulo, context=None):
1662 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001663
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001664 # if can't convert other and modulo to Decimal, raise
1665 # TypeError; there's no point returning NotImplemented (no
1666 # equivalent of __rpow__ for three argument pow)
1667 other = _convert_other(other, raiseit=True)
1668 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001669
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001670 if context is None:
1671 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001672
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001673 # deal with NaNs: if there are any sNaNs then first one wins,
1674 # (i.e. behaviour for NaNs is identical to that of fma)
1675 self_is_nan = self._isnan()
1676 other_is_nan = other._isnan()
1677 modulo_is_nan = modulo._isnan()
1678 if self_is_nan or other_is_nan or modulo_is_nan:
1679 if self_is_nan == 2:
1680 return context._raise_error(InvalidOperation, 'sNaN',
1681 1, self)
1682 if other_is_nan == 2:
1683 return context._raise_error(InvalidOperation, 'sNaN',
1684 1, other)
1685 if modulo_is_nan == 2:
1686 return context._raise_error(InvalidOperation, 'sNaN',
1687 1, modulo)
1688 if self_is_nan:
1689 return self._fix_nan(context)
1690 if other_is_nan:
1691 return other._fix_nan(context)
1692 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001693
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001694 # check inputs: we apply same restrictions as Python's pow()
1695 if not (self._isinteger() and
1696 other._isinteger() and
1697 modulo._isinteger()):
1698 return context._raise_error(InvalidOperation,
1699 'pow() 3rd argument not allowed '
1700 'unless all arguments are integers')
1701 if other < 0:
1702 return context._raise_error(InvalidOperation,
1703 'pow() 2nd argument cannot be '
1704 'negative when 3rd argument specified')
1705 if not modulo:
1706 return context._raise_error(InvalidOperation,
1707 'pow() 3rd argument cannot be 0')
1708
1709 # additional restriction for decimal: the modulus must be less
1710 # than 10**prec in absolute value
1711 if modulo.adjusted() >= context.prec:
1712 return context._raise_error(InvalidOperation,
1713 'insufficient precision: pow() 3rd '
1714 'argument must not have more than '
1715 'precision digits')
1716
1717 # define 0**0 == NaN, for consistency with two-argument pow
1718 # (even though it hurts!)
1719 if not other and not self:
1720 return context._raise_error(InvalidOperation,
1721 'at least one of pow() 1st argument '
1722 'and 2nd argument must be nonzero ;'
1723 '0**0 is not defined')
1724
1725 # compute sign of result
1726 if other._iseven():
1727 sign = 0
1728 else:
1729 sign = self._sign
1730
1731 # convert modulo to a Python integer, and self and other to
1732 # Decimal integers (i.e. force their exponents to be >= 0)
1733 modulo = abs(int(modulo))
1734 base = _WorkRep(self.to_integral_value())
1735 exponent = _WorkRep(other.to_integral_value())
1736
1737 # compute result using integer pow()
1738 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1739 for i in range(exponent.exp):
1740 base = pow(base, 10, modulo)
1741 base = pow(base, exponent.int, modulo)
1742
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001743 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001744
1745 def _power_exact(self, other, p):
1746 """Attempt to compute self**other exactly.
1747
1748 Given Decimals self and other and an integer p, attempt to
1749 compute an exact result for the power self**other, with p
1750 digits of precision. Return None if self**other is not
1751 exactly representable in p digits.
1752
1753 Assumes that elimination of special cases has already been
1754 performed: self and other must both be nonspecial; self must
1755 be positive and not numerically equal to 1; other must be
1756 nonzero. For efficiency, other._exp should not be too large,
1757 so that 10**abs(other._exp) is a feasible calculation."""
1758
1759 # In the comments below, we write x for the value of self and
1760 # y for the value of other. Write x = xc*10**xe and y =
1761 # yc*10**ye.
1762
1763 # The main purpose of this method is to identify the *failure*
1764 # of x**y to be exactly representable with as little effort as
1765 # possible. So we look for cheap and easy tests that
1766 # eliminate the possibility of x**y being exact. Only if all
1767 # these tests are passed do we go on to actually compute x**y.
1768
1769 # Here's the main idea. First normalize both x and y. We
1770 # express y as a rational m/n, with m and n relatively prime
1771 # and n>0. Then for x**y to be exactly representable (at
1772 # *any* precision), xc must be the nth power of a positive
1773 # integer and xe must be divisible by n. If m is negative
1774 # then additionally xc must be a power of either 2 or 5, hence
1775 # a power of 2**n or 5**n.
1776 #
1777 # There's a limit to how small |y| can be: if y=m/n as above
1778 # then:
1779 #
1780 # (1) if xc != 1 then for the result to be representable we
1781 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1782 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1783 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1784 # representable.
1785 #
1786 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1787 # |y| < 1/|xe| then the result is not representable.
1788 #
1789 # Note that since x is not equal to 1, at least one of (1) and
1790 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1791 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1792 #
1793 # There's also a limit to how large y can be, at least if it's
1794 # positive: the normalized result will have coefficient xc**y,
1795 # so if it's representable then xc**y < 10**p, and y <
1796 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1797 # not exactly representable.
1798
1799 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1800 # so |y| < 1/xe and the result is not representable.
1801 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1802 # < 1/nbits(xc).
1803
1804 x = _WorkRep(self)
1805 xc, xe = x.int, x.exp
1806 while xc % 10 == 0:
1807 xc //= 10
1808 xe += 1
1809
1810 y = _WorkRep(other)
1811 yc, ye = y.int, y.exp
1812 while yc % 10 == 0:
1813 yc //= 10
1814 ye += 1
1815
1816 # case where xc == 1: result is 10**(xe*y), with xe*y
1817 # required to be an integer
1818 if xc == 1:
1819 if ye >= 0:
1820 exponent = xe*yc*10**ye
1821 else:
1822 exponent, remainder = divmod(xe*yc, 10**-ye)
1823 if remainder:
1824 return None
1825 if y.sign == 1:
1826 exponent = -exponent
1827 # if other is a nonnegative integer, use ideal exponent
1828 if other._isinteger() and other._sign == 0:
1829 ideal_exponent = self._exp*int(other)
1830 zeros = min(exponent-ideal_exponent, p-1)
1831 else:
1832 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001833 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001834
1835 # case where y is negative: xc must be either a power
1836 # of 2 or a power of 5.
1837 if y.sign == 1:
1838 last_digit = xc % 10
1839 if last_digit in (2,4,6,8):
1840 # quick test for power of 2
1841 if xc & -xc != xc:
1842 return None
1843 # now xc is a power of 2; e is its exponent
1844 e = _nbits(xc)-1
1845 # find e*y and xe*y; both must be integers
1846 if ye >= 0:
1847 y_as_int = yc*10**ye
1848 e = e*y_as_int
1849 xe = xe*y_as_int
1850 else:
1851 ten_pow = 10**-ye
1852 e, remainder = divmod(e*yc, ten_pow)
1853 if remainder:
1854 return None
1855 xe, remainder = divmod(xe*yc, ten_pow)
1856 if remainder:
1857 return None
1858
1859 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1860 return None
1861 xc = 5**e
1862
1863 elif last_digit == 5:
1864 # e >= log_5(xc) if xc is a power of 5; we have
1865 # equality all the way up to xc=5**2658
1866 e = _nbits(xc)*28//65
1867 xc, remainder = divmod(5**e, xc)
1868 if remainder:
1869 return None
1870 while xc % 5 == 0:
1871 xc //= 5
1872 e -= 1
1873 if ye >= 0:
1874 y_as_integer = yc*10**ye
1875 e = e*y_as_integer
1876 xe = xe*y_as_integer
1877 else:
1878 ten_pow = 10**-ye
1879 e, remainder = divmod(e*yc, ten_pow)
1880 if remainder:
1881 return None
1882 xe, remainder = divmod(xe*yc, ten_pow)
1883 if remainder:
1884 return None
1885 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1886 return None
1887 xc = 2**e
1888 else:
1889 return None
1890
1891 if xc >= 10**p:
1892 return None
1893 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001894 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001895
1896 # now y is positive; find m and n such that y = m/n
1897 if ye >= 0:
1898 m, n = yc*10**ye, 1
1899 else:
1900 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1901 return None
1902 xc_bits = _nbits(xc)
1903 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1904 return None
1905 m, n = yc, 10**(-ye)
1906 while m % 2 == n % 2 == 0:
1907 m //= 2
1908 n //= 2
1909 while m % 5 == n % 5 == 0:
1910 m //= 5
1911 n //= 5
1912
1913 # compute nth root of xc*10**xe
1914 if n > 1:
1915 # if 1 < xc < 2**n then xc isn't an nth power
1916 if xc != 1 and xc_bits <= n:
1917 return None
1918
1919 xe, rem = divmod(xe, n)
1920 if rem != 0:
1921 return None
1922
1923 # compute nth root of xc using Newton's method
1924 a = 1 << -(-_nbits(xc)//n) # initial estimate
1925 while True:
1926 q, r = divmod(xc, a**(n-1))
1927 if a <= q:
1928 break
1929 else:
1930 a = (a*(n-1) + q)//n
1931 if not (a == q and r == 0):
1932 return None
1933 xc = a
1934
1935 # now xc*10**xe is the nth root of the original xc*10**xe
1936 # compute mth power of xc*10**xe
1937
1938 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1939 # 10**p and the result is not representable.
1940 if xc > 1 and m > p*100//_log10_lb(xc):
1941 return None
1942 xc = xc**m
1943 xe *= m
1944 if xc > 10**p:
1945 return None
1946
1947 # by this point the result *is* exactly representable
1948 # adjust the exponent to get as close as possible to the ideal
1949 # exponent, if necessary
1950 str_xc = str(xc)
1951 if other._isinteger() and other._sign == 0:
1952 ideal_exponent = self._exp*int(other)
1953 zeros = min(xe-ideal_exponent, p-len(str_xc))
1954 else:
1955 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001956 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001957
1958 def __pow__(self, other, modulo=None, context=None):
1959 """Return self ** other [ % modulo].
1960
1961 With two arguments, compute self**other.
1962
1963 With three arguments, compute (self**other) % modulo. For the
1964 three argument form, the following restrictions on the
1965 arguments hold:
1966
1967 - all three arguments must be integral
1968 - other must be nonnegative
1969 - either self or other (or both) must be nonzero
1970 - modulo must be nonzero and must have at most p digits,
1971 where p is the context precision.
1972
1973 If any of these restrictions is violated the InvalidOperation
1974 flag is raised.
1975
1976 The result of pow(self, other, modulo) is identical to the
1977 result that would be obtained by computing (self**other) %
1978 modulo with unbounded precision, but is computed more
1979 efficiently. It is always exact.
1980 """
1981
1982 if modulo is not None:
1983 return self._power_modulo(other, modulo, context)
1984
1985 other = _convert_other(other)
1986 if other is NotImplemented:
1987 return other
1988
1989 if context is None:
1990 context = getcontext()
1991
1992 # either argument is a NaN => result is NaN
1993 ans = self._check_nans(other, context)
1994 if ans:
1995 return ans
1996
1997 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1998 if not other:
1999 if not self:
2000 return context._raise_error(InvalidOperation, '0 ** 0')
2001 else:
2002 return Dec_p1
2003
2004 # result has sign 1 iff self._sign is 1 and other is an odd integer
2005 result_sign = 0
2006 if self._sign == 1:
2007 if other._isinteger():
2008 if not other._iseven():
2009 result_sign = 1
2010 else:
2011 # -ve**noninteger = NaN
2012 # (-0)**noninteger = 0**noninteger
2013 if self:
2014 return context._raise_error(InvalidOperation,
2015 'x ** y with x negative and y not an integer')
2016 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002017 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002018
2019 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2020 if not self:
2021 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002022 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002023 else:
2024 return Infsign[result_sign]
2025
2026 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002027 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002028 if other._sign == 0:
2029 return Infsign[result_sign]
2030 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002031 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002032
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002033 # 1**other = 1, but the choice of exponent and the flags
2034 # depend on the exponent of self, and on whether other is a
2035 # positive integer, a negative integer, or neither
2036 if self == Dec_p1:
2037 if other._isinteger():
2038 # exp = max(self._exp*max(int(other), 0),
2039 # 1-context.prec) but evaluating int(other) directly
2040 # is dangerous until we know other is small (other
2041 # could be 1e999999999)
2042 if other._sign == 1:
2043 multiplier = 0
2044 elif other > context.prec:
2045 multiplier = context.prec
2046 else:
2047 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002048
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002049 exp = self._exp * multiplier
2050 if exp < 1-context.prec:
2051 exp = 1-context.prec
2052 context._raise_error(Rounded)
2053 else:
2054 context._raise_error(Inexact)
2055 context._raise_error(Rounded)
2056 exp = 1-context.prec
2057
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002058 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002059
2060 # compute adjusted exponent of self
2061 self_adj = self.adjusted()
2062
2063 # self ** infinity is infinity if self > 1, 0 if self < 1
2064 # self ** -infinity is infinity if self < 1, 0 if self > 1
2065 if other._isinfinity():
2066 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002067 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002068 else:
2069 return Infsign[result_sign]
2070
2071 # from here on, the result always goes through the call
2072 # to _fix at the end of this function.
2073 ans = None
2074
2075 # crude test to catch cases of extreme overflow/underflow. If
2076 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2077 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2078 # self**other >= 10**(Emax+1), so overflow occurs. The test
2079 # for underflow is similar.
2080 bound = self._log10_exp_bound() + other.adjusted()
2081 if (self_adj >= 0) == (other._sign == 0):
2082 # self > 1 and other +ve, or self < 1 and other -ve
2083 # possibility of overflow
2084 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002085 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002086 else:
2087 # self > 1 and other -ve, or self < 1 and other +ve
2088 # possibility of underflow to 0
2089 Etiny = context.Etiny()
2090 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002091 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002092
2093 # try for an exact result with precision +1
2094 if ans is None:
2095 ans = self._power_exact(other, context.prec + 1)
2096 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002097 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002098
2099 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2100 if ans is None:
2101 p = context.prec
2102 x = _WorkRep(self)
2103 xc, xe = x.int, x.exp
2104 y = _WorkRep(other)
2105 yc, ye = y.int, y.exp
2106 if y.sign == 1:
2107 yc = -yc
2108
2109 # compute correctly rounded result: start with precision +3,
2110 # then increase precision until result is unambiguously roundable
2111 extra = 3
2112 while True:
2113 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2114 if coeff % (5*10**(len(str(coeff))-p-1)):
2115 break
2116 extra += 3
2117
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002118 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002119
2120 # the specification says that for non-integer other we need to
2121 # raise Inexact, even when the result is actually exact. In
2122 # the same way, we need to raise Underflow here if the result
2123 # is subnormal. (The call to _fix will take care of raising
2124 # Rounded and Subnormal, as usual.)
2125 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002126 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002127 # pad with zeros up to length context.prec+1 if necessary
2128 if len(ans._int) <= context.prec:
2129 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002130 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2131 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002132 if ans.adjusted() < context.Emin:
2133 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002134
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002135 # unlike exp, ln and log10, the power function respects the
2136 # rounding mode; no need to use ROUND_HALF_EVEN here
2137 ans = ans._fix(context)
2138 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002139
2140 def __rpow__(self, other, context=None):
2141 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002142 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002143 if other is NotImplemented:
2144 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002145 return other.__pow__(self, context=context)
2146
2147 def normalize(self, context=None):
2148 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002149
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002150 if context is None:
2151 context = getcontext()
2152
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002153 if self._is_special:
2154 ans = self._check_nans(context=context)
2155 if ans:
2156 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002157
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002158 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002159 if dup._isinfinity():
2160 return dup
2161
2162 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002163 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002164 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002165 end = len(dup._int)
2166 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002167 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002168 exp += 1
2169 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002170 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002171
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002172 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002173 """Quantize self so its exponent is the same as that of exp.
2174
2175 Similar to self._rescale(exp._exp) but with error checking.
2176 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002177 exp = _convert_other(exp, raiseit=True)
2178
2179 if context is None:
2180 context = getcontext()
2181 if rounding is None:
2182 rounding = context.rounding
2183
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002184 if self._is_special or exp._is_special:
2185 ans = self._check_nans(exp, context)
2186 if ans:
2187 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002188
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002189 if exp._isinfinity() or self._isinfinity():
2190 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002191 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002192 return context._raise_error(InvalidOperation,
2193 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002194
2195 # if we're not watching exponents, do a simple rescale
2196 if not watchexp:
2197 ans = self._rescale(exp._exp, rounding)
2198 # raise Inexact and Rounded where appropriate
2199 if ans._exp > self._exp:
2200 context._raise_error(Rounded)
2201 if ans != self:
2202 context._raise_error(Inexact)
2203 return ans
2204
2205 # exp._exp should be between Etiny and Emax
2206 if not (context.Etiny() <= exp._exp <= context.Emax):
2207 return context._raise_error(InvalidOperation,
2208 'target exponent out of bounds in quantize')
2209
2210 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002211 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002212 return ans._fix(context)
2213
2214 self_adjusted = self.adjusted()
2215 if self_adjusted > context.Emax:
2216 return context._raise_error(InvalidOperation,
2217 'exponent of quantize result too large for current context')
2218 if self_adjusted - exp._exp + 1 > context.prec:
2219 return context._raise_error(InvalidOperation,
2220 'quantize result has too many digits for current context')
2221
2222 ans = self._rescale(exp._exp, rounding)
2223 if ans.adjusted() > context.Emax:
2224 return context._raise_error(InvalidOperation,
2225 'exponent of quantize result too large for current context')
2226 if len(ans._int) > context.prec:
2227 return context._raise_error(InvalidOperation,
2228 'quantize result has too many digits for current context')
2229
2230 # raise appropriate flags
2231 if ans._exp > self._exp:
2232 context._raise_error(Rounded)
2233 if ans != self:
2234 context._raise_error(Inexact)
2235 if ans and ans.adjusted() < context.Emin:
2236 context._raise_error(Subnormal)
2237
2238 # call to fix takes care of any necessary folddown
2239 ans = ans._fix(context)
2240 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002241
2242 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002243 """Return True if self and other have the same exponent; otherwise
2244 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002245
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002246 If either operand is a special value, the following rules are used:
2247 * return True if both operands are infinities
2248 * return True if both operands are NaNs
2249 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002250 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002251 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002252 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002253 return (self.is_nan() and other.is_nan() or
2254 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002255 return self._exp == other._exp
2256
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002257 def _rescale(self, exp, rounding):
2258 """Rescale self so that the exponent is exp, either by padding with zeros
2259 or by truncating digits, using the given rounding mode.
2260
2261 Specials are returned without change. This operation is
2262 quiet: it raises no flags, and uses no information from the
2263 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002264
2265 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002266 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002267 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002268 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002269 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002270 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002271 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002272
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002273 if self._exp >= exp:
2274 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002275 return _dec_from_triple(self._sign,
2276 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002277
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002278 # too many digits; round and lose data. If self.adjusted() <
2279 # exp-1, replace self by 10**(exp-1) before rounding
2280 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002281 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002282 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002283 digits = 0
2284 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002285 changed = this_function(digits)
2286 coeff = self._int[:digits] or '0'
2287 if changed == 1:
2288 coeff = str(int(coeff)+1)
2289 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002290
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002291 def to_integral_exact(self, rounding=None, context=None):
2292 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002293
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002294 If no rounding mode is specified, take the rounding mode from
2295 the context. This method raises the Rounded and Inexact flags
2296 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002297
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002298 See also: to_integral_value, which does exactly the same as
2299 this method except that it doesn't raise Inexact or Rounded.
2300 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002301 if self._is_special:
2302 ans = self._check_nans(context=context)
2303 if ans:
2304 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002305 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002306 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002307 return Decimal(self)
2308 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002309 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002310 if context is None:
2311 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002312 if rounding is None:
2313 rounding = context.rounding
2314 context._raise_error(Rounded)
2315 ans = self._rescale(0, rounding)
2316 if ans != self:
2317 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002318 return ans
2319
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002320 def to_integral_value(self, rounding=None, context=None):
2321 """Rounds to the nearest integer, without raising inexact, rounded."""
2322 if context is None:
2323 context = getcontext()
2324 if rounding is None:
2325 rounding = context.rounding
2326 if self._is_special:
2327 ans = self._check_nans(context=context)
2328 if ans:
2329 return ans
2330 return Decimal(self)
2331 if self._exp >= 0:
2332 return Decimal(self)
2333 else:
2334 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002335
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002336 # the method name changed, but we provide also the old one, for compatibility
2337 to_integral = to_integral_value
2338
2339 def sqrt(self, context=None):
2340 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002341 if self._is_special:
2342 ans = self._check_nans(context=context)
2343 if ans:
2344 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002345
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002346 if self._isinfinity() and self._sign == 0:
2347 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002348
2349 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002350 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002351 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002352 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002353
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002354 if context is None:
2355 context = getcontext()
2356
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002357 if self._sign == 1:
2358 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2359
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002360 # At this point self represents a positive number. Let p be
2361 # the desired precision and express self in the form c*100**e
2362 # with c a positive real number and e an integer, c and e
2363 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2364 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2365 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2366 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2367 # the closest integer to sqrt(c) with the even integer chosen
2368 # in the case of a tie.
2369 #
2370 # To ensure correct rounding in all cases, we use the
2371 # following trick: we compute the square root to an extra
2372 # place (precision p+1 instead of precision p), rounding down.
2373 # Then, if the result is inexact and its last digit is 0 or 5,
2374 # we increase the last digit to 1 or 6 respectively; if it's
2375 # exact we leave the last digit alone. Now the final round to
2376 # p places (or fewer in the case of underflow) will round
2377 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002378
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002379 # use an extra digit of precision
2380 prec = context.prec+1
2381
2382 # write argument in the form c*100**e where e = self._exp//2
2383 # is the 'ideal' exponent, to be used if the square root is
2384 # exactly representable. l is the number of 'digits' of c in
2385 # base 100, so that 100**(l-1) <= c < 100**l.
2386 op = _WorkRep(self)
2387 e = op.exp >> 1
2388 if op.exp & 1:
2389 c = op.int * 10
2390 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002391 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002392 c = op.int
2393 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002394
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002395 # rescale so that c has exactly prec base 100 'digits'
2396 shift = prec-l
2397 if shift >= 0:
2398 c *= 100**shift
2399 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002400 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002401 c, remainder = divmod(c, 100**-shift)
2402 exact = not remainder
2403 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002404
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002405 # find n = floor(sqrt(c)) using Newton's method
2406 n = 10**prec
2407 while True:
2408 q = c//n
2409 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002410 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002411 else:
2412 n = n + q >> 1
2413 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002414
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002415 if exact:
2416 # result is exact; rescale to use ideal exponent e
2417 if shift >= 0:
2418 # assert n % 10**shift == 0
2419 n //= 10**shift
2420 else:
2421 n *= 10**-shift
2422 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002423 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002424 # result is not exact; fix last digit as described above
2425 if n % 5 == 0:
2426 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002427
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002428 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002429
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002430 # round, and fit to current context
2431 context = context._shallow_copy()
2432 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002433 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002434 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002435
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002436 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002437
2438 def max(self, other, context=None):
2439 """Returns the larger value.
2440
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002441 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002442 NaN (and signals if one is sNaN). Also rounds.
2443 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002444 other = _convert_other(other, raiseit=True)
2445
2446 if context is None:
2447 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002448
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002449 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002450 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002451 # number is always returned
2452 sn = self._isnan()
2453 on = other._isnan()
2454 if sn or on:
2455 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002456 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002457 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002458 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002459 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002460
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002461 c = self.__cmp__(other)
2462 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002463 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002464 # then an ordering is applied:
2465 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002466 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002467 # positive sign and min returns the operand with the negative sign
2468 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002469 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002470 # the result. This is exactly the ordering used in compare_total.
2471 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002472
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002473 if c == -1:
2474 ans = other
2475 else:
2476 ans = self
2477
Christian Heimes2c181612007-12-17 20:04:13 +00002478 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002479
2480 def min(self, other, context=None):
2481 """Returns the smaller value.
2482
Guido van Rossumd8faa362007-04-27 19:54:29 +00002483 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002484 NaN (and signals if one is sNaN). Also rounds.
2485 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002486 other = _convert_other(other, raiseit=True)
2487
2488 if context is None:
2489 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002490
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002491 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002492 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002493 # number is always returned
2494 sn = self._isnan()
2495 on = other._isnan()
2496 if sn or on:
2497 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002498 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002499 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002500 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002501 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002502
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002503 c = self.__cmp__(other)
2504 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002505 c = self.compare_total(other)
2506
2507 if c == -1:
2508 ans = self
2509 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002510 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002511
Christian Heimes2c181612007-12-17 20:04:13 +00002512 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002513
2514 def _isinteger(self):
2515 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002516 if self._is_special:
2517 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002518 if self._exp >= 0:
2519 return True
2520 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002521 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002522
2523 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002524 """Returns True if self is even. Assumes self is an integer."""
2525 if not self or self._exp > 0:
2526 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002527 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002528
2529 def adjusted(self):
2530 """Return the adjusted exponent of self"""
2531 try:
2532 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002533 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002534 except TypeError:
2535 return 0
2536
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002537 def canonical(self, context=None):
2538 """Returns the same Decimal object.
2539
2540 As we do not have different encodings for the same number, the
2541 received object already is in its canonical form.
2542 """
2543 return self
2544
2545 def compare_signal(self, other, context=None):
2546 """Compares self to the other operand numerically.
2547
2548 It's pretty much like compare(), but all NaNs signal, with signaling
2549 NaNs taking precedence over quiet NaNs.
2550 """
2551 if context is None:
2552 context = getcontext()
2553
2554 self_is_nan = self._isnan()
2555 other_is_nan = other._isnan()
2556 if self_is_nan == 2:
2557 return context._raise_error(InvalidOperation, 'sNaN',
2558 1, self)
2559 if other_is_nan == 2:
2560 return context._raise_error(InvalidOperation, 'sNaN',
2561 1, other)
2562 if self_is_nan:
2563 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2564 1, self)
2565 if other_is_nan:
2566 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2567 1, other)
2568 return self.compare(other, context=context)
2569
2570 def compare_total(self, other):
2571 """Compares self to other using the abstract representations.
2572
2573 This is not like the standard compare, which use their numerical
2574 value. Note that a total ordering is defined for all possible abstract
2575 representations.
2576 """
2577 # if one is negative and the other is positive, it's easy
2578 if self._sign and not other._sign:
2579 return Dec_n1
2580 if not self._sign and other._sign:
2581 return Dec_p1
2582 sign = self._sign
2583
2584 # let's handle both NaN types
2585 self_nan = self._isnan()
2586 other_nan = other._isnan()
2587 if self_nan or other_nan:
2588 if self_nan == other_nan:
2589 if self._int < other._int:
2590 if sign:
2591 return Dec_p1
2592 else:
2593 return Dec_n1
2594 if self._int > other._int:
2595 if sign:
2596 return Dec_n1
2597 else:
2598 return Dec_p1
2599 return Dec_0
2600
2601 if sign:
2602 if self_nan == 1:
2603 return Dec_n1
2604 if other_nan == 1:
2605 return Dec_p1
2606 if self_nan == 2:
2607 return Dec_n1
2608 if other_nan == 2:
2609 return Dec_p1
2610 else:
2611 if self_nan == 1:
2612 return Dec_p1
2613 if other_nan == 1:
2614 return Dec_n1
2615 if self_nan == 2:
2616 return Dec_p1
2617 if other_nan == 2:
2618 return Dec_n1
2619
2620 if self < other:
2621 return Dec_n1
2622 if self > other:
2623 return Dec_p1
2624
2625 if self._exp < other._exp:
2626 if sign:
2627 return Dec_p1
2628 else:
2629 return Dec_n1
2630 if self._exp > other._exp:
2631 if sign:
2632 return Dec_n1
2633 else:
2634 return Dec_p1
2635 return Dec_0
2636
2637
2638 def compare_total_mag(self, other):
2639 """Compares self to other using abstract repr., ignoring sign.
2640
2641 Like compare_total, but with operand's sign ignored and assumed to be 0.
2642 """
2643 s = self.copy_abs()
2644 o = other.copy_abs()
2645 return s.compare_total(o)
2646
2647 def copy_abs(self):
2648 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002649 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002650
2651 def copy_negate(self):
2652 """Returns a copy with the sign inverted."""
2653 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002654 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002655 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002656 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002657
2658 def copy_sign(self, other):
2659 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002660 return _dec_from_triple(other._sign, self._int,
2661 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002662
2663 def exp(self, context=None):
2664 """Returns e ** self."""
2665
2666 if context is None:
2667 context = getcontext()
2668
2669 # exp(NaN) = NaN
2670 ans = self._check_nans(context=context)
2671 if ans:
2672 return ans
2673
2674 # exp(-Infinity) = 0
2675 if self._isinfinity() == -1:
2676 return Dec_0
2677
2678 # exp(0) = 1
2679 if not self:
2680 return Dec_p1
2681
2682 # exp(Infinity) = Infinity
2683 if self._isinfinity() == 1:
2684 return Decimal(self)
2685
2686 # the result is now guaranteed to be inexact (the true
2687 # mathematical result is transcendental). There's no need to
2688 # raise Rounded and Inexact here---they'll always be raised as
2689 # a result of the call to _fix.
2690 p = context.prec
2691 adj = self.adjusted()
2692
2693 # we only need to do any computation for quite a small range
2694 # of adjusted exponents---for example, -29 <= adj <= 10 for
2695 # the default context. For smaller exponent the result is
2696 # indistinguishable from 1 at the given precision, while for
2697 # larger exponent the result either overflows or underflows.
2698 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2699 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002700 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002701 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2702 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002703 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002704 elif self._sign == 0 and adj < -p:
2705 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002706 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002707 elif self._sign == 1 and adj < -p-1:
2708 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002709 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002710 # general case
2711 else:
2712 op = _WorkRep(self)
2713 c, e = op.int, op.exp
2714 if op.sign == 1:
2715 c = -c
2716
2717 # compute correctly rounded result: increase precision by
2718 # 3 digits at a time until we get an unambiguously
2719 # roundable result
2720 extra = 3
2721 while True:
2722 coeff, exp = _dexp(c, e, p+extra)
2723 if coeff % (5*10**(len(str(coeff))-p-1)):
2724 break
2725 extra += 3
2726
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002727 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002728
2729 # at this stage, ans should round correctly with *any*
2730 # rounding mode, not just with ROUND_HALF_EVEN
2731 context = context._shallow_copy()
2732 rounding = context._set_rounding(ROUND_HALF_EVEN)
2733 ans = ans._fix(context)
2734 context.rounding = rounding
2735
2736 return ans
2737
2738 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002739 """Return True if self is canonical; otherwise return False.
2740
2741 Currently, the encoding of a Decimal instance is always
2742 canonical, so this method returns True for any Decimal.
2743 """
2744 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002745
2746 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002747 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002748
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002749 A Decimal instance is considered finite if it is neither
2750 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002751 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002752 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002753
2754 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002755 """Return True if self is infinite; otherwise return False."""
2756 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002757
2758 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002759 """Return True if self is a qNaN or sNaN; otherwise return False."""
2760 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002761
2762 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002763 """Return True if self is a normal number; otherwise return False."""
2764 if self._is_special or not self:
2765 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002766 if context is None:
2767 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002768 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002769
2770 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002771 """Return True if self is a quiet NaN; otherwise return False."""
2772 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002773
2774 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002775 """Return True if self is negative; otherwise return False."""
2776 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002777
2778 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002779 """Return True if self is a signaling NaN; otherwise return False."""
2780 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002781
2782 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002783 """Return True if self is subnormal; otherwise return False."""
2784 if self._is_special or not self:
2785 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002786 if context is None:
2787 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002788 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002789
2790 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002791 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002792 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002793
2794 def _ln_exp_bound(self):
2795 """Compute a lower bound for the adjusted exponent of self.ln().
2796 In other words, compute r such that self.ln() >= 10**r. Assumes
2797 that self is finite and positive and that self != 1.
2798 """
2799
2800 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2801 adj = self._exp + len(self._int) - 1
2802 if adj >= 1:
2803 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2804 return len(str(adj*23//10)) - 1
2805 if adj <= -2:
2806 # argument <= 0.1
2807 return len(str((-1-adj)*23//10)) - 1
2808 op = _WorkRep(self)
2809 c, e = op.int, op.exp
2810 if adj == 0:
2811 # 1 < self < 10
2812 num = str(c-10**-e)
2813 den = str(c)
2814 return len(num) - len(den) - (num < den)
2815 # adj == -1, 0.1 <= self < 1
2816 return e + len(str(10**-e - c)) - 1
2817
2818
2819 def ln(self, context=None):
2820 """Returns the natural (base e) logarithm of self."""
2821
2822 if context is None:
2823 context = getcontext()
2824
2825 # ln(NaN) = NaN
2826 ans = self._check_nans(context=context)
2827 if ans:
2828 return ans
2829
2830 # ln(0.0) == -Infinity
2831 if not self:
2832 return negInf
2833
2834 # ln(Infinity) = Infinity
2835 if self._isinfinity() == 1:
2836 return Inf
2837
2838 # ln(1.0) == 0.0
2839 if self == Dec_p1:
2840 return Dec_0
2841
2842 # ln(negative) raises InvalidOperation
2843 if self._sign == 1:
2844 return context._raise_error(InvalidOperation,
2845 'ln of a negative value')
2846
2847 # result is irrational, so necessarily inexact
2848 op = _WorkRep(self)
2849 c, e = op.int, op.exp
2850 p = context.prec
2851
2852 # correctly rounded result: repeatedly increase precision by 3
2853 # until we get an unambiguously roundable result
2854 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2855 while True:
2856 coeff = _dlog(c, e, places)
2857 # assert len(str(abs(coeff)))-p >= 1
2858 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2859 break
2860 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002861 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002862
2863 context = context._shallow_copy()
2864 rounding = context._set_rounding(ROUND_HALF_EVEN)
2865 ans = ans._fix(context)
2866 context.rounding = rounding
2867 return ans
2868
2869 def _log10_exp_bound(self):
2870 """Compute a lower bound for the adjusted exponent of self.log10().
2871 In other words, find r such that self.log10() >= 10**r.
2872 Assumes that self is finite and positive and that self != 1.
2873 """
2874
2875 # For x >= 10 or x < 0.1 we only need a bound on the integer
2876 # part of log10(self), and this comes directly from the
2877 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2878 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2879 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2880
2881 adj = self._exp + len(self._int) - 1
2882 if adj >= 1:
2883 # self >= 10
2884 return len(str(adj))-1
2885 if adj <= -2:
2886 # self < 0.1
2887 return len(str(-1-adj))-1
2888 op = _WorkRep(self)
2889 c, e = op.int, op.exp
2890 if adj == 0:
2891 # 1 < self < 10
2892 num = str(c-10**-e)
2893 den = str(231*c)
2894 return len(num) - len(den) - (num < den) + 2
2895 # adj == -1, 0.1 <= self < 1
2896 num = str(10**-e-c)
2897 return len(num) + e - (num < "231") - 1
2898
2899 def log10(self, context=None):
2900 """Returns the base 10 logarithm of self."""
2901
2902 if context is None:
2903 context = getcontext()
2904
2905 # log10(NaN) = NaN
2906 ans = self._check_nans(context=context)
2907 if ans:
2908 return ans
2909
2910 # log10(0.0) == -Infinity
2911 if not self:
2912 return negInf
2913
2914 # log10(Infinity) = Infinity
2915 if self._isinfinity() == 1:
2916 return Inf
2917
2918 # log10(negative or -Infinity) raises InvalidOperation
2919 if self._sign == 1:
2920 return context._raise_error(InvalidOperation,
2921 'log10 of a negative value')
2922
2923 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002924 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002925 # answer may need rounding
2926 ans = Decimal(self._exp + len(self._int) - 1)
2927 else:
2928 # result is irrational, so necessarily inexact
2929 op = _WorkRep(self)
2930 c, e = op.int, op.exp
2931 p = context.prec
2932
2933 # correctly rounded result: repeatedly increase precision
2934 # until result is unambiguously roundable
2935 places = p-self._log10_exp_bound()+2
2936 while True:
2937 coeff = _dlog10(c, e, places)
2938 # assert len(str(abs(coeff)))-p >= 1
2939 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2940 break
2941 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002942 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002943
2944 context = context._shallow_copy()
2945 rounding = context._set_rounding(ROUND_HALF_EVEN)
2946 ans = ans._fix(context)
2947 context.rounding = rounding
2948 return ans
2949
2950 def logb(self, context=None):
2951 """ Returns the exponent of the magnitude of self's MSD.
2952
2953 The result is the integer which is the exponent of the magnitude
2954 of the most significant digit of self (as though it were truncated
2955 to a single digit while maintaining the value of that digit and
2956 without limiting the resulting exponent).
2957 """
2958 # logb(NaN) = NaN
2959 ans = self._check_nans(context=context)
2960 if ans:
2961 return ans
2962
2963 if context is None:
2964 context = getcontext()
2965
2966 # logb(+/-Inf) = +Inf
2967 if self._isinfinity():
2968 return Inf
2969
2970 # logb(0) = -Inf, DivisionByZero
2971 if not self:
2972 return context._raise_error(DivisionByZero, 'logb(0)', 1)
2973
2974 # otherwise, simply return the adjusted exponent of self, as a
2975 # Decimal. Note that no attempt is made to fit the result
2976 # into the current context.
2977 return Decimal(self.adjusted())
2978
2979 def _islogical(self):
2980 """Return True if self is a logical operand.
2981
2982 For being logical, it must be a finite numbers with a sign of 0,
2983 an exponent of 0, and a coefficient whose digits must all be
2984 either 0 or 1.
2985 """
2986 if self._sign != 0 or self._exp != 0:
2987 return False
2988 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002989 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002990 return False
2991 return True
2992
2993 def _fill_logical(self, context, opa, opb):
2994 dif = context.prec - len(opa)
2995 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002996 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002997 elif dif < 0:
2998 opa = opa[-context.prec:]
2999 dif = context.prec - len(opb)
3000 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003001 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003002 elif dif < 0:
3003 opb = opb[-context.prec:]
3004 return opa, opb
3005
3006 def logical_and(self, other, context=None):
3007 """Applies an 'and' operation between self and other's digits."""
3008 if context is None:
3009 context = getcontext()
3010 if not self._islogical() or not other._islogical():
3011 return context._raise_error(InvalidOperation)
3012
3013 # fill to context.prec
3014 (opa, opb) = self._fill_logical(context, self._int, other._int)
3015
3016 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003017 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3018 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003019
3020 def logical_invert(self, context=None):
3021 """Invert all its digits."""
3022 if context is None:
3023 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003024 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3025 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003026
3027 def logical_or(self, other, context=None):
3028 """Applies an 'or' operation between self and other's digits."""
3029 if context is None:
3030 context = getcontext()
3031 if not self._islogical() or not other._islogical():
3032 return context._raise_error(InvalidOperation)
3033
3034 # fill to context.prec
3035 (opa, opb) = self._fill_logical(context, self._int, other._int)
3036
3037 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003038 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3039 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003040
3041 def logical_xor(self, other, context=None):
3042 """Applies an 'xor' operation between self and other's digits."""
3043 if context is None:
3044 context = getcontext()
3045 if not self._islogical() or not other._islogical():
3046 return context._raise_error(InvalidOperation)
3047
3048 # fill to context.prec
3049 (opa, opb) = self._fill_logical(context, self._int, other._int)
3050
3051 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003052 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3053 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003054
3055 def max_mag(self, other, context=None):
3056 """Compares the values numerically with their sign ignored."""
3057 other = _convert_other(other, raiseit=True)
3058
3059 if context is None:
3060 context = getcontext()
3061
3062 if self._is_special or other._is_special:
3063 # If one operand is a quiet NaN and the other is number, then the
3064 # number is always returned
3065 sn = self._isnan()
3066 on = other._isnan()
3067 if sn or on:
3068 if on == 1 and sn != 2:
3069 return self._fix_nan(context)
3070 if sn == 1 and on != 2:
3071 return other._fix_nan(context)
3072 return self._check_nans(other, context)
3073
3074 c = self.copy_abs().__cmp__(other.copy_abs())
3075 if c == 0:
3076 c = self.compare_total(other)
3077
3078 if c == -1:
3079 ans = other
3080 else:
3081 ans = self
3082
Christian Heimes2c181612007-12-17 20:04:13 +00003083 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003084
3085 def min_mag(self, other, context=None):
3086 """Compares the values numerically with their sign ignored."""
3087 other = _convert_other(other, raiseit=True)
3088
3089 if context is None:
3090 context = getcontext()
3091
3092 if self._is_special or other._is_special:
3093 # If one operand is a quiet NaN and the other is number, then the
3094 # number is always returned
3095 sn = self._isnan()
3096 on = other._isnan()
3097 if sn or on:
3098 if on == 1 and sn != 2:
3099 return self._fix_nan(context)
3100 if sn == 1 and on != 2:
3101 return other._fix_nan(context)
3102 return self._check_nans(other, context)
3103
3104 c = self.copy_abs().__cmp__(other.copy_abs())
3105 if c == 0:
3106 c = self.compare_total(other)
3107
3108 if c == -1:
3109 ans = self
3110 else:
3111 ans = other
3112
Christian Heimes2c181612007-12-17 20:04:13 +00003113 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003114
3115 def next_minus(self, context=None):
3116 """Returns the largest representable number smaller than itself."""
3117 if context is None:
3118 context = getcontext()
3119
3120 ans = self._check_nans(context=context)
3121 if ans:
3122 return ans
3123
3124 if self._isinfinity() == -1:
3125 return negInf
3126 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003127 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003128
3129 context = context.copy()
3130 context._set_rounding(ROUND_FLOOR)
3131 context._ignore_all_flags()
3132 new_self = self._fix(context)
3133 if new_self != self:
3134 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003135 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3136 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003137
3138 def next_plus(self, context=None):
3139 """Returns the smallest representable number larger than itself."""
3140 if context is None:
3141 context = getcontext()
3142
3143 ans = self._check_nans(context=context)
3144 if ans:
3145 return ans
3146
3147 if self._isinfinity() == 1:
3148 return Inf
3149 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003150 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003151
3152 context = context.copy()
3153 context._set_rounding(ROUND_CEILING)
3154 context._ignore_all_flags()
3155 new_self = self._fix(context)
3156 if new_self != self:
3157 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003158 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3159 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003160
3161 def next_toward(self, other, context=None):
3162 """Returns the number closest to self, in the direction towards other.
3163
3164 The result is the closest representable number to self
3165 (excluding self) that is in the direction towards other,
3166 unless both have the same value. If the two operands are
3167 numerically equal, then the result is a copy of self with the
3168 sign set to be the same as the sign of other.
3169 """
3170 other = _convert_other(other, raiseit=True)
3171
3172 if context is None:
3173 context = getcontext()
3174
3175 ans = self._check_nans(other, context)
3176 if ans:
3177 return ans
3178
3179 comparison = self.__cmp__(other)
3180 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003181 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003182
3183 if comparison == -1:
3184 ans = self.next_plus(context)
3185 else: # comparison == 1
3186 ans = self.next_minus(context)
3187
3188 # decide which flags to raise using value of ans
3189 if ans._isinfinity():
3190 context._raise_error(Overflow,
3191 'Infinite result from next_toward',
3192 ans._sign)
3193 context._raise_error(Rounded)
3194 context._raise_error(Inexact)
3195 elif ans.adjusted() < context.Emin:
3196 context._raise_error(Underflow)
3197 context._raise_error(Subnormal)
3198 context._raise_error(Rounded)
3199 context._raise_error(Inexact)
3200 # if precision == 1 then we don't raise Clamped for a
3201 # result 0E-Etiny.
3202 if not ans:
3203 context._raise_error(Clamped)
3204
3205 return ans
3206
3207 def number_class(self, context=None):
3208 """Returns an indication of the class of self.
3209
3210 The class is one of the following strings:
3211 -sNaN
3212 -NaN
3213 -Infinity
3214 -Normal
3215 -Subnormal
3216 -Zero
3217 +Zero
3218 +Subnormal
3219 +Normal
3220 +Infinity
3221 """
3222 if self.is_snan():
3223 return "sNaN"
3224 if self.is_qnan():
3225 return "NaN"
3226 inf = self._isinfinity()
3227 if inf == 1:
3228 return "+Infinity"
3229 if inf == -1:
3230 return "-Infinity"
3231 if self.is_zero():
3232 if self._sign:
3233 return "-Zero"
3234 else:
3235 return "+Zero"
3236 if context is None:
3237 context = getcontext()
3238 if self.is_subnormal(context=context):
3239 if self._sign:
3240 return "-Subnormal"
3241 else:
3242 return "+Subnormal"
3243 # just a normal, regular, boring number, :)
3244 if self._sign:
3245 return "-Normal"
3246 else:
3247 return "+Normal"
3248
3249 def radix(self):
3250 """Just returns 10, as this is Decimal, :)"""
3251 return Decimal(10)
3252
3253 def rotate(self, other, context=None):
3254 """Returns a rotated copy of self, value-of-other times."""
3255 if context is None:
3256 context = getcontext()
3257
3258 ans = self._check_nans(other, context)
3259 if ans:
3260 return ans
3261
3262 if other._exp != 0:
3263 return context._raise_error(InvalidOperation)
3264 if not (-context.prec <= int(other) <= context.prec):
3265 return context._raise_error(InvalidOperation)
3266
3267 if self._isinfinity():
3268 return Decimal(self)
3269
3270 # get values, pad if necessary
3271 torot = int(other)
3272 rotdig = self._int
3273 topad = context.prec - len(rotdig)
3274 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003275 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003276
3277 # let's rotate!
3278 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003279 return _dec_from_triple(self._sign,
3280 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003281
3282 def scaleb (self, other, context=None):
3283 """Returns self operand after adding the second value to its exp."""
3284 if context is None:
3285 context = getcontext()
3286
3287 ans = self._check_nans(other, context)
3288 if ans:
3289 return ans
3290
3291 if other._exp != 0:
3292 return context._raise_error(InvalidOperation)
3293 liminf = -2 * (context.Emax + context.prec)
3294 limsup = 2 * (context.Emax + context.prec)
3295 if not (liminf <= int(other) <= limsup):
3296 return context._raise_error(InvalidOperation)
3297
3298 if self._isinfinity():
3299 return Decimal(self)
3300
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003301 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003302 d = d._fix(context)
3303 return d
3304
3305 def shift(self, other, context=None):
3306 """Returns a shifted copy of self, value-of-other times."""
3307 if context is None:
3308 context = getcontext()
3309
3310 ans = self._check_nans(other, context)
3311 if ans:
3312 return ans
3313
3314 if other._exp != 0:
3315 return context._raise_error(InvalidOperation)
3316 if not (-context.prec <= int(other) <= context.prec):
3317 return context._raise_error(InvalidOperation)
3318
3319 if self._isinfinity():
3320 return Decimal(self)
3321
3322 # get values, pad if necessary
3323 torot = int(other)
3324 if not torot:
3325 return Decimal(self)
3326 rotdig = self._int
3327 topad = context.prec - len(rotdig)
3328 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003329 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003330
3331 # let's shift!
3332 if torot < 0:
3333 rotated = rotdig[:torot]
3334 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003335 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003336 rotated = rotated[-context.prec:]
3337
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003338 return _dec_from_triple(self._sign,
3339 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003340
Guido van Rossumd8faa362007-04-27 19:54:29 +00003341 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003342 def __reduce__(self):
3343 return (self.__class__, (str(self),))
3344
3345 def __copy__(self):
3346 if type(self) == Decimal:
3347 return self # I'm immutable; therefore I am my own clone
3348 return self.__class__(str(self))
3349
3350 def __deepcopy__(self, memo):
3351 if type(self) == Decimal:
3352 return self # My components are also immutable
3353 return self.__class__(str(self))
3354
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003355def _dec_from_triple(sign, coefficient, exponent, special=False):
3356 """Create a decimal instance directly, without any validation,
3357 normalization (e.g. removal of leading zeros) or argument
3358 conversion.
3359
3360 This function is for *internal use only*.
3361 """
3362
3363 self = object.__new__(Decimal)
3364 self._sign = sign
3365 self._int = coefficient
3366 self._exp = exponent
3367 self._is_special = special
3368
3369 return self
3370
Guido van Rossumd8faa362007-04-27 19:54:29 +00003371##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003372
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003373
3374# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003375rounding_functions = [name for name in Decimal.__dict__.keys()
3376 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003377for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003378 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003379 globalname = name[1:].upper()
3380 val = globals()[globalname]
3381 Decimal._pick_rounding_function[val] = name
3382
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003383del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003384
Thomas Wouters89f507f2006-12-13 04:49:30 +00003385class _ContextManager(object):
3386 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003387
Thomas Wouters89f507f2006-12-13 04:49:30 +00003388 Sets a copy of the supplied context in __enter__() and restores
3389 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003390 """
3391 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003392 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003393 def __enter__(self):
3394 self.saved_context = getcontext()
3395 setcontext(self.new_context)
3396 return self.new_context
3397 def __exit__(self, t, v, tb):
3398 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003399
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003400class Context(object):
3401 """Contains the context for a Decimal instance.
3402
3403 Contains:
3404 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003405 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003406 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003407 raised when it is caused. Otherwise, a value is
3408 substituted in.
3409 flags - When an exception is caused, flags[exception] is incremented.
3410 (Whether or not the trap_enabler is set)
3411 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003412 Emin - Minimum exponent
3413 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003414 capitals - If 1, 1*10^1 is printed as 1E+1.
3415 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003416 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003417 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003418
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003419 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003420 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003421 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003422 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003423 _ignored_flags=None):
3424 if flags is None:
3425 flags = []
3426 if _ignored_flags is None:
3427 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003428 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003429 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003430 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003431 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003432 for name, val in locals().items():
3433 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003434 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003435 else:
3436 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003437 del self.self
3438
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003439 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003440 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003441 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003442 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3443 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3444 % vars(self))
3445 names = [f.__name__ for f, v in self.flags.items() if v]
3446 s.append('flags=[' + ', '.join(names) + ']')
3447 names = [t.__name__ for t, v in self.traps.items() if v]
3448 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003449 return ', '.join(s) + ')'
3450
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003451 def clear_flags(self):
3452 """Reset all flags to zero"""
3453 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003454 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003455
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003456 def _shallow_copy(self):
3457 """Returns a shallow copy from self."""
Christian Heimes2c181612007-12-17 20:04:13 +00003458 nc = Context(self.prec, self.rounding, self.traps,
3459 self.flags, self.Emin, self.Emax,
3460 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003461 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003462
3463 def copy(self):
3464 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003465 nc = Context(self.prec, self.rounding, self.traps.copy(),
Christian Heimes2c181612007-12-17 20:04:13 +00003466 self.flags.copy(), self.Emin, self.Emax,
3467 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003468 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003469 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003470
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003471 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003472 """Handles an error
3473
3474 If the flag is in _ignored_flags, returns the default response.
3475 Otherwise, it increments the flag, then, if the corresponding
3476 trap_enabler is set, it reaises the exception. Otherwise, it returns
3477 the default value after incrementing the flag.
3478 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003479 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003480 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003481 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003482 return error().handle(self, *args)
3483
3484 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003485 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003486 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003487 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003488
3489 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003490 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003491 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003492
3493 def _ignore_all_flags(self):
3494 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003495 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003496
3497 def _ignore_flags(self, *flags):
3498 """Ignore the flags, if they are raised"""
3499 # Do not mutate-- This way, copies of a context leave the original
3500 # alone.
3501 self._ignored_flags = (self._ignored_flags + list(flags))
3502 return list(flags)
3503
3504 def _regard_flags(self, *flags):
3505 """Stop ignoring the flags, if they are raised"""
3506 if flags and isinstance(flags[0], (tuple,list)):
3507 flags = flags[0]
3508 for flag in flags:
3509 self._ignored_flags.remove(flag)
3510
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003511 def __hash__(self):
3512 """A Context cannot be hashed."""
3513 # We inherit object.__hash__, so we must deny this explicitly
Guido van Rossumd8faa362007-04-27 19:54:29 +00003514 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003515
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003516 def Etiny(self):
3517 """Returns Etiny (= Emin - prec + 1)"""
3518 return int(self.Emin - self.prec + 1)
3519
3520 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003521 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003522 return int(self.Emax - self.prec + 1)
3523
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003524 def _set_rounding(self, type):
3525 """Sets the rounding type.
3526
3527 Sets the rounding type, and returns the current (previous)
3528 rounding type. Often used like:
3529
3530 context = context.copy()
3531 # so you don't change the calling context
3532 # if an error occurs in the middle.
3533 rounding = context._set_rounding(ROUND_UP)
3534 val = self.__sub__(other, context=context)
3535 context._set_rounding(rounding)
3536
3537 This will make it round up for that operation.
3538 """
3539 rounding = self.rounding
3540 self.rounding= type
3541 return rounding
3542
Raymond Hettingerfed52962004-07-14 15:41:57 +00003543 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003544 """Creates a new Decimal instance but using self as context."""
3545 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003546 if d._isnan() and len(d._int) > self.prec - self._clamp:
3547 return self._raise_error(ConversionSyntax,
3548 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003549 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003550
Guido van Rossumd8faa362007-04-27 19:54:29 +00003551 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003552 def abs(self, a):
3553 """Returns the absolute value of the operand.
3554
3555 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003556 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003557 the plus operation on the operand.
3558
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003559 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003560 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003561 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003562 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003563 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003564 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003565 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003566 Decimal("101.5")
3567 """
3568 return a.__abs__(context=self)
3569
3570 def add(self, a, b):
3571 """Return the sum of the two operands.
3572
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003573 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003574 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003575 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003576 Decimal("1.02E+4")
3577 """
3578 return a.__add__(b, context=self)
3579
3580 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003581 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003582
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003583 def canonical(self, a):
3584 """Returns the same Decimal object.
3585
3586 As we do not have different encodings for the same number, the
3587 received object already is in its canonical form.
3588
3589 >>> ExtendedContext.canonical(Decimal('2.50'))
3590 Decimal("2.50")
3591 """
3592 return a.canonical(context=self)
3593
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003594 def compare(self, a, b):
3595 """Compares values numerically.
3596
3597 If the signs of the operands differ, a value representing each operand
3598 ('-1' if the operand is less than zero, '0' if the operand is zero or
3599 negative zero, or '1' if the operand is greater than zero) is used in
3600 place of that operand for the comparison instead of the actual
3601 operand.
3602
3603 The comparison is then effected by subtracting the second operand from
3604 the first and then returning a value according to the result of the
3605 subtraction: '-1' if the result is less than zero, '0' if the result is
3606 zero or negative zero, or '1' if the result is greater than zero.
3607
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003608 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003609 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003610 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003611 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003612 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003613 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003614 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003615 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003616 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003617 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003618 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003619 Decimal("-1")
3620 """
3621 return a.compare(b, context=self)
3622
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003623 def compare_signal(self, a, b):
3624 """Compares the values of the two operands numerically.
3625
3626 It's pretty much like compare(), but all NaNs signal, with signaling
3627 NaNs taking precedence over quiet NaNs.
3628
3629 >>> c = ExtendedContext
3630 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3631 Decimal("-1")
3632 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3633 Decimal("0")
3634 >>> c.flags[InvalidOperation] = 0
3635 >>> print(c.flags[InvalidOperation])
3636 0
3637 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3638 Decimal("NaN")
3639 >>> print(c.flags[InvalidOperation])
3640 1
3641 >>> c.flags[InvalidOperation] = 0
3642 >>> print(c.flags[InvalidOperation])
3643 0
3644 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3645 Decimal("NaN")
3646 >>> print(c.flags[InvalidOperation])
3647 1
3648 """
3649 return a.compare_signal(b, context=self)
3650
3651 def compare_total(self, a, b):
3652 """Compares two operands using their abstract representation.
3653
3654 This is not like the standard compare, which use their numerical
3655 value. Note that a total ordering is defined for all possible abstract
3656 representations.
3657
3658 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3659 Decimal("-1")
3660 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3661 Decimal("-1")
3662 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3663 Decimal("-1")
3664 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3665 Decimal("0")
3666 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3667 Decimal("1")
3668 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3669 Decimal("-1")
3670 """
3671 return a.compare_total(b)
3672
3673 def compare_total_mag(self, a, b):
3674 """Compares two operands using their abstract representation ignoring sign.
3675
3676 Like compare_total, but with operand's sign ignored and assumed to be 0.
3677 """
3678 return a.compare_total_mag(b)
3679
3680 def copy_abs(self, a):
3681 """Returns a copy of the operand with the sign set to 0.
3682
3683 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3684 Decimal("2.1")
3685 >>> ExtendedContext.copy_abs(Decimal('-100'))
3686 Decimal("100")
3687 """
3688 return a.copy_abs()
3689
3690 def copy_decimal(self, a):
3691 """Returns a copy of the decimal objet.
3692
3693 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3694 Decimal("2.1")
3695 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3696 Decimal("-1.00")
3697 """
3698 return Decimal(a)
3699
3700 def copy_negate(self, a):
3701 """Returns a copy of the operand with the sign inverted.
3702
3703 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3704 Decimal("-101.5")
3705 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3706 Decimal("101.5")
3707 """
3708 return a.copy_negate()
3709
3710 def copy_sign(self, a, b):
3711 """Copies the second operand's sign to the first one.
3712
3713 In detail, it returns a copy of the first operand with the sign
3714 equal to the sign of the second operand.
3715
3716 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3717 Decimal("1.50")
3718 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3719 Decimal("1.50")
3720 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3721 Decimal("-1.50")
3722 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3723 Decimal("-1.50")
3724 """
3725 return a.copy_sign(b)
3726
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003727 def divide(self, a, b):
3728 """Decimal division in a specified context.
3729
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003730 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003731 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003732 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003733 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003734 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003735 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003736 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003737 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003738 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003739 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003740 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003741 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003742 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003743 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003744 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003745 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003746 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003747 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003748 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003749 Decimal("1.20E+6")
3750 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003751 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003752
3753 def divide_int(self, a, b):
3754 """Divides two numbers and returns the integer part of the result.
3755
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003756 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003757 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003758 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003759 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003760 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003761 Decimal("3")
3762 """
3763 return a.__floordiv__(b, context=self)
3764
3765 def divmod(self, a, b):
3766 return a.__divmod__(b, context=self)
3767
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003768 def exp(self, a):
3769 """Returns e ** a.
3770
3771 >>> c = ExtendedContext.copy()
3772 >>> c.Emin = -999
3773 >>> c.Emax = 999
3774 >>> c.exp(Decimal('-Infinity'))
3775 Decimal("0")
3776 >>> c.exp(Decimal('-1'))
3777 Decimal("0.367879441")
3778 >>> c.exp(Decimal('0'))
3779 Decimal("1")
3780 >>> c.exp(Decimal('1'))
3781 Decimal("2.71828183")
3782 >>> c.exp(Decimal('0.693147181'))
3783 Decimal("2.00000000")
3784 >>> c.exp(Decimal('+Infinity'))
3785 Decimal("Infinity")
3786 """
3787 return a.exp(context=self)
3788
3789 def fma(self, a, b, c):
3790 """Returns a multiplied by b, plus c.
3791
3792 The first two operands are multiplied together, using multiply,
3793 the third operand is then added to the result of that
3794 multiplication, using add, all with only one final rounding.
3795
3796 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3797 Decimal("22")
3798 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3799 Decimal("-8")
3800 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3801 Decimal("1.38435736E+12")
3802 """
3803 return a.fma(b, c, context=self)
3804
3805 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003806 """Return True if the operand is canonical; otherwise return False.
3807
3808 Currently, the encoding of a Decimal instance is always
3809 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003810
3811 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003812 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003813 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003814 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003815
3816 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003817 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003818
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003819 A Decimal instance is considered finite if it is neither
3820 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003821
3822 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003823 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003824 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003825 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003826 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003827 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003828 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003829 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003830 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003831 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003832 """
3833 return a.is_finite()
3834
3835 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003836 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003837
3838 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003839 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003840 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003841 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003842 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003843 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003844 """
3845 return a.is_infinite()
3846
3847 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003848 """Return True if the operand is a qNaN or sNaN;
3849 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003850
3851 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003852 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003853 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003854 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003855 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003856 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003857 """
3858 return a.is_nan()
3859
3860 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003861 """Return True if the operand is a normal number;
3862 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003863
3864 >>> c = ExtendedContext.copy()
3865 >>> c.Emin = -999
3866 >>> c.Emax = 999
3867 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003868 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003869 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003870 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003871 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003872 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003873 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003874 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003875 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003876 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003877 """
3878 return a.is_normal(context=self)
3879
3880 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003881 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003882
3883 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003884 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003885 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003886 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003887 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003888 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003889 """
3890 return a.is_qnan()
3891
3892 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003893 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003894
3895 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003896 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003897 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003898 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003899 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003900 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003901 """
3902 return a.is_signed()
3903
3904 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003905 """Return True if the operand is a signaling NaN;
3906 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003907
3908 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003909 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003910 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003911 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003912 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003913 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003914 """
3915 return a.is_snan()
3916
3917 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003918 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003919
3920 >>> c = ExtendedContext.copy()
3921 >>> c.Emin = -999
3922 >>> c.Emax = 999
3923 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003924 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003925 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003926 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003927 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003928 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003929 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003930 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003931 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003932 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003933 """
3934 return a.is_subnormal(context=self)
3935
3936 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003937 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003938
3939 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003940 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003941 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003942 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003943 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003944 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003945 """
3946 return a.is_zero()
3947
3948 def ln(self, a):
3949 """Returns the natural (base e) logarithm of the operand.
3950
3951 >>> c = ExtendedContext.copy()
3952 >>> c.Emin = -999
3953 >>> c.Emax = 999
3954 >>> c.ln(Decimal('0'))
3955 Decimal("-Infinity")
3956 >>> c.ln(Decimal('1.000'))
3957 Decimal("0")
3958 >>> c.ln(Decimal('2.71828183'))
3959 Decimal("1.00000000")
3960 >>> c.ln(Decimal('10'))
3961 Decimal("2.30258509")
3962 >>> c.ln(Decimal('+Infinity'))
3963 Decimal("Infinity")
3964 """
3965 return a.ln(context=self)
3966
3967 def log10(self, a):
3968 """Returns the base 10 logarithm of the operand.
3969
3970 >>> c = ExtendedContext.copy()
3971 >>> c.Emin = -999
3972 >>> c.Emax = 999
3973 >>> c.log10(Decimal('0'))
3974 Decimal("-Infinity")
3975 >>> c.log10(Decimal('0.001'))
3976 Decimal("-3")
3977 >>> c.log10(Decimal('1.000'))
3978 Decimal("0")
3979 >>> c.log10(Decimal('2'))
3980 Decimal("0.301029996")
3981 >>> c.log10(Decimal('10'))
3982 Decimal("1")
3983 >>> c.log10(Decimal('70'))
3984 Decimal("1.84509804")
3985 >>> c.log10(Decimal('+Infinity'))
3986 Decimal("Infinity")
3987 """
3988 return a.log10(context=self)
3989
3990 def logb(self, a):
3991 """ Returns the exponent of the magnitude of the operand's MSD.
3992
3993 The result is the integer which is the exponent of the magnitude
3994 of the most significant digit of the operand (as though the
3995 operand were truncated to a single digit while maintaining the
3996 value of that digit and without limiting the resulting exponent).
3997
3998 >>> ExtendedContext.logb(Decimal('250'))
3999 Decimal("2")
4000 >>> ExtendedContext.logb(Decimal('2.50'))
4001 Decimal("0")
4002 >>> ExtendedContext.logb(Decimal('0.03'))
4003 Decimal("-2")
4004 >>> ExtendedContext.logb(Decimal('0'))
4005 Decimal("-Infinity")
4006 """
4007 return a.logb(context=self)
4008
4009 def logical_and(self, a, b):
4010 """Applies the logical operation 'and' between each operand's digits.
4011
4012 The operands must be both logical numbers.
4013
4014 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4015 Decimal("0")
4016 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4017 Decimal("0")
4018 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4019 Decimal("0")
4020 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4021 Decimal("1")
4022 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4023 Decimal("1000")
4024 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4025 Decimal("10")
4026 """
4027 return a.logical_and(b, context=self)
4028
4029 def logical_invert(self, a):
4030 """Invert all the digits in the operand.
4031
4032 The operand must be a logical number.
4033
4034 >>> ExtendedContext.logical_invert(Decimal('0'))
4035 Decimal("111111111")
4036 >>> ExtendedContext.logical_invert(Decimal('1'))
4037 Decimal("111111110")
4038 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4039 Decimal("0")
4040 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4041 Decimal("10101010")
4042 """
4043 return a.logical_invert(context=self)
4044
4045 def logical_or(self, a, b):
4046 """Applies the logical operation 'or' between each operand's digits.
4047
4048 The operands must be both logical numbers.
4049
4050 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4051 Decimal("0")
4052 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4053 Decimal("1")
4054 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4055 Decimal("1")
4056 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4057 Decimal("1")
4058 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4059 Decimal("1110")
4060 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4061 Decimal("1110")
4062 """
4063 return a.logical_or(b, context=self)
4064
4065 def logical_xor(self, a, b):
4066 """Applies the logical operation 'xor' between each operand's digits.
4067
4068 The operands must be both logical numbers.
4069
4070 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4071 Decimal("0")
4072 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4073 Decimal("1")
4074 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4075 Decimal("1")
4076 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4077 Decimal("0")
4078 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4079 Decimal("110")
4080 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4081 Decimal("1101")
4082 """
4083 return a.logical_xor(b, context=self)
4084
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004085 def max(self, a,b):
4086 """max compares two values numerically and returns the maximum.
4087
4088 If either operand is a NaN then the general rules apply.
4089 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004090 operation. If they are numerically equal then the left-hand operand
4091 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004092 infinity) of the two operands is chosen as the result.
4093
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004094 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004095 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004096 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004097 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004098 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004099 Decimal("1")
4100 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4101 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004102 """
4103 return a.max(b, context=self)
4104
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004105 def max_mag(self, a, b):
4106 """Compares the values numerically with their sign ignored."""
4107 return a.max_mag(b, context=self)
4108
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004109 def min(self, a,b):
4110 """min compares two values numerically and returns the minimum.
4111
4112 If either operand is a NaN then the general rules apply.
4113 Otherwise, the operands are compared as as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004114 operation. If they are numerically equal then the left-hand operand
4115 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004116 infinity) of the two operands is chosen as the result.
4117
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004118 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004119 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004120 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004121 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004122 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004123 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004124 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4125 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004126 """
4127 return a.min(b, context=self)
4128
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004129 def min_mag(self, a, b):
4130 """Compares the values numerically with their sign ignored."""
4131 return a.min_mag(b, context=self)
4132
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004133 def minus(self, a):
4134 """Minus corresponds to unary prefix minus in Python.
4135
4136 The operation is evaluated using the same rules as subtract; the
4137 operation minus(a) is calculated as subtract('0', a) where the '0'
4138 has the same exponent as the operand.
4139
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004140 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004141 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004142 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004143 Decimal("1.3")
4144 """
4145 return a.__neg__(context=self)
4146
4147 def multiply(self, a, b):
4148 """multiply multiplies two operands.
4149
4150 If either operand is a special value then the general rules apply.
4151 Otherwise, the operands are multiplied together ('long multiplication'),
4152 resulting in a number which may be as long as the sum of the lengths
4153 of the two operands.
4154
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004155 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004156 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004157 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004158 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004159 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004160 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004161 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004162 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004163 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004164 Decimal("4.28135971E+11")
4165 """
4166 return a.__mul__(b, context=self)
4167
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004168 def next_minus(self, a):
4169 """Returns the largest representable number smaller than a.
4170
4171 >>> c = ExtendedContext.copy()
4172 >>> c.Emin = -999
4173 >>> c.Emax = 999
4174 >>> ExtendedContext.next_minus(Decimal('1'))
4175 Decimal("0.999999999")
4176 >>> c.next_minus(Decimal('1E-1007'))
4177 Decimal("0E-1007")
4178 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4179 Decimal("-1.00000004")
4180 >>> c.next_minus(Decimal('Infinity'))
4181 Decimal("9.99999999E+999")
4182 """
4183 return a.next_minus(context=self)
4184
4185 def next_plus(self, a):
4186 """Returns the smallest representable number larger than a.
4187
4188 >>> c = ExtendedContext.copy()
4189 >>> c.Emin = -999
4190 >>> c.Emax = 999
4191 >>> ExtendedContext.next_plus(Decimal('1'))
4192 Decimal("1.00000001")
4193 >>> c.next_plus(Decimal('-1E-1007'))
4194 Decimal("-0E-1007")
4195 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4196 Decimal("-1.00000002")
4197 >>> c.next_plus(Decimal('-Infinity'))
4198 Decimal("-9.99999999E+999")
4199 """
4200 return a.next_plus(context=self)
4201
4202 def next_toward(self, a, b):
4203 """Returns the number closest to a, in direction towards b.
4204
4205 The result is the closest representable number from the first
4206 operand (but not the first operand) that is in the direction
4207 towards the second operand, unless the operands have the same
4208 value.
4209
4210 >>> c = ExtendedContext.copy()
4211 >>> c.Emin = -999
4212 >>> c.Emax = 999
4213 >>> c.next_toward(Decimal('1'), Decimal('2'))
4214 Decimal("1.00000001")
4215 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4216 Decimal("-0E-1007")
4217 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4218 Decimal("-1.00000002")
4219 >>> c.next_toward(Decimal('1'), Decimal('0'))
4220 Decimal("0.999999999")
4221 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4222 Decimal("0E-1007")
4223 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4224 Decimal("-1.00000004")
4225 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4226 Decimal("-0.00")
4227 """
4228 return a.next_toward(b, context=self)
4229
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004230 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004231 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004232
4233 Essentially a plus operation with all trailing zeros removed from the
4234 result.
4235
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004236 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004237 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004238 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004239 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004240 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004241 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004242 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004243 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004244 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004245 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004246 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004247 Decimal("0")
4248 """
4249 return a.normalize(context=self)
4250
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004251 def number_class(self, a):
4252 """Returns an indication of the class of the operand.
4253
4254 The class is one of the following strings:
4255 -sNaN
4256 -NaN
4257 -Infinity
4258 -Normal
4259 -Subnormal
4260 -Zero
4261 +Zero
4262 +Subnormal
4263 +Normal
4264 +Infinity
4265
4266 >>> c = Context(ExtendedContext)
4267 >>> c.Emin = -999
4268 >>> c.Emax = 999
4269 >>> c.number_class(Decimal('Infinity'))
4270 '+Infinity'
4271 >>> c.number_class(Decimal('1E-10'))
4272 '+Normal'
4273 >>> c.number_class(Decimal('2.50'))
4274 '+Normal'
4275 >>> c.number_class(Decimal('0.1E-999'))
4276 '+Subnormal'
4277 >>> c.number_class(Decimal('0'))
4278 '+Zero'
4279 >>> c.number_class(Decimal('-0'))
4280 '-Zero'
4281 >>> c.number_class(Decimal('-0.1E-999'))
4282 '-Subnormal'
4283 >>> c.number_class(Decimal('-1E-10'))
4284 '-Normal'
4285 >>> c.number_class(Decimal('-2.50'))
4286 '-Normal'
4287 >>> c.number_class(Decimal('-Infinity'))
4288 '-Infinity'
4289 >>> c.number_class(Decimal('NaN'))
4290 'NaN'
4291 >>> c.number_class(Decimal('-NaN'))
4292 'NaN'
4293 >>> c.number_class(Decimal('sNaN'))
4294 'sNaN'
4295 """
4296 return a.number_class(context=self)
4297
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004298 def plus(self, a):
4299 """Plus corresponds to unary prefix plus in Python.
4300
4301 The operation is evaluated using the same rules as add; the
4302 operation plus(a) is calculated as add('0', a) where the '0'
4303 has the same exponent as the operand.
4304
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004305 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004306 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004307 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004308 Decimal("-1.3")
4309 """
4310 return a.__pos__(context=self)
4311
4312 def power(self, a, b, modulo=None):
4313 """Raises a to the power of b, to modulo if given.
4314
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004315 With two arguments, compute a**b. If a is negative then b
4316 must be integral. The result will be inexact unless b is
4317 integral and the result is finite and can be expressed exactly
4318 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004319
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004320 With three arguments, compute (a**b) % modulo. For the
4321 three argument form, the following restrictions on the
4322 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004323
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004324 - all three arguments must be integral
4325 - b must be nonnegative
4326 - at least one of a or b must be nonzero
4327 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004328
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004329 The result of pow(a, b, modulo) is identical to the result
4330 that would be obtained by computing (a**b) % modulo with
4331 unbounded precision, but is computed more efficiently. It is
4332 always exact.
4333
4334 >>> c = ExtendedContext.copy()
4335 >>> c.Emin = -999
4336 >>> c.Emax = 999
4337 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004338 Decimal("8")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004339 >>> c.power(Decimal('-2'), Decimal('3'))
4340 Decimal("-8")
4341 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004342 Decimal("0.125")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004343 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004344 Decimal("69.7575744")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004345 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4346 Decimal("2.00000000")
4347 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004348 Decimal("0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004349 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004350 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004351 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004352 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004353 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004354 Decimal("-0")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004355 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004356 Decimal("1")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004357 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004358 Decimal("-Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004359 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004360 Decimal("Infinity")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004361 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004362 Decimal("NaN")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004363
4364 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4365 Decimal("11")
4366 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4367 Decimal("-11")
4368 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4369 Decimal("1")
4370 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4371 Decimal("11")
4372 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4373 Decimal("11729830")
4374 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4375 Decimal("-0")
4376 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4377 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004378 """
4379 return a.__pow__(b, modulo, context=self)
4380
4381 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004382 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004383
4384 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004385 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004386 exponent is being increased), multiplied by a positive power of ten (if
4387 the exponent is being decreased), or is unchanged (if the exponent is
4388 already equal to that of the right-hand operand).
4389
4390 Unlike other operations, if the length of the coefficient after the
4391 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004392 operation condition is raised. This guarantees that, unless there is
4393 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004394 equal to that of the right-hand operand.
4395
4396 Also unlike other operations, quantize will never raise Underflow, even
4397 if the result is subnormal and inexact.
4398
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004399 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004400 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004401 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004402 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004403 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004404 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004405 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004406 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004407 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004408 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004409 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004410 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004411 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004412 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004413 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004414 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004415 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004416 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004417 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004418 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004419 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004420 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004421 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004422 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004423 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004424 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004425 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004426 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004427 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004428 Decimal("2E+2")
4429 """
4430 return a.quantize(b, context=self)
4431
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004432 def radix(self):
4433 """Just returns 10, as this is Decimal, :)
4434
4435 >>> ExtendedContext.radix()
4436 Decimal("10")
4437 """
4438 return Decimal(10)
4439
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004440 def remainder(self, a, b):
4441 """Returns the remainder from integer division.
4442
4443 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004444 calculating integer division as described for divide-integer, rounded
4445 to precision digits if necessary. The sign of the result, if
4446 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004447
4448 This operation will fail under the same conditions as integer division
4449 (that is, if integer division on the same two operands would fail, the
4450 remainder cannot be calculated).
4451
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004452 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004453 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004454 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004455 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004456 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004457 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004458 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004459 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004460 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004461 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004462 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004463 Decimal("1.0")
4464 """
4465 return a.__mod__(b, context=self)
4466
4467 def remainder_near(self, a, b):
4468 """Returns to be "a - b * n", where n is the integer nearest the exact
4469 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004470 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004471 sign of a.
4472
4473 This operation will fail under the same conditions as integer division
4474 (that is, if integer division on the same two operands would fail, the
4475 remainder cannot be calculated).
4476
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004477 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004478 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004479 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004480 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004481 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004482 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004483 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004484 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004485 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004486 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004487 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004488 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004489 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004490 Decimal("-0.3")
4491 """
4492 return a.remainder_near(b, context=self)
4493
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004494 def rotate(self, a, b):
4495 """Returns a rotated copy of a, b times.
4496
4497 The coefficient of the result is a rotated copy of the digits in
4498 the coefficient of the first operand. The number of places of
4499 rotation is taken from the absolute value of the second operand,
4500 with the rotation being to the left if the second operand is
4501 positive or to the right otherwise.
4502
4503 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4504 Decimal("400000003")
4505 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4506 Decimal("12")
4507 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4508 Decimal("891234567")
4509 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4510 Decimal("123456789")
4511 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4512 Decimal("345678912")
4513 """
4514 return a.rotate(b, context=self)
4515
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004516 def same_quantum(self, a, b):
4517 """Returns True if the two operands have the same exponent.
4518
4519 The result is never affected by either the sign or the coefficient of
4520 either operand.
4521
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004522 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004523 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004524 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004525 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004526 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004527 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004528 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004529 True
4530 """
4531 return a.same_quantum(b)
4532
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004533 def scaleb (self, a, b):
4534 """Returns the first operand after adding the second value its exp.
4535
4536 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4537 Decimal("0.0750")
4538 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4539 Decimal("7.50")
4540 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4541 Decimal("7.50E+3")
4542 """
4543 return a.scaleb (b, context=self)
4544
4545 def shift(self, a, b):
4546 """Returns a shifted copy of a, b times.
4547
4548 The coefficient of the result is a shifted copy of the digits
4549 in the coefficient of the first operand. The number of places
4550 to shift is taken from the absolute value of the second operand,
4551 with the shift being to the left if the second operand is
4552 positive or to the right otherwise. Digits shifted into the
4553 coefficient are zeros.
4554
4555 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4556 Decimal("400000000")
4557 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4558 Decimal("0")
4559 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4560 Decimal("1234567")
4561 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4562 Decimal("123456789")
4563 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4564 Decimal("345678900")
4565 """
4566 return a.shift(b, context=self)
4567
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004568 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004569 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004570
4571 If the result must be inexact, it is rounded using the round-half-even
4572 algorithm.
4573
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004574 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004575 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004576 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004577 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004578 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004579 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004580 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004581 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004582 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004583 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004584 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004585 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004586 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004587 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004588 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004589 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004590 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004591 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004592 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004593 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004594 """
4595 return a.sqrt(context=self)
4596
4597 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004598 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004599
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004600 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004601 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004602 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004603 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004604 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004605 Decimal("-0.77")
4606 """
4607 return a.__sub__(b, context=self)
4608
4609 def to_eng_string(self, a):
4610 """Converts a number to a string, using scientific notation.
4611
4612 The operation is not affected by the context.
4613 """
4614 return a.to_eng_string(context=self)
4615
4616 def to_sci_string(self, a):
4617 """Converts a number to a string, using scientific notation.
4618
4619 The operation is not affected by the context.
4620 """
4621 return a.__str__(context=self)
4622
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004623 def to_integral_exact(self, a):
4624 """Rounds to an integer.
4625
4626 When the operand has a negative exponent, the result is the same
4627 as using the quantize() operation using the given operand as the
4628 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4629 of the operand as the precision setting; Inexact and Rounded flags
4630 are allowed in this operation. The rounding mode is taken from the
4631 context.
4632
4633 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4634 Decimal("2")
4635 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4636 Decimal("100")
4637 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4638 Decimal("100")
4639 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4640 Decimal("102")
4641 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4642 Decimal("-102")
4643 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4644 Decimal("1.0E+6")
4645 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4646 Decimal("7.89E+77")
4647 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4648 Decimal("-Infinity")
4649 """
4650 return a.to_integral_exact(context=self)
4651
4652 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004653 """Rounds to an integer.
4654
4655 When the operand has a negative exponent, the result is the same
4656 as using the quantize() operation using the given operand as the
4657 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4658 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004659 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004660
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004661 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004662 Decimal("2")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004663 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004664 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004665 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004666 Decimal("100")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004667 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004668 Decimal("102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004669 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004670 Decimal("-102")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004671 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004672 Decimal("1.0E+6")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004673 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004674 Decimal("7.89E+77")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004675 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004676 Decimal("-Infinity")
4677 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004678 return a.to_integral_value(context=self)
4679
4680 # the method name changed, but we provide also the old one, for compatibility
4681 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004682
4683class _WorkRep(object):
4684 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004685 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004686 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004687 # exp: None, int, or string
4688
4689 def __init__(self, value=None):
4690 if value is None:
4691 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004692 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004693 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004694 elif isinstance(value, Decimal):
4695 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00004696 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004697 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004698 else:
4699 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004700 self.sign = value[0]
4701 self.int = value[1]
4702 self.exp = value[2]
4703
4704 def __repr__(self):
4705 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4706
4707 __str__ = __repr__
4708
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004709
4710
Christian Heimes2c181612007-12-17 20:04:13 +00004711def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004712 """Normalizes op1, op2 to have the same exp and length of coefficient.
4713
4714 Done during addition.
4715 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004716 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004717 tmp = op2
4718 other = op1
4719 else:
4720 tmp = op1
4721 other = op2
4722
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004723 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4724 # Then adding 10**exp to tmp has the same effect (after rounding)
4725 # as adding any positive quantity smaller than 10**exp; similarly
4726 # for subtraction. So if other is smaller than 10**exp we replace
4727 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00004728 tmp_len = len(str(tmp.int))
4729 other_len = len(str(other.int))
4730 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4731 if other_len + other.exp - 1 < exp:
4732 other.int = 1
4733 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004734
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004735 tmp.int *= 10 ** (tmp.exp - other.exp)
4736 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004737 return op1, op2
4738
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004739##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004740
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004741# This function from Tim Peters was taken from here:
4742# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4743# The correction being in the function definition is for speed, and
4744# the whole function is not resolved with math.log because of avoiding
4745# the use of floats.
4746def _nbits(n, correction = {
4747 '0': 4, '1': 3, '2': 2, '3': 2,
4748 '4': 1, '5': 1, '6': 1, '7': 1,
4749 '8': 0, '9': 0, 'a': 0, 'b': 0,
4750 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4751 """Number of bits in binary representation of the positive integer n,
4752 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004753 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004754 if n < 0:
4755 raise ValueError("The argument to _nbits should be nonnegative.")
4756 hex_n = "%x" % n
4757 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004758
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004759def _sqrt_nearest(n, a):
4760 """Closest integer to the square root of the positive integer n. a is
4761 an initial approximation to the square root. Any positive integer
4762 will do for a, but the closer a is to the square root of n the
4763 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004764
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004765 """
4766 if n <= 0 or a <= 0:
4767 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4768
4769 b=0
4770 while a != b:
4771 b, a = a, a--n//a>>1
4772 return a
4773
4774def _rshift_nearest(x, shift):
4775 """Given an integer x and a nonnegative integer shift, return closest
4776 integer to x / 2**shift; use round-to-even in case of a tie.
4777
4778 """
4779 b, q = 1 << shift, x >> shift
4780 return q + (2*(x & (b-1)) + (q&1) > b)
4781
4782def _div_nearest(a, b):
4783 """Closest integer to a/b, a and b positive integers; rounds to even
4784 in the case of a tie.
4785
4786 """
4787 q, r = divmod(a, b)
4788 return q + (2*r + (q&1) > b)
4789
4790def _ilog(x, M, L = 8):
4791 """Integer approximation to M*log(x/M), with absolute error boundable
4792 in terms only of x/M.
4793
4794 Given positive integers x and M, return an integer approximation to
4795 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4796 between the approximation and the exact result is at most 22. For
4797 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4798 both cases these are upper bounds on the error; it will usually be
4799 much smaller."""
4800
4801 # The basic algorithm is the following: let log1p be the function
4802 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4803 # the reduction
4804 #
4805 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4806 #
4807 # repeatedly until the argument to log1p is small (< 2**-L in
4808 # absolute value). For small y we can use the Taylor series
4809 # expansion
4810 #
4811 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4812 #
4813 # truncating at T such that y**T is small enough. The whole
4814 # computation is carried out in a form of fixed-point arithmetic,
4815 # with a real number z being represented by an integer
4816 # approximation to z*M. To avoid loss of precision, the y below
4817 # is actually an integer approximation to 2**R*y*M, where R is the
4818 # number of reductions performed so far.
4819
4820 y = x-M
4821 # argument reduction; R = number of reductions performed
4822 R = 0
4823 while (R <= L and abs(y) << L-R >= M or
4824 R > L and abs(y) >> R-L >= M):
4825 y = _div_nearest((M*y) << 1,
4826 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4827 R += 1
4828
4829 # Taylor series with T terms
4830 T = -int(-10*len(str(M))//(3*L))
4831 yshift = _rshift_nearest(y, R)
4832 w = _div_nearest(M, T)
4833 for k in range(T-1, 0, -1):
4834 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4835
4836 return _div_nearest(w*y, M)
4837
4838def _dlog10(c, e, p):
4839 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4840 approximation to 10**p * log10(c*10**e), with an absolute error of
4841 at most 1. Assumes that c*10**e is not exactly 1."""
4842
4843 # increase precision by 2; compensate for this by dividing
4844 # final result by 100
4845 p += 2
4846
4847 # write c*10**e as d*10**f with either:
4848 # f >= 0 and 1 <= d <= 10, or
4849 # f <= 0 and 0.1 <= d <= 1.
4850 # Thus for c*10**e close to 1, f = 0
4851 l = len(str(c))
4852 f = e+l - (e+l >= 1)
4853
4854 if p > 0:
4855 M = 10**p
4856 k = e+p-f
4857 if k >= 0:
4858 c *= 10**k
4859 else:
4860 c = _div_nearest(c, 10**-k)
4861
4862 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004863 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004864 log_d = _div_nearest(log_d*M, log_10)
4865 log_tenpower = f*M # exact
4866 else:
4867 log_d = 0 # error < 2.31
4868 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4869
4870 return _div_nearest(log_tenpower+log_d, 100)
4871
4872def _dlog(c, e, p):
4873 """Given integers c, e and p with c > 0, compute an integer
4874 approximation to 10**p * log(c*10**e), with an absolute error of
4875 at most 1. Assumes that c*10**e is not exactly 1."""
4876
4877 # Increase precision by 2. The precision increase is compensated
4878 # for at the end with a division by 100.
4879 p += 2
4880
4881 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4882 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4883 # as 10**p * log(d) + 10**p*f * log(10).
4884 l = len(str(c))
4885 f = e+l - (e+l >= 1)
4886
4887 # compute approximation to 10**p*log(d), with error < 27
4888 if p > 0:
4889 k = e+p-f
4890 if k >= 0:
4891 c *= 10**k
4892 else:
4893 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4894
4895 # _ilog magnifies existing error in c by a factor of at most 10
4896 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4897 else:
4898 # p <= 0: just approximate the whole thing by 0; error < 2.31
4899 log_d = 0
4900
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004901 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004902 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004903 extra = len(str(abs(f)))-1
4904 if p + extra >= 0:
4905 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4906 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4907 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004908 else:
4909 f_log_ten = 0
4910 else:
4911 f_log_ten = 0
4912
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004913 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004914 return _div_nearest(f_log_ten + log_d, 100)
4915
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004916class _Log10Memoize(object):
4917 """Class to compute, store, and allow retrieval of, digits of the
4918 constant log(10) = 2.302585.... This constant is needed by
4919 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4920 def __init__(self):
4921 self.digits = "23025850929940456840179914546843642076011014886"
4922
4923 def getdigits(self, p):
4924 """Given an integer p >= 0, return floor(10**p)*log(10).
4925
4926 For example, self.getdigits(3) returns 2302.
4927 """
4928 # digits are stored as a string, for quick conversion to
4929 # integer in the case that we've already computed enough
4930 # digits; the stored digits should always be correct
4931 # (truncated, not rounded to nearest).
4932 if p < 0:
4933 raise ValueError("p should be nonnegative")
4934
4935 if p >= len(self.digits):
4936 # compute p+3, p+6, p+9, ... digits; continue until at
4937 # least one of the extra digits is nonzero
4938 extra = 3
4939 while True:
4940 # compute p+extra digits, correct to within 1ulp
4941 M = 10**(p+extra+2)
4942 digits = str(_div_nearest(_ilog(10*M, M), 100))
4943 if digits[-extra:] != '0'*extra:
4944 break
4945 extra += 3
4946 # keep all reliable digits so far; remove trailing zeros
4947 # and next nonzero digit
4948 self.digits = digits.rstrip('0')[:-1]
4949 return int(self.digits[:p+1])
4950
4951_log10_digits = _Log10Memoize().getdigits
4952
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004953def _iexp(x, M, L=8):
4954 """Given integers x and M, M > 0, such that x/M is small in absolute
4955 value, compute an integer approximation to M*exp(x/M). For 0 <=
4956 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4957 is usually much smaller)."""
4958
4959 # Algorithm: to compute exp(z) for a real number z, first divide z
4960 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4961 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4962 # series
4963 #
4964 # expm1(x) = x + x**2/2! + x**3/3! + ...
4965 #
4966 # Now use the identity
4967 #
4968 # expm1(2x) = expm1(x)*(expm1(x)+2)
4969 #
4970 # R times to compute the sequence expm1(z/2**R),
4971 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
4972
4973 # Find R such that x/2**R/M <= 2**-L
4974 R = _nbits((x<<L)//M)
4975
4976 # Taylor series. (2**L)**T > M
4977 T = -int(-10*len(str(M))//(3*L))
4978 y = _div_nearest(x, T)
4979 Mshift = M<<R
4980 for i in range(T-1, 0, -1):
4981 y = _div_nearest(x*(Mshift + y), Mshift * i)
4982
4983 # Expansion
4984 for k in range(R-1, -1, -1):
4985 Mshift = M<<(k+2)
4986 y = _div_nearest(y*(y+Mshift), Mshift)
4987
4988 return M+y
4989
4990def _dexp(c, e, p):
4991 """Compute an approximation to exp(c*10**e), with p decimal places of
4992 precision.
4993
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004994 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004995
4996 10**(p-1) <= d <= 10**p, and
4997 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
4998
4999 In other words, d*10**f is an approximation to exp(c*10**e) with p
5000 digits of precision, and with an error in d of at most 1. This is
5001 almost, but not quite, the same as the error being < 1ulp: when d
5002 = 10**(p-1) the error could be up to 10 ulp."""
5003
5004 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5005 p += 2
5006
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005007 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005008 extra = max(0, e + len(str(c)) - 1)
5009 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005010
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005011 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005012 # rounding down
5013 shift = e+q
5014 if shift >= 0:
5015 cshift = c*10**shift
5016 else:
5017 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005018 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005019
5020 # reduce remainder back to original precision
5021 rem = _div_nearest(rem, 10**extra)
5022
5023 # error in result of _iexp < 120; error after division < 0.62
5024 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5025
5026def _dpower(xc, xe, yc, ye, p):
5027 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5028 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5029
5030 10**(p-1) <= c <= 10**p, and
5031 (c-1)*10**e < x**y < (c+1)*10**e
5032
5033 in other words, c*10**e is an approximation to x**y with p digits
5034 of precision, and with an error in c of at most 1. (This is
5035 almost, but not quite, the same as the error being < 1ulp: when c
5036 == 10**(p-1) we can only guarantee error < 10ulp.)
5037
5038 We assume that: x is positive and not equal to 1, and y is nonzero.
5039 """
5040
5041 # Find b such that 10**(b-1) <= |y| <= 10**b
5042 b = len(str(abs(yc))) + ye
5043
5044 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5045 lxc = _dlog(xc, xe, p+b+1)
5046
5047 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5048 shift = ye-b
5049 if shift >= 0:
5050 pc = lxc*yc*10**shift
5051 else:
5052 pc = _div_nearest(lxc*yc, 10**-shift)
5053
5054 if pc == 0:
5055 # we prefer a result that isn't exactly 1; this makes it
5056 # easier to compute a correctly rounded result in __pow__
5057 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5058 coeff, exp = 10**(p-1)+1, 1-p
5059 else:
5060 coeff, exp = 10**p-1, -p
5061 else:
5062 coeff, exp = _dexp(pc, -(p+1), p+1)
5063 coeff = _div_nearest(coeff, 10)
5064 exp += 1
5065
5066 return coeff, exp
5067
5068def _log10_lb(c, correction = {
5069 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5070 '6': 23, '7': 16, '8': 10, '9': 5}):
5071 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5072 if c <= 0:
5073 raise ValueError("The argument to _log10_lb should be nonnegative.")
5074 str_c = str(c)
5075 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005076
Guido van Rossumd8faa362007-04-27 19:54:29 +00005077##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005078
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005079def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005080 """Convert other to Decimal.
5081
5082 Verifies that it's ok to use in an implicit construction.
5083 """
5084 if isinstance(other, Decimal):
5085 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005086 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005087 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005088 if raiseit:
5089 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005090 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005091
Guido van Rossumd8faa362007-04-27 19:54:29 +00005092##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005093
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005094# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005095# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005096
5097DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005098 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005099 traps=[DivisionByZero, Overflow, InvalidOperation],
5100 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005101 Emax=999999999,
5102 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005103 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005104)
5105
5106# Pre-made alternate contexts offered by the specification
5107# Don't change these; the user should be able to select these
5108# contexts and be able to reproduce results from other implementations
5109# of the spec.
5110
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005111BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005112 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005113 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5114 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005115)
5116
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005117ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005118 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005119 traps=[],
5120 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005121)
5122
5123
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005124##### crud for parsing strings #############################################
5125import re
5126
5127# Regular expression used for parsing numeric strings. Additional
5128# comments:
5129#
5130# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5131# whitespace. But note that the specification disallows whitespace in
5132# a numeric string.
5133#
5134# 2. For finite numbers (not infinities and NaNs) the body of the
5135# number between the optional sign and the optional exponent must have
5136# at least one decimal digit, possibly after the decimal point. The
5137# lookahead expression '(?=\d|\.\d)' checks this.
5138#
5139# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5140# other meaning for \d than the numbers [0-9].
5141
5142import re
5143_parser = re.compile(r""" # A numeric string consists of:
5144# \s*
5145 (?P<sign>[-+])? # an optional sign, followed by either...
5146 (
5147 (?=\d|\.\d) # ...a number (with at least one digit)
5148 (?P<int>\d*) # consisting of a (possibly empty) integer part
5149 (\.(?P<frac>\d*))? # followed by an optional fractional part
5150 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5151 |
5152 Inf(inity)? # ...an infinity, or...
5153 |
5154 (?P<signal>s)? # ...an (optionally signaling)
5155 NaN # NaN
5156 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5157 )
5158# \s*
5159 $
5160""", re.VERBOSE | re.IGNORECASE).match
5161
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005162_all_zeros = re.compile('0*$').match
5163_exact_half = re.compile('50*$').match
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005164del re
5165
5166
Guido van Rossumd8faa362007-04-27 19:54:29 +00005167##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005168
Guido van Rossumd8faa362007-04-27 19:54:29 +00005169# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005170Inf = Decimal('Inf')
5171negInf = Decimal('-Inf')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005172NaN = Decimal('NaN')
5173Dec_0 = Decimal(0)
5174Dec_p1 = Decimal(1)
5175Dec_n1 = Decimal(-1)
5176Dec_p2 = Decimal(2)
5177Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005178
Guido van Rossumd8faa362007-04-27 19:54:29 +00005179# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005180Infsign = (Inf, negInf)
5181
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005182
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005183
5184if __name__ == '__main__':
5185 import doctest, sys
5186 doctest.testmod(sys.modules[__name__])