blob: 7fb9c7b82e82486b9cd52ee2bc3be02cd1982774 [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
Christian Heimes68f5fbe2008-02-14 08:27:37 +000038of the expected Decimal('0.00') returned by decimal floating point).
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000039
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)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000045Decimal('0')
46>>> Decimal('1')
47Decimal('1')
48>>> Decimal('-.0123')
49Decimal('-0.0123')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000050>>> Decimal(123456)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000051Decimal('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')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000058>>> 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))
Christian Heimes68f5fbe2008-02-14 08:27:37 +000094Decimal('NaN')
Raymond Hettingerbf440692004-07-10 14:14:37 +000095>>> c.traps[InvalidOperation] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000096>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000098>>> c.flags[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000099>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000
Guido van Rossum7131f842007-02-09 20:13:25 +0000101>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000102Traceback (most recent call last):
103 ...
104 ...
105 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +0000106decimal.InvalidOperation: 0 / 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000107>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000109>>> c.flags[InvalidOperation] = 0
Raymond Hettingerbf440692004-07-10 14:14:37 +0000110>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000111>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000112NaN
Guido van Rossum7131f842007-02-09 20:13:25 +0000113>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141
115>>>
116"""
117
118__all__ = [
119 # Two major classes
120 'Decimal', 'Context',
121
122 # Contexts
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +0000123 'DefaultContext', 'BasicContext', 'ExtendedContext',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000124
125 # Exceptions
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +0000126 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
127 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000128
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000129 # Constants for use in setting up contexts
130 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000131 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000132
133 # Functions for manipulating contexts
Thomas Wouters89f507f2006-12-13 04:49:30 +0000134 'setcontext', 'getcontext', 'localcontext'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000135]
136
Guido van Rossuma13f4a12007-12-10 20:04:04 +0000137import numbers as _numbers
Raymond Hettingereb260842005-06-07 18:52:34 +0000138import copy as _copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000139
Christian Heimes25bb7832008-01-11 16:17:00 +0000140try:
141 from collections import namedtuple as _namedtuple
142 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
143except ImportError:
144 DecimalTuple = lambda *args: args
145
Guido van Rossumd8faa362007-04-27 19:54:29 +0000146# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000147ROUND_DOWN = 'ROUND_DOWN'
148ROUND_HALF_UP = 'ROUND_HALF_UP'
149ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
150ROUND_CEILING = 'ROUND_CEILING'
151ROUND_FLOOR = 'ROUND_FLOOR'
152ROUND_UP = 'ROUND_UP'
153ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000154ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000155
Guido van Rossumd8faa362007-04-27 19:54:29 +0000156# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000157
158class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000159 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000160
161 Used exceptions derive from this.
162 If an exception derives from another exception besides this (such as
163 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
164 called if the others are present. This isn't actually used for
165 anything, though.
166
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000167 handle -- Called when context._raise_error is called and the
168 trap_enabler is set. First argument is self, second is the
169 context. More arguments can be given, those being after
170 the explanation in _raise_error (For example,
171 context._raise_error(NewError, '(-x)!', self._sign) would
172 call NewError().handle(context, self._sign).)
173
174 To define a new exception, it should be sufficient to have it derive
175 from DecimalException.
176 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000177 def handle(self, context, *args):
178 pass
179
180
181class Clamped(DecimalException):
182 """Exponent of a 0 changed to fit bounds.
183
184 This occurs and signals clamped if the exponent of a result has been
185 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000186 representation. This may occur when the exponent of a zero result would
187 be outside the bounds of a representation, or when a large normal
188 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000189 this latter case, the exponent is reduced to fit and the corresponding
190 number of zero digits are appended to the coefficient ("fold-down").
191 """
192
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000193class InvalidOperation(DecimalException):
194 """An invalid operation was performed.
195
196 Various bad things cause this:
197
198 Something creates a signaling NaN
199 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000200 0 * (+-)INF
201 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000202 x % 0
203 (+-)INF % x
204 x._rescale( non-integer )
205 sqrt(-x) , x > 0
206 0 ** 0
207 x ** (non-integer)
208 x ** (+-)INF
209 An operand is invalid
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000210
211 The result of the operation after these is a quiet positive NaN,
212 except when the cause is a signaling NaN, in which case the result is
213 also a quiet NaN, but with the original sign, and an optional
214 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000215 """
216 def handle(self, context, *args):
217 if args:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000218 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
219 return ans._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000220 return NaN
221
222class ConversionSyntax(InvalidOperation):
223 """Trying to convert badly formed string.
224
225 This occurs and signals invalid-operation if an string is being
226 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000228 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000229 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000230 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000231
232class DivisionByZero(DecimalException, ZeroDivisionError):
233 """Division by 0.
234
235 This occurs and signals division-by-zero if division of a finite number
236 by zero was attempted (during a divide-integer or divide operation, or a
237 power operation with negative right-hand operand), and the dividend was
238 not zero.
239
240 The result of the operation is [sign,inf], where sign is the exclusive
241 or of the signs of the operands for divide, or is 1 for an odd power of
242 -0, for power.
243 """
244
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000245 def handle(self, context, sign, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000246 return Infsign[sign]
247
248class DivisionImpossible(InvalidOperation):
249 """Cannot perform the division adequately.
250
251 This occurs and signals invalid-operation if the integer result of a
252 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000253 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000254 """
255
256 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000257 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000258
259class DivisionUndefined(InvalidOperation, ZeroDivisionError):
260 """Undefined result of division.
261
262 This occurs and signals invalid-operation if division by zero was
263 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000264 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000265 """
266
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000267 def handle(self, context, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000268 return NaN
269
270class Inexact(DecimalException):
271 """Had to round, losing information.
272
273 This occurs and signals inexact whenever the result of an operation is
274 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000275 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000276 result in all cases is unchanged.
277
278 The inexact signal may be tested (or trapped) to determine if a given
279 operation (or sequence of operations) was inexact.
280 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000281
282class InvalidContext(InvalidOperation):
283 """Invalid context. Unknown rounding, for example.
284
285 This occurs and signals invalid-operation if an invalid context was
Guido van Rossumd8faa362007-04-27 19:54:29 +0000286 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000287 on creation and either the precision exceeds the capability of the
288 underlying concrete representation or an unknown or unsupported rounding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000289 was specified. These aspects of the context need only be checked when
290 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000291 """
292
293 def handle(self, context, *args):
294 return NaN
295
296class Rounded(DecimalException):
297 """Number got rounded (not necessarily changed during rounding).
298
299 This occurs and signals rounded whenever the result of an operation is
300 rounded (that is, some zero or non-zero digits were discarded from the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000301 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000302 result in all cases is unchanged.
303
304 The rounded signal may be tested (or trapped) to determine if a given
305 operation (or sequence of operations) caused a loss of precision.
306 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000307
308class Subnormal(DecimalException):
309 """Exponent < Emin before rounding.
310
311 This occurs and signals subnormal whenever the result of a conversion or
312 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000313 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000314
315 The subnormal signal may be tested (or trapped) to determine if a given
316 or operation (or sequence of operations) yielded a subnormal result.
317 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000318
319class Overflow(Inexact, Rounded):
320 """Numerical overflow.
321
322 This occurs and signals overflow if the adjusted exponent of a result
323 (from a conversion or from an operation that is not an attempt to divide
324 by zero), after rounding, would be greater than the largest value that
325 can be handled by the implementation (the value Emax).
326
327 The result depends on the rounding mode:
328
329 For round-half-up and round-half-even (and for round-half-down and
330 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000331 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000332 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000333 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000334 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000335 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000336 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000337 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000338 will also be raised.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000339 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000340
341 def handle(self, context, sign, *args):
342 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000343 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000344 return Infsign[sign]
345 if sign == 0:
346 if context.rounding == ROUND_CEILING:
347 return Infsign[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000348 return _dec_from_triple(sign, '9'*context.prec,
349 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000350 if sign == 1:
351 if context.rounding == ROUND_FLOOR:
352 return Infsign[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000353 return _dec_from_triple(sign, '9'*context.prec,
354 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000355
356
357class Underflow(Inexact, Rounded, Subnormal):
358 """Numerical underflow with result rounded to 0.
359
360 This occurs and signals underflow if a result is inexact and the
361 adjusted exponent of the result would be smaller (more negative) than
362 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000363 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000364
365 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000366 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000367 in 0 with the sign of the intermediate result and an exponent of Etiny.
368
369 In all cases, Inexact, Rounded, and Subnormal will also be raised.
370 """
371
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000372# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000373_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000374 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000375
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000376# Map conditions (per the spec) to signals
377_condition_map = {ConversionSyntax:InvalidOperation,
378 DivisionImpossible:InvalidOperation,
379 DivisionUndefined:InvalidOperation,
380 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000381
Guido van Rossumd8faa362007-04-27 19:54:29 +0000382##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000383
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000384# The getcontext() and setcontext() function manage access to a thread-local
385# current context. Py2.4 offers direct support for thread locals. If that
Georg Brandlf9926402008-06-13 06:32:25 +0000386# is not available, use threading.current_thread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000387# work for older Pythons. If threads are not part of the build, create a
388# mock threading object with threading.local() returning the module namespace.
389
390try:
391 import threading
392except ImportError:
393 # Python was compiled without threads; create a mock object instead
394 import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +0000395 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000396 def local(self, sys=sys):
397 return sys.modules[__name__]
398 threading = MockThreading()
399 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000400
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000401try:
402 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000403
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000404except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000405
Guido van Rossumd8faa362007-04-27 19:54:29 +0000406 # To fix reloading, force it to create a new context
407 # Old contexts have different exceptions in their dicts, making problems.
Georg Brandlf9926402008-06-13 06:32:25 +0000408 if hasattr(threading.current_thread(), '__decimal_context__'):
409 del threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000410
411 def setcontext(context):
412 """Set this thread's context to context."""
413 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000414 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000415 context.clear_flags()
Georg Brandlf9926402008-06-13 06:32:25 +0000416 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000417
418 def getcontext():
419 """Returns this thread's context.
420
421 If this thread does not yet have a context, returns
422 a new context and sets this thread's context.
423 New contexts are copies of DefaultContext.
424 """
425 try:
Georg Brandlf9926402008-06-13 06:32:25 +0000426 return threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000427 except AttributeError:
428 context = Context()
Georg Brandlf9926402008-06-13 06:32:25 +0000429 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000430 return context
431
432else:
433
434 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000435 if hasattr(local, '__decimal_context__'):
436 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000437
438 def getcontext(_local=local):
439 """Returns this thread's context.
440
441 If this thread does not yet have a context, returns
442 a new context and sets this thread's context.
443 New contexts are copies of DefaultContext.
444 """
445 try:
446 return _local.__decimal_context__
447 except AttributeError:
448 context = Context()
449 _local.__decimal_context__ = context
450 return context
451
452 def setcontext(context, _local=local):
453 """Set this thread's context to context."""
454 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000455 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000456 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000457 _local.__decimal_context__ = context
458
459 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000460
Thomas Wouters89f507f2006-12-13 04:49:30 +0000461def localcontext(ctx=None):
462 """Return a context manager for a copy of the supplied context
463
464 Uses a copy of the current context if no context is specified
465 The returned context manager creates a local decimal context
466 in a with statement:
467 def sin(x):
468 with localcontext() as ctx:
469 ctx.prec += 2
470 # Rest of sin calculation algorithm
471 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000472 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000473
474 def sin(x):
475 with localcontext(ExtendedContext):
476 # Rest of sin calculation algorithm
477 # uses the Extended Context from the
478 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000479 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000480
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000481 >>> setcontext(DefaultContext)
Guido van Rossum7131f842007-02-09 20:13:25 +0000482 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000483 28
484 >>> with localcontext():
485 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000486 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000487 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000488 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000489 30
490 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000491 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000492 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000493 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000494 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000495 28
496 """
497 if ctx is None: ctx = getcontext()
498 return _ContextManager(ctx)
499
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000500
Guido van Rossumd8faa362007-04-27 19:54:29 +0000501##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000502
Christian Heimes08976cb2008-03-16 00:32:36 +0000503class Decimal(_numbers.Real):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000504 """Floating point class for decimal arithmetic."""
505
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000506 __slots__ = ('_exp','_int','_sign', '_is_special')
507 # Generally, the value of the Decimal instance is given by
508 # (-1)**_sign * _int * 10**_exp
509 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000510
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000511 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000512 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000513 """Create a decimal point instance.
514
515 >>> Decimal('3.14') # string input
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000516 Decimal('3.14')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000517 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000518 Decimal('3.14')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000519 >>> Decimal(314) # int
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000520 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000521 >>> Decimal(Decimal(314)) # another decimal instance
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000522 Decimal('314')
Christian Heimesa62da1d2008-01-12 19:39:10 +0000523 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000524 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000525 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000526
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000527 # Note that the coefficient, self._int, is actually stored as
528 # a string rather than as a tuple of digits. This speeds up
529 # the "digits to integer" and "integer to digits" conversions
530 # that are used in almost every arithmetic operation on
531 # Decimals. This is an internal detail: the as_tuple function
532 # and the Decimal constructor still deal with tuples of
533 # digits.
534
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000535 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000536
Christian Heimesd59c64c2007-11-30 19:27:20 +0000537 # From a string
538 # REs insist on real strings, so we can too.
539 if isinstance(value, str):
Christian Heimesa62da1d2008-01-12 19:39:10 +0000540 m = _parser(value.strip())
Christian Heimesd59c64c2007-11-30 19:27:20 +0000541 if m is None:
542 if context is None:
543 context = getcontext()
544 return context._raise_error(ConversionSyntax,
545 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000546
Christian Heimesd59c64c2007-11-30 19:27:20 +0000547 if m.group('sign') == "-":
548 self._sign = 1
549 else:
550 self._sign = 0
551 intpart = m.group('int')
552 if intpart is not None:
553 # finite number
554 fracpart = m.group('frac')
555 exp = int(m.group('exp') or '0')
556 if fracpart is not None:
557 self._int = (intpart+fracpart).lstrip('0') or '0'
558 self._exp = exp - len(fracpart)
559 else:
560 self._int = intpart.lstrip('0') or '0'
561 self._exp = exp
562 self._is_special = False
563 else:
564 diag = m.group('diag')
565 if diag is not None:
566 # NaN
567 self._int = diag.lstrip('0')
568 if m.group('signal'):
569 self._exp = 'N'
570 else:
571 self._exp = 'n'
572 else:
573 # infinity
574 self._int = '0'
575 self._exp = 'F'
576 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000577 return self
578
579 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000580 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000581 if value >= 0:
582 self._sign = 0
583 else:
584 self._sign = 1
585 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000586 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000587 self._is_special = False
588 return self
589
590 # From another decimal
591 if isinstance(value, Decimal):
592 self._exp = value._exp
593 self._sign = value._sign
594 self._int = value._int
595 self._is_special = value._is_special
596 return self
597
598 # From an internal working value
599 if isinstance(value, _WorkRep):
600 self._sign = value.sign
601 self._int = str(value.int)
602 self._exp = int(value.exp)
603 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000604 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000605
606 # tuple/list conversion (possibly from as_tuple())
607 if isinstance(value, (list,tuple)):
608 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000609 raise ValueError('Invalid tuple size in creation of Decimal '
610 'from list or tuple. The list or tuple '
611 'should have exactly three elements.')
612 # process sign. The isinstance test rejects floats
613 if not (isinstance(value[0], int) and value[0] in (0,1)):
614 raise ValueError("Invalid sign. The first value in the tuple "
615 "should be an integer; either 0 for a "
616 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000617 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000618 if value[2] == 'F':
619 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000620 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000621 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000622 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000623 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000624 # process and validate the digits in value[1]
625 digits = []
626 for digit in value[1]:
627 if isinstance(digit, int) and 0 <= digit <= 9:
628 # skip leading zeros
629 if digits or digit != 0:
630 digits.append(digit)
631 else:
632 raise ValueError("The second value in the tuple must "
633 "be composed of integers in the range "
634 "0 through 9.")
635 if value[2] in ('n', 'N'):
636 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000637 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000638 self._exp = value[2]
639 self._is_special = True
640 elif isinstance(value[2], int):
641 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000642 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000643 self._exp = value[2]
644 self._is_special = False
645 else:
646 raise ValueError("The third value in the tuple must "
647 "be an integer, or one of the "
648 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000649 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000650
Raymond Hettingerbf440692004-07-10 14:14:37 +0000651 if isinstance(value, float):
652 raise TypeError("Cannot convert float to Decimal. " +
653 "First convert the float to a string")
654
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000655 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000656
657 def _isnan(self):
658 """Returns whether the number is not actually one.
659
660 0 if a number
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000661 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000662 2 if sNaN
663 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000664 if self._is_special:
665 exp = self._exp
666 if exp == 'n':
667 return 1
668 elif exp == 'N':
669 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000670 return 0
671
672 def _isinfinity(self):
673 """Returns whether the number is infinite
674
675 0 if finite or not a number
676 1 if +INF
677 -1 if -INF
678 """
679 if self._exp == 'F':
680 if self._sign:
681 return -1
682 return 1
683 return 0
684
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000685 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000686 """Returns whether the number is not actually one.
687
688 if self, other are sNaN, signal
689 if self, other are NaN return nan
690 return 0
691
692 Done before operations.
693 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000694
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000695 self_is_nan = self._isnan()
696 if other is None:
697 other_is_nan = False
698 else:
699 other_is_nan = other._isnan()
700
701 if self_is_nan or other_is_nan:
702 if context is None:
703 context = getcontext()
704
705 if self_is_nan == 2:
706 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000707 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000708 if other_is_nan == 2:
709 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000710 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000711 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000712 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000713
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000714 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000715 return 0
716
Christian Heimes77c02eb2008-02-09 02:18:51 +0000717 def _compare_check_nans(self, other, context):
718 """Version of _check_nans used for the signaling comparisons
719 compare_signal, __le__, __lt__, __ge__, __gt__.
720
721 Signal InvalidOperation if either self or other is a (quiet
722 or signaling) NaN. Signaling NaNs take precedence over quiet
723 NaNs.
724
725 Return 0 if neither operand is a NaN.
726
727 """
728 if context is None:
729 context = getcontext()
730
731 if self._is_special or other._is_special:
732 if self.is_snan():
733 return context._raise_error(InvalidOperation,
734 'comparison involving sNaN',
735 self)
736 elif other.is_snan():
737 return context._raise_error(InvalidOperation,
738 'comparison involving sNaN',
739 other)
740 elif self.is_qnan():
741 return context._raise_error(InvalidOperation,
742 'comparison involving NaN',
743 self)
744 elif other.is_qnan():
745 return context._raise_error(InvalidOperation,
746 'comparison involving NaN',
747 other)
748 return 0
749
Jack Diederich4dafcc42006-11-28 19:15:13 +0000750 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000751 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000752
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000753 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000754 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000755 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000756
Christian Heimes77c02eb2008-02-09 02:18:51 +0000757 def _cmp(self, other):
758 """Compare the two non-NaN decimal instances self and other.
759
760 Returns -1 if self < other, 0 if self == other and 1
761 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000762
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000763 if self._is_special or other._is_special:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000764 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000765
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000766 # check for zeros; note that cmp(0, -0) should return 0
767 if not self:
768 if not other:
769 return 0
770 else:
771 return -((-1)**other._sign)
772 if not other:
773 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000774
Guido van Rossumd8faa362007-04-27 19:54:29 +0000775 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000776 if other._sign < self._sign:
777 return -1
778 if self._sign < other._sign:
779 return 1
780
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000781 self_adjusted = self.adjusted()
782 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000783 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000784 self_padded = self._int + '0'*(self._exp - other._exp)
785 other_padded = other._int + '0'*(other._exp - self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000786 return cmp(self_padded, other_padded) * (-1)**self._sign
787 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000788 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000789 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000790 return -((-1)**self._sign)
791
Christian Heimes77c02eb2008-02-09 02:18:51 +0000792 # Note: The Decimal standard doesn't cover rich comparisons for
793 # Decimals. In particular, the specification is silent on the
794 # subject of what should happen for a comparison involving a NaN.
795 # We take the following approach:
796 #
797 # == comparisons involving a NaN always return False
798 # != comparisons involving a NaN always return True
799 # <, >, <= and >= comparisons involving a (quiet or signaling)
800 # NaN signal InvalidOperation, and return False if the
Christian Heimes3feef612008-02-11 06:19:17 +0000801 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000802 #
803 # This behavior is designed to conform as closely as possible to
804 # that specified by IEEE 754.
805
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000806 def __eq__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000807 other = _convert_other(other)
808 if other is NotImplemented:
809 return other
810 if self.is_nan() or other.is_nan():
811 return False
812 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000813
814 def __ne__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000815 other = _convert_other(other)
816 if other is NotImplemented:
817 return other
818 if self.is_nan() or other.is_nan():
819 return True
820 return self._cmp(other) != 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000821
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000822
Christian Heimes77c02eb2008-02-09 02:18:51 +0000823 def __lt__(self, other, context=None):
824 other = _convert_other(other)
825 if other is NotImplemented:
826 return other
827 ans = self._compare_check_nans(other, context)
828 if ans:
829 return False
830 return self._cmp(other) < 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000831
Christian Heimes77c02eb2008-02-09 02:18:51 +0000832 def __le__(self, other, context=None):
833 other = _convert_other(other)
834 if other is NotImplemented:
835 return other
836 ans = self._compare_check_nans(other, context)
837 if ans:
838 return False
839 return self._cmp(other) <= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000840
Christian Heimes77c02eb2008-02-09 02:18:51 +0000841 def __gt__(self, other, context=None):
842 other = _convert_other(other)
843 if other is NotImplemented:
844 return other
845 ans = self._compare_check_nans(other, context)
846 if ans:
847 return False
848 return self._cmp(other) > 0
849
850 def __ge__(self, other, context=None):
851 other = _convert_other(other)
852 if other is NotImplemented:
853 return other
854 ans = self._compare_check_nans(other, context)
855 if ans:
856 return False
857 return self._cmp(other) >= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000858
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000859 def compare(self, other, context=None):
860 """Compares one to another.
861
862 -1 => a < b
863 0 => a = b
864 1 => a > b
865 NaN => one is NaN
866 Like __cmp__, but returns Decimal instances.
867 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000868 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000869
Guido van Rossumd8faa362007-04-27 19:54:29 +0000870 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000871 if (self._is_special or other and other._is_special):
872 ans = self._check_nans(other, context)
873 if ans:
874 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000875
Christian Heimes77c02eb2008-02-09 02:18:51 +0000876 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000877
878 def __hash__(self):
879 """x.__hash__() <==> hash(x)"""
880 # Decimal integers must hash the same as the ints
Christian Heimes2380ac72008-01-09 00:17:24 +0000881 #
882 # The hash of a nonspecial noninteger Decimal must depend only
883 # on the value of that Decimal, and not on its representation.
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000884 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000885 if self._is_special:
886 if self._isnan():
887 raise TypeError('Cannot hash a NaN value.')
888 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000889 if not self:
890 return 0
891 if self._isinteger():
892 op = _WorkRep(self.to_integral_value())
893 # to make computation feasible for Decimals with large
894 # exponent, we use the fact that hash(n) == hash(m) for
895 # any two nonzero integers n and m such that (i) n and m
896 # have the same sign, and (ii) n is congruent to m modulo
897 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
898 # hash((-1)**s*c*pow(10, e, 2**64-1).
899 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Christian Heimes2380ac72008-01-09 00:17:24 +0000900 # The value of a nonzero nonspecial Decimal instance is
901 # faithfully represented by the triple consisting of its sign,
902 # its adjusted exponent, and its coefficient with trailing
903 # zeros removed.
904 return hash((self._sign,
905 self._exp+len(self._int),
906 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000907
908 def as_tuple(self):
909 """Represents the number as a triple tuple.
910
911 To show the internals exactly as they are.
912 """
Christian Heimes25bb7832008-01-11 16:17:00 +0000913 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000914
915 def __repr__(self):
916 """Represents the number as an instance of Decimal."""
917 # Invariant: eval(repr(d)) == d
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000918 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000919
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000920 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000921 """Return string representation of the number in scientific notation.
922
923 Captures all of the information in the underlying representation.
924 """
925
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000926 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000927 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000928 if self._exp == 'F':
929 return sign + 'Infinity'
930 elif self._exp == 'n':
931 return sign + 'NaN' + self._int
932 else: # self._exp == 'N'
933 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000934
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000935 # number of digits of self._int to left of decimal point
936 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000937
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000938 # dotplace is number of digits of self._int to the left of the
939 # decimal point in the mantissa of the output string (that is,
940 # after adjusting the exponent)
941 if self._exp <= 0 and leftdigits > -6:
942 # no exponent required
943 dotplace = leftdigits
944 elif not eng:
945 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000946 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000947 elif self._int == '0':
948 # engineering notation, zero
949 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000950 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000951 # engineering notation, nonzero
952 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000953
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000954 if dotplace <= 0:
955 intpart = '0'
956 fracpart = '.' + '0'*(-dotplace) + self._int
957 elif dotplace >= len(self._int):
958 intpart = self._int+'0'*(dotplace-len(self._int))
959 fracpart = ''
960 else:
961 intpart = self._int[:dotplace]
962 fracpart = '.' + self._int[dotplace:]
963 if leftdigits == dotplace:
964 exp = ''
965 else:
966 if context is None:
967 context = getcontext()
968 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
969
970 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971
972 def to_eng_string(self, context=None):
973 """Convert to engineering-type string.
974
975 Engineering notation has an exponent which is a multiple of 3, so there
976 are up to 3 digits left of the decimal place.
977
978 Same rules for when in exponential and when as a value as in __str__.
979 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000980 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000981
982 def __neg__(self, context=None):
983 """Returns a copy with the sign switched.
984
985 Rounds, if it has reason.
986 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000987 if self._is_special:
988 ans = self._check_nans(context=context)
989 if ans:
990 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000991
992 if not self:
993 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000994 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000995 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000996 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000997
998 if context is None:
999 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001000 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001001
1002 def __pos__(self, context=None):
1003 """Returns a copy, unless it is a sNaN.
1004
1005 Rounds the number (if more then precision digits)
1006 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001007 if self._is_special:
1008 ans = self._check_nans(context=context)
1009 if ans:
1010 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001011
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001012 if not self:
1013 # + (-0) = 0
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001014 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001015 else:
1016 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001017
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001018 if context is None:
1019 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001020 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001021
Christian Heimes2c181612007-12-17 20:04:13 +00001022 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001023 """Returns the absolute value of self.
1024
Christian Heimes2c181612007-12-17 20:04:13 +00001025 If the keyword argument 'round' is false, do not round. The
1026 expression self.__abs__(round=False) is equivalent to
1027 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001028 """
Christian Heimes2c181612007-12-17 20:04:13 +00001029 if not round:
1030 return self.copy_abs()
1031
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001032 if self._is_special:
1033 ans = self._check_nans(context=context)
1034 if ans:
1035 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001036
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001037 if self._sign:
1038 ans = self.__neg__(context=context)
1039 else:
1040 ans = self.__pos__(context=context)
1041
1042 return ans
1043
1044 def __add__(self, other, context=None):
1045 """Returns self + other.
1046
1047 -INF + INF (or the reverse) cause InvalidOperation errors.
1048 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001049 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001050 if other is NotImplemented:
1051 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001052
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001053 if context is None:
1054 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001056 if self._is_special or other._is_special:
1057 ans = self._check_nans(other, context)
1058 if ans:
1059 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001060
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001061 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001062 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001063 if self._sign != other._sign and other._isinfinity():
1064 return context._raise_error(InvalidOperation, '-INF + INF')
1065 return Decimal(self)
1066 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001067 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001068
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001069 exp = min(self._exp, other._exp)
1070 negativezero = 0
1071 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001072 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001073 negativezero = 1
1074
1075 if not self and not other:
1076 sign = min(self._sign, other._sign)
1077 if negativezero:
1078 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001079 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001080 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001081 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001082 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001083 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001084 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001085 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001086 return ans
1087 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001088 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001089 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001090 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001091 return ans
1092
1093 op1 = _WorkRep(self)
1094 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001095 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001096
1097 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001098 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001099 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001100 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001101 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001102 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001103 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001104 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001105 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001106 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001107 if op1.sign == 1:
1108 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001109 op1.sign, op2.sign = op2.sign, op1.sign
1110 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001111 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001112 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001113 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001114 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001115 op1.sign, op2.sign = (0, 0)
1116 else:
1117 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001118 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001119
Raymond Hettinger17931de2004-10-27 06:21:46 +00001120 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001121 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001122 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001123 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001124
1125 result.exp = op1.exp
1126 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001127 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001128 return ans
1129
1130 __radd__ = __add__
1131
1132 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001133 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001134 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001135 if other is NotImplemented:
1136 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001137
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001138 if self._is_special or other._is_special:
1139 ans = self._check_nans(other, context=context)
1140 if ans:
1141 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001142
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001143 # self - other is computed as self + other.copy_negate()
1144 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001145
1146 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001147 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001148 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001149 if other is NotImplemented:
1150 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001151
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001152 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001153
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001154 def __mul__(self, other, context=None):
1155 """Return self * other.
1156
1157 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1158 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001159 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001160 if other is NotImplemented:
1161 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001162
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001163 if context is None:
1164 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001165
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001166 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001167
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001168 if self._is_special or other._is_special:
1169 ans = self._check_nans(other, context)
1170 if ans:
1171 return ans
1172
1173 if self._isinfinity():
1174 if not other:
1175 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1176 return Infsign[resultsign]
1177
1178 if other._isinfinity():
1179 if not self:
1180 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1181 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001182
1183 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001184
1185 # Special case for multiplying by zero
1186 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001187 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001188 # Fixing in case the exponent is out of bounds
1189 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001190 return ans
1191
1192 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001193 if self._int == '1':
1194 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001195 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001196 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001197 if other._int == '1':
1198 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001199 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001200 return ans
1201
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001202 op1 = _WorkRep(self)
1203 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001204
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001205 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001206 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001207
1208 return ans
1209 __rmul__ = __mul__
1210
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001211 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001212 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001213 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001214 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001215 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001216
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001217 if context is None:
1218 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001219
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001220 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001221
1222 if self._is_special or other._is_special:
1223 ans = self._check_nans(other, context)
1224 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001225 return ans
1226
1227 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001228 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001229
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001230 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001231 return Infsign[sign]
1232
1233 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001234 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001235 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001236
1237 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001238 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001239 if not self:
1240 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001241 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001242
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001243 if not self:
1244 exp = self._exp - other._exp
1245 coeff = 0
1246 else:
1247 # OK, so neither = 0, INF or NaN
1248 shift = len(other._int) - len(self._int) + context.prec + 1
1249 exp = self._exp - other._exp - shift
1250 op1 = _WorkRep(self)
1251 op2 = _WorkRep(other)
1252 if shift >= 0:
1253 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1254 else:
1255 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1256 if remainder:
1257 # result is not exact; adjust to ensure correct rounding
1258 if coeff % 5 == 0:
1259 coeff += 1
1260 else:
1261 # result is exact; get as close to ideal exponent as possible
1262 ideal_exp = self._exp - other._exp
1263 while exp < ideal_exp and coeff % 10 == 0:
1264 coeff //= 10
1265 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001266
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001267 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001268 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001269
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001270 def _divide(self, other, context):
1271 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001272
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001273 Assumes that neither self nor other is a NaN, that self is not
1274 infinite and that other is nonzero.
1275 """
1276 sign = self._sign ^ other._sign
1277 if other._isinfinity():
1278 ideal_exp = self._exp
1279 else:
1280 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001281
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001282 expdiff = self.adjusted() - other.adjusted()
1283 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001284 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001285 self._rescale(ideal_exp, context.rounding))
1286 if expdiff <= context.prec:
1287 op1 = _WorkRep(self)
1288 op2 = _WorkRep(other)
1289 if op1.exp >= op2.exp:
1290 op1.int *= 10**(op1.exp - op2.exp)
1291 else:
1292 op2.int *= 10**(op2.exp - op1.exp)
1293 q, r = divmod(op1.int, op2.int)
1294 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001295 return (_dec_from_triple(sign, str(q), 0),
1296 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001297
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001298 # Here the quotient is too large to be representable
1299 ans = context._raise_error(DivisionImpossible,
1300 'quotient too large in //, % or divmod')
1301 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001302
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001303 def __rtruediv__(self, other, context=None):
1304 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001305 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001306 if other is NotImplemented:
1307 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001308 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001309
1310 def __divmod__(self, other, context=None):
1311 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001312 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001313 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001314 other = _convert_other(other)
1315 if other is NotImplemented:
1316 return other
1317
1318 if context is None:
1319 context = getcontext()
1320
1321 ans = self._check_nans(other, context)
1322 if ans:
1323 return (ans, ans)
1324
1325 sign = self._sign ^ other._sign
1326 if self._isinfinity():
1327 if other._isinfinity():
1328 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1329 return ans, ans
1330 else:
1331 return (Infsign[sign],
1332 context._raise_error(InvalidOperation, 'INF % x'))
1333
1334 if not other:
1335 if not self:
1336 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1337 return ans, ans
1338 else:
1339 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1340 context._raise_error(InvalidOperation, 'x % 0'))
1341
1342 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001343 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001344 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001345
1346 def __rdivmod__(self, other, context=None):
1347 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001348 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001349 if other is NotImplemented:
1350 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001351 return other.__divmod__(self, context=context)
1352
1353 def __mod__(self, other, context=None):
1354 """
1355 self % other
1356 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001357 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001358 if other is NotImplemented:
1359 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001360
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001361 if context is None:
1362 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001363
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001364 ans = self._check_nans(other, context)
1365 if ans:
1366 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001367
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001368 if self._isinfinity():
1369 return context._raise_error(InvalidOperation, 'INF % x')
1370 elif not other:
1371 if self:
1372 return context._raise_error(InvalidOperation, 'x % 0')
1373 else:
1374 return context._raise_error(DivisionUndefined, '0 % 0')
1375
1376 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001377 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001378 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001379
1380 def __rmod__(self, other, context=None):
1381 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001382 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001383 if other is NotImplemented:
1384 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001385 return other.__mod__(self, context=context)
1386
1387 def remainder_near(self, other, context=None):
1388 """
1389 Remainder nearest to 0- abs(remainder-near) <= other/2
1390 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001391 if context is None:
1392 context = getcontext()
1393
1394 other = _convert_other(other, raiseit=True)
1395
1396 ans = self._check_nans(other, context)
1397 if ans:
1398 return ans
1399
1400 # self == +/-infinity -> InvalidOperation
1401 if self._isinfinity():
1402 return context._raise_error(InvalidOperation,
1403 'remainder_near(infinity, x)')
1404
1405 # other == 0 -> either InvalidOperation or DivisionUndefined
1406 if not other:
1407 if self:
1408 return context._raise_error(InvalidOperation,
1409 'remainder_near(x, 0)')
1410 else:
1411 return context._raise_error(DivisionUndefined,
1412 'remainder_near(0, 0)')
1413
1414 # other = +/-infinity -> remainder = self
1415 if other._isinfinity():
1416 ans = Decimal(self)
1417 return ans._fix(context)
1418
1419 # self = 0 -> remainder = self, with ideal exponent
1420 ideal_exponent = min(self._exp, other._exp)
1421 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001422 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001423 return ans._fix(context)
1424
1425 # catch most cases of large or small quotient
1426 expdiff = self.adjusted() - other.adjusted()
1427 if expdiff >= context.prec + 1:
1428 # expdiff >= prec+1 => abs(self/other) > 10**prec
1429 return context._raise_error(DivisionImpossible)
1430 if expdiff <= -2:
1431 # expdiff <= -2 => abs(self/other) < 0.1
1432 ans = self._rescale(ideal_exponent, context.rounding)
1433 return ans._fix(context)
1434
1435 # adjust both arguments to have the same exponent, then divide
1436 op1 = _WorkRep(self)
1437 op2 = _WorkRep(other)
1438 if op1.exp >= op2.exp:
1439 op1.int *= 10**(op1.exp - op2.exp)
1440 else:
1441 op2.int *= 10**(op2.exp - op1.exp)
1442 q, r = divmod(op1.int, op2.int)
1443 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1444 # 10**ideal_exponent. Apply correction to ensure that
1445 # abs(remainder) <= abs(other)/2
1446 if 2*r + (q&1) > op2.int:
1447 r -= op2.int
1448 q += 1
1449
1450 if q >= 10**context.prec:
1451 return context._raise_error(DivisionImpossible)
1452
1453 # result has same sign as self unless r is negative
1454 sign = self._sign
1455 if r < 0:
1456 sign = 1-sign
1457 r = -r
1458
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001459 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001460 return ans._fix(context)
1461
1462 def __floordiv__(self, other, context=None):
1463 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001464 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001465 if other is NotImplemented:
1466 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001467
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001468 if context is None:
1469 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001470
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001471 ans = self._check_nans(other, context)
1472 if ans:
1473 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001474
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001475 if self._isinfinity():
1476 if other._isinfinity():
1477 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001478 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001479 return Infsign[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001480
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001481 if not other:
1482 if self:
1483 return context._raise_error(DivisionByZero, 'x // 0',
1484 self._sign ^ other._sign)
1485 else:
1486 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001487
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001488 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001489
1490 def __rfloordiv__(self, other, context=None):
1491 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001492 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001493 if other is NotImplemented:
1494 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001495 return other.__floordiv__(self, context=context)
1496
1497 def __float__(self):
1498 """Float representation."""
1499 return float(str(self))
1500
1501 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001502 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001503 if self._is_special:
1504 if self._isnan():
1505 context = getcontext()
1506 return context._raise_error(InvalidContext)
1507 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001508 raise OverflowError("Cannot convert infinity to int")
1509 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001510 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001511 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001512 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001513 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001514
Christian Heimes969fe572008-01-25 11:23:10 +00001515 __trunc__ = __int__
1516
Christian Heimes0bd4e112008-02-12 22:59:25 +00001517 @property
1518 def real(self):
1519 return self
1520
1521 @property
1522 def imag(self):
1523 return Decimal(0)
1524
1525 def conjugate(self):
1526 return self
1527
1528 def __complex__(self):
1529 return complex(float(self))
1530
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001531 def _fix_nan(self, context):
1532 """Decapitate the payload of a NaN to fit the context"""
1533 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001534
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001535 # maximum length of payload is precision if _clamp=0,
1536 # precision-1 if _clamp=1.
1537 max_payload_len = context.prec - context._clamp
1538 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001539 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1540 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001541 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001542
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001543 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001544 """Round if it is necessary to keep self within prec precision.
1545
1546 Rounds and fixes the exponent. Does not raise on a sNaN.
1547
1548 Arguments:
1549 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001550 context - context used.
1551 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001552
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001553 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001554 if self._isnan():
1555 # decapitate payload if necessary
1556 return self._fix_nan(context)
1557 else:
1558 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001559 return Decimal(self)
1560
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001561 # if self is zero then exponent should be between Etiny and
1562 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1563 Etiny = context.Etiny()
1564 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001565 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001566 exp_max = [context.Emax, Etop][context._clamp]
1567 new_exp = min(max(self._exp, Etiny), exp_max)
1568 if new_exp != self._exp:
1569 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001570 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001571 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001572 return Decimal(self)
1573
1574 # exp_min is the smallest allowable exponent of the result,
1575 # equal to max(self.adjusted()-context.prec+1, Etiny)
1576 exp_min = len(self._int) + self._exp - context.prec
1577 if exp_min > Etop:
1578 # overflow: exp_min > Etop iff self.adjusted() > Emax
1579 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001580 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001581 return context._raise_error(Overflow, 'above Emax', self._sign)
1582 self_is_subnormal = exp_min < Etiny
1583 if self_is_subnormal:
1584 context._raise_error(Subnormal)
1585 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001586
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001587 # round if self has too many digits
1588 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001589 context._raise_error(Rounded)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001590 digits = len(self._int) + self._exp - exp_min
1591 if digits < 0:
1592 self = _dec_from_triple(self._sign, '1', exp_min-1)
1593 digits = 0
1594 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1595 changed = this_function(digits)
1596 coeff = self._int[:digits] or '0'
1597 if changed == 1:
1598 coeff = str(int(coeff)+1)
1599 ans = _dec_from_triple(self._sign, coeff, exp_min)
1600
1601 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001602 context._raise_error(Inexact)
1603 if self_is_subnormal:
1604 context._raise_error(Underflow)
1605 if not ans:
1606 # raise Clamped on underflow to 0
1607 context._raise_error(Clamped)
1608 elif len(ans._int) == context.prec+1:
1609 # we get here only if rescaling rounds the
1610 # cofficient up to exactly 10**context.prec
1611 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001612 ans = _dec_from_triple(ans._sign,
1613 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001614 else:
1615 # Inexact and Rounded have already been raised
1616 ans = context._raise_error(Overflow, 'above Emax',
1617 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001618 return ans
1619
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001620 # fold down if _clamp == 1 and self has too few digits
1621 if context._clamp == 1 and self._exp > Etop:
1622 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001623 self_padded = self._int + '0'*(self._exp - Etop)
1624 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001625
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001626 # here self was representable to begin with; return unchanged
1627 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001628
1629 _pick_rounding_function = {}
1630
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001631 # for each of the rounding functions below:
1632 # self is a finite, nonzero Decimal
1633 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001634 #
1635 # each function returns either -1, 0, or 1, as follows:
1636 # 1 indicates that self should be rounded up (away from zero)
1637 # 0 indicates that self should be truncated, and that all the
1638 # digits to be truncated are zeros (so the value is unchanged)
1639 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001640
1641 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001642 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001643 if _all_zeros(self._int, prec):
1644 return 0
1645 else:
1646 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001647
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001648 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001649 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001650 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001651
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001652 def _round_half_up(self, prec):
1653 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001654 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001655 return 1
1656 elif _all_zeros(self._int, prec):
1657 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001658 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001659 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001660
1661 def _round_half_down(self, prec):
1662 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001663 if _exact_half(self._int, prec):
1664 return -1
1665 else:
1666 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001667
1668 def _round_half_even(self, prec):
1669 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001670 if _exact_half(self._int, prec) and \
1671 (prec == 0 or self._int[prec-1] in '02468'):
1672 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001673 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001674 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001675
1676 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001677 """Rounds up (not away from 0 if negative.)"""
1678 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001679 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001680 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001681 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001682
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001683 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001684 """Rounds down (not towards 0 if negative)"""
1685 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001686 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001687 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001688 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001689
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001690 def _round_05up(self, prec):
1691 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001692 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001693 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001694 else:
1695 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001696
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001697 def __round__(self, n=None):
1698 """Round self to the nearest integer, or to a given precision.
1699
1700 If only one argument is supplied, round a finite Decimal
1701 instance self to the nearest integer. If self is infinite or
1702 a NaN then a Python exception is raised. If self is finite
1703 and lies exactly halfway between two integers then it is
1704 rounded to the integer with even last digit.
1705
1706 >>> round(Decimal('123.456'))
1707 123
1708 >>> round(Decimal('-456.789'))
1709 -457
1710 >>> round(Decimal('-3.0'))
1711 -3
1712 >>> round(Decimal('2.5'))
1713 2
1714 >>> round(Decimal('3.5'))
1715 4
1716 >>> round(Decimal('Inf'))
1717 Traceback (most recent call last):
1718 ...
1719 ...
1720 ...
1721 OverflowError: cannot round an infinity
1722 >>> round(Decimal('NaN'))
1723 Traceback (most recent call last):
1724 ...
1725 ...
1726 ...
1727 ValueError: cannot round a NaN
1728
1729 If a second argument n is supplied, self is rounded to n
1730 decimal places using the rounding mode for the current
1731 context.
1732
1733 For an integer n, round(self, -n) is exactly equivalent to
1734 self.quantize(Decimal('1En')).
1735
1736 >>> round(Decimal('123.456'), 0)
1737 Decimal('123')
1738 >>> round(Decimal('123.456'), 2)
1739 Decimal('123.46')
1740 >>> round(Decimal('123.456'), -2)
1741 Decimal('1E+2')
1742 >>> round(Decimal('-Infinity'), 37)
1743 Decimal('NaN')
1744 >>> round(Decimal('sNaN123'), 0)
1745 Decimal('NaN123')
1746
1747 """
1748 if n is not None:
1749 # two-argument form: use the equivalent quantize call
1750 if not isinstance(n, int):
1751 raise TypeError('Second argument to round should be integral')
1752 exp = _dec_from_triple(0, '1', -n)
1753 return self.quantize(exp)
1754
1755 # one-argument form
1756 if self._is_special:
1757 if self.is_nan():
1758 raise ValueError("cannot round a NaN")
1759 else:
1760 raise OverflowError("cannot round an infinity")
1761 return int(self._rescale(0, ROUND_HALF_EVEN))
1762
1763 def __floor__(self):
1764 """Return the floor of self, as an integer.
1765
1766 For a finite Decimal instance self, return the greatest
1767 integer n such that n <= self. If self is infinite or a NaN
1768 then a Python exception is raised.
1769
1770 """
1771 if self._is_special:
1772 if self.is_nan():
1773 raise ValueError("cannot round a NaN")
1774 else:
1775 raise OverflowError("cannot round an infinity")
1776 return int(self._rescale(0, ROUND_FLOOR))
1777
1778 def __ceil__(self):
1779 """Return the ceiling of self, as an integer.
1780
1781 For a finite Decimal instance self, return the least integer n
1782 such that n >= self. If self is infinite or a NaN then a
1783 Python exception is raised.
1784
1785 """
1786 if self._is_special:
1787 if self.is_nan():
1788 raise ValueError("cannot round a NaN")
1789 else:
1790 raise OverflowError("cannot round an infinity")
1791 return int(self._rescale(0, ROUND_CEILING))
1792
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001793 def fma(self, other, third, context=None):
1794 """Fused multiply-add.
1795
1796 Returns self*other+third with no rounding of the intermediate
1797 product self*other.
1798
1799 self and other are multiplied together, with no rounding of
1800 the result. The third operand is then added to the result,
1801 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001802 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001803
1804 other = _convert_other(other, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001805
1806 # compute product; raise InvalidOperation if either operand is
1807 # a signaling NaN or if the product is zero times infinity.
1808 if self._is_special or other._is_special:
1809 if context is None:
1810 context = getcontext()
1811 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001812 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001813 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001814 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001815 if self._exp == 'n':
1816 product = self
1817 elif other._exp == 'n':
1818 product = other
1819 elif self._exp == 'F':
1820 if not other:
1821 return context._raise_error(InvalidOperation,
1822 'INF * 0 in fma')
1823 product = Infsign[self._sign ^ other._sign]
1824 elif other._exp == 'F':
1825 if not self:
1826 return context._raise_error(InvalidOperation,
1827 '0 * INF in fma')
1828 product = Infsign[self._sign ^ other._sign]
1829 else:
1830 product = _dec_from_triple(self._sign ^ other._sign,
1831 str(int(self._int) * int(other._int)),
1832 self._exp + other._exp)
1833
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001834 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001835 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001836
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001837 def _power_modulo(self, other, modulo, context=None):
1838 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001839
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001840 # if can't convert other and modulo to Decimal, raise
1841 # TypeError; there's no point returning NotImplemented (no
1842 # equivalent of __rpow__ for three argument pow)
1843 other = _convert_other(other, raiseit=True)
1844 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001845
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001846 if context is None:
1847 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001848
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001849 # deal with NaNs: if there are any sNaNs then first one wins,
1850 # (i.e. behaviour for NaNs is identical to that of fma)
1851 self_is_nan = self._isnan()
1852 other_is_nan = other._isnan()
1853 modulo_is_nan = modulo._isnan()
1854 if self_is_nan or other_is_nan or modulo_is_nan:
1855 if self_is_nan == 2:
1856 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001857 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001858 if other_is_nan == 2:
1859 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001860 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001861 if modulo_is_nan == 2:
1862 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001863 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001864 if self_is_nan:
1865 return self._fix_nan(context)
1866 if other_is_nan:
1867 return other._fix_nan(context)
1868 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001869
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001870 # check inputs: we apply same restrictions as Python's pow()
1871 if not (self._isinteger() and
1872 other._isinteger() and
1873 modulo._isinteger()):
1874 return context._raise_error(InvalidOperation,
1875 'pow() 3rd argument not allowed '
1876 'unless all arguments are integers')
1877 if other < 0:
1878 return context._raise_error(InvalidOperation,
1879 'pow() 2nd argument cannot be '
1880 'negative when 3rd argument specified')
1881 if not modulo:
1882 return context._raise_error(InvalidOperation,
1883 'pow() 3rd argument cannot be 0')
1884
1885 # additional restriction for decimal: the modulus must be less
1886 # than 10**prec in absolute value
1887 if modulo.adjusted() >= context.prec:
1888 return context._raise_error(InvalidOperation,
1889 'insufficient precision: pow() 3rd '
1890 'argument must not have more than '
1891 'precision digits')
1892
1893 # define 0**0 == NaN, for consistency with two-argument pow
1894 # (even though it hurts!)
1895 if not other and not self:
1896 return context._raise_error(InvalidOperation,
1897 'at least one of pow() 1st argument '
1898 'and 2nd argument must be nonzero ;'
1899 '0**0 is not defined')
1900
1901 # compute sign of result
1902 if other._iseven():
1903 sign = 0
1904 else:
1905 sign = self._sign
1906
1907 # convert modulo to a Python integer, and self and other to
1908 # Decimal integers (i.e. force their exponents to be >= 0)
1909 modulo = abs(int(modulo))
1910 base = _WorkRep(self.to_integral_value())
1911 exponent = _WorkRep(other.to_integral_value())
1912
1913 # compute result using integer pow()
1914 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1915 for i in range(exponent.exp):
1916 base = pow(base, 10, modulo)
1917 base = pow(base, exponent.int, modulo)
1918
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001919 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001920
1921 def _power_exact(self, other, p):
1922 """Attempt to compute self**other exactly.
1923
1924 Given Decimals self and other and an integer p, attempt to
1925 compute an exact result for the power self**other, with p
1926 digits of precision. Return None if self**other is not
1927 exactly representable in p digits.
1928
1929 Assumes that elimination of special cases has already been
1930 performed: self and other must both be nonspecial; self must
1931 be positive and not numerically equal to 1; other must be
1932 nonzero. For efficiency, other._exp should not be too large,
1933 so that 10**abs(other._exp) is a feasible calculation."""
1934
1935 # In the comments below, we write x for the value of self and
1936 # y for the value of other. Write x = xc*10**xe and y =
1937 # yc*10**ye.
1938
1939 # The main purpose of this method is to identify the *failure*
1940 # of x**y to be exactly representable with as little effort as
1941 # possible. So we look for cheap and easy tests that
1942 # eliminate the possibility of x**y being exact. Only if all
1943 # these tests are passed do we go on to actually compute x**y.
1944
1945 # Here's the main idea. First normalize both x and y. We
1946 # express y as a rational m/n, with m and n relatively prime
1947 # and n>0. Then for x**y to be exactly representable (at
1948 # *any* precision), xc must be the nth power of a positive
1949 # integer and xe must be divisible by n. If m is negative
1950 # then additionally xc must be a power of either 2 or 5, hence
1951 # a power of 2**n or 5**n.
1952 #
1953 # There's a limit to how small |y| can be: if y=m/n as above
1954 # then:
1955 #
1956 # (1) if xc != 1 then for the result to be representable we
1957 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1958 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1959 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1960 # representable.
1961 #
1962 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1963 # |y| < 1/|xe| then the result is not representable.
1964 #
1965 # Note that since x is not equal to 1, at least one of (1) and
1966 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1967 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1968 #
1969 # There's also a limit to how large y can be, at least if it's
1970 # positive: the normalized result will have coefficient xc**y,
1971 # so if it's representable then xc**y < 10**p, and y <
1972 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1973 # not exactly representable.
1974
1975 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1976 # so |y| < 1/xe and the result is not representable.
1977 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1978 # < 1/nbits(xc).
1979
1980 x = _WorkRep(self)
1981 xc, xe = x.int, x.exp
1982 while xc % 10 == 0:
1983 xc //= 10
1984 xe += 1
1985
1986 y = _WorkRep(other)
1987 yc, ye = y.int, y.exp
1988 while yc % 10 == 0:
1989 yc //= 10
1990 ye += 1
1991
1992 # case where xc == 1: result is 10**(xe*y), with xe*y
1993 # required to be an integer
1994 if xc == 1:
1995 if ye >= 0:
1996 exponent = xe*yc*10**ye
1997 else:
1998 exponent, remainder = divmod(xe*yc, 10**-ye)
1999 if remainder:
2000 return None
2001 if y.sign == 1:
2002 exponent = -exponent
2003 # if other is a nonnegative integer, use ideal exponent
2004 if other._isinteger() and other._sign == 0:
2005 ideal_exponent = self._exp*int(other)
2006 zeros = min(exponent-ideal_exponent, p-1)
2007 else:
2008 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002009 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002010
2011 # case where y is negative: xc must be either a power
2012 # of 2 or a power of 5.
2013 if y.sign == 1:
2014 last_digit = xc % 10
2015 if last_digit in (2,4,6,8):
2016 # quick test for power of 2
2017 if xc & -xc != xc:
2018 return None
2019 # now xc is a power of 2; e is its exponent
2020 e = _nbits(xc)-1
2021 # find e*y and xe*y; both must be integers
2022 if ye >= 0:
2023 y_as_int = yc*10**ye
2024 e = e*y_as_int
2025 xe = xe*y_as_int
2026 else:
2027 ten_pow = 10**-ye
2028 e, remainder = divmod(e*yc, ten_pow)
2029 if remainder:
2030 return None
2031 xe, remainder = divmod(xe*yc, ten_pow)
2032 if remainder:
2033 return None
2034
2035 if e*65 >= p*93: # 93/65 > log(10)/log(5)
2036 return None
2037 xc = 5**e
2038
2039 elif last_digit == 5:
2040 # e >= log_5(xc) if xc is a power of 5; we have
2041 # equality all the way up to xc=5**2658
2042 e = _nbits(xc)*28//65
2043 xc, remainder = divmod(5**e, xc)
2044 if remainder:
2045 return None
2046 while xc % 5 == 0:
2047 xc //= 5
2048 e -= 1
2049 if ye >= 0:
2050 y_as_integer = yc*10**ye
2051 e = e*y_as_integer
2052 xe = xe*y_as_integer
2053 else:
2054 ten_pow = 10**-ye
2055 e, remainder = divmod(e*yc, ten_pow)
2056 if remainder:
2057 return None
2058 xe, remainder = divmod(xe*yc, ten_pow)
2059 if remainder:
2060 return None
2061 if e*3 >= p*10: # 10/3 > log(10)/log(2)
2062 return None
2063 xc = 2**e
2064 else:
2065 return None
2066
2067 if xc >= 10**p:
2068 return None
2069 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002070 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002071
2072 # now y is positive; find m and n such that y = m/n
2073 if ye >= 0:
2074 m, n = yc*10**ye, 1
2075 else:
2076 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2077 return None
2078 xc_bits = _nbits(xc)
2079 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2080 return None
2081 m, n = yc, 10**(-ye)
2082 while m % 2 == n % 2 == 0:
2083 m //= 2
2084 n //= 2
2085 while m % 5 == n % 5 == 0:
2086 m //= 5
2087 n //= 5
2088
2089 # compute nth root of xc*10**xe
2090 if n > 1:
2091 # if 1 < xc < 2**n then xc isn't an nth power
2092 if xc != 1 and xc_bits <= n:
2093 return None
2094
2095 xe, rem = divmod(xe, n)
2096 if rem != 0:
2097 return None
2098
2099 # compute nth root of xc using Newton's method
2100 a = 1 << -(-_nbits(xc)//n) # initial estimate
2101 while True:
2102 q, r = divmod(xc, a**(n-1))
2103 if a <= q:
2104 break
2105 else:
2106 a = (a*(n-1) + q)//n
2107 if not (a == q and r == 0):
2108 return None
2109 xc = a
2110
2111 # now xc*10**xe is the nth root of the original xc*10**xe
2112 # compute mth power of xc*10**xe
2113
2114 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2115 # 10**p and the result is not representable.
2116 if xc > 1 and m > p*100//_log10_lb(xc):
2117 return None
2118 xc = xc**m
2119 xe *= m
2120 if xc > 10**p:
2121 return None
2122
2123 # by this point the result *is* exactly representable
2124 # adjust the exponent to get as close as possible to the ideal
2125 # exponent, if necessary
2126 str_xc = str(xc)
2127 if other._isinteger() and other._sign == 0:
2128 ideal_exponent = self._exp*int(other)
2129 zeros = min(xe-ideal_exponent, p-len(str_xc))
2130 else:
2131 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002132 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002133
2134 def __pow__(self, other, modulo=None, context=None):
2135 """Return self ** other [ % modulo].
2136
2137 With two arguments, compute self**other.
2138
2139 With three arguments, compute (self**other) % modulo. For the
2140 three argument form, the following restrictions on the
2141 arguments hold:
2142
2143 - all three arguments must be integral
2144 - other must be nonnegative
2145 - either self or other (or both) must be nonzero
2146 - modulo must be nonzero and must have at most p digits,
2147 where p is the context precision.
2148
2149 If any of these restrictions is violated the InvalidOperation
2150 flag is raised.
2151
2152 The result of pow(self, other, modulo) is identical to the
2153 result that would be obtained by computing (self**other) %
2154 modulo with unbounded precision, but is computed more
2155 efficiently. It is always exact.
2156 """
2157
2158 if modulo is not None:
2159 return self._power_modulo(other, modulo, context)
2160
2161 other = _convert_other(other)
2162 if other is NotImplemented:
2163 return other
2164
2165 if context is None:
2166 context = getcontext()
2167
2168 # either argument is a NaN => result is NaN
2169 ans = self._check_nans(other, context)
2170 if ans:
2171 return ans
2172
2173 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2174 if not other:
2175 if not self:
2176 return context._raise_error(InvalidOperation, '0 ** 0')
2177 else:
2178 return Dec_p1
2179
2180 # result has sign 1 iff self._sign is 1 and other is an odd integer
2181 result_sign = 0
2182 if self._sign == 1:
2183 if other._isinteger():
2184 if not other._iseven():
2185 result_sign = 1
2186 else:
2187 # -ve**noninteger = NaN
2188 # (-0)**noninteger = 0**noninteger
2189 if self:
2190 return context._raise_error(InvalidOperation,
2191 'x ** y with x negative and y not an integer')
2192 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002193 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002194
2195 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2196 if not self:
2197 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002198 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002199 else:
2200 return Infsign[result_sign]
2201
2202 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002203 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002204 if other._sign == 0:
2205 return Infsign[result_sign]
2206 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002207 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002208
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002209 # 1**other = 1, but the choice of exponent and the flags
2210 # depend on the exponent of self, and on whether other is a
2211 # positive integer, a negative integer, or neither
2212 if self == Dec_p1:
2213 if other._isinteger():
2214 # exp = max(self._exp*max(int(other), 0),
2215 # 1-context.prec) but evaluating int(other) directly
2216 # is dangerous until we know other is small (other
2217 # could be 1e999999999)
2218 if other._sign == 1:
2219 multiplier = 0
2220 elif other > context.prec:
2221 multiplier = context.prec
2222 else:
2223 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002224
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002225 exp = self._exp * multiplier
2226 if exp < 1-context.prec:
2227 exp = 1-context.prec
2228 context._raise_error(Rounded)
2229 else:
2230 context._raise_error(Inexact)
2231 context._raise_error(Rounded)
2232 exp = 1-context.prec
2233
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002234 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002235
2236 # compute adjusted exponent of self
2237 self_adj = self.adjusted()
2238
2239 # self ** infinity is infinity if self > 1, 0 if self < 1
2240 # self ** -infinity is infinity if self < 1, 0 if self > 1
2241 if other._isinfinity():
2242 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002243 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002244 else:
2245 return Infsign[result_sign]
2246
2247 # from here on, the result always goes through the call
2248 # to _fix at the end of this function.
2249 ans = None
2250
2251 # crude test to catch cases of extreme overflow/underflow. If
2252 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2253 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2254 # self**other >= 10**(Emax+1), so overflow occurs. The test
2255 # for underflow is similar.
2256 bound = self._log10_exp_bound() + other.adjusted()
2257 if (self_adj >= 0) == (other._sign == 0):
2258 # self > 1 and other +ve, or self < 1 and other -ve
2259 # possibility of overflow
2260 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002261 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002262 else:
2263 # self > 1 and other -ve, or self < 1 and other +ve
2264 # possibility of underflow to 0
2265 Etiny = context.Etiny()
2266 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002267 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002268
2269 # try for an exact result with precision +1
2270 if ans is None:
2271 ans = self._power_exact(other, context.prec + 1)
2272 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002273 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002274
2275 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2276 if ans is None:
2277 p = context.prec
2278 x = _WorkRep(self)
2279 xc, xe = x.int, x.exp
2280 y = _WorkRep(other)
2281 yc, ye = y.int, y.exp
2282 if y.sign == 1:
2283 yc = -yc
2284
2285 # compute correctly rounded result: start with precision +3,
2286 # then increase precision until result is unambiguously roundable
2287 extra = 3
2288 while True:
2289 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2290 if coeff % (5*10**(len(str(coeff))-p-1)):
2291 break
2292 extra += 3
2293
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002294 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002295
2296 # the specification says that for non-integer other we need to
2297 # raise Inexact, even when the result is actually exact. In
2298 # the same way, we need to raise Underflow here if the result
2299 # is subnormal. (The call to _fix will take care of raising
2300 # Rounded and Subnormal, as usual.)
2301 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002302 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002303 # pad with zeros up to length context.prec+1 if necessary
2304 if len(ans._int) <= context.prec:
2305 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002306 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2307 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002308 if ans.adjusted() < context.Emin:
2309 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002310
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002311 # unlike exp, ln and log10, the power function respects the
2312 # rounding mode; no need to use ROUND_HALF_EVEN here
2313 ans = ans._fix(context)
2314 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002315
2316 def __rpow__(self, other, context=None):
2317 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002318 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002319 if other is NotImplemented:
2320 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002321 return other.__pow__(self, context=context)
2322
2323 def normalize(self, context=None):
2324 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002325
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002326 if context is None:
2327 context = getcontext()
2328
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002329 if self._is_special:
2330 ans = self._check_nans(context=context)
2331 if ans:
2332 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002333
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002334 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002335 if dup._isinfinity():
2336 return dup
2337
2338 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002339 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002340 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002341 end = len(dup._int)
2342 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002343 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002344 exp += 1
2345 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002346 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002347
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002348 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002349 """Quantize self so its exponent is the same as that of exp.
2350
2351 Similar to self._rescale(exp._exp) but with error checking.
2352 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002353 exp = _convert_other(exp, raiseit=True)
2354
2355 if context is None:
2356 context = getcontext()
2357 if rounding is None:
2358 rounding = context.rounding
2359
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002360 if self._is_special or exp._is_special:
2361 ans = self._check_nans(exp, context)
2362 if ans:
2363 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002364
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002365 if exp._isinfinity() or self._isinfinity():
2366 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002367 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002368 return context._raise_error(InvalidOperation,
2369 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002370
2371 # if we're not watching exponents, do a simple rescale
2372 if not watchexp:
2373 ans = self._rescale(exp._exp, rounding)
2374 # raise Inexact and Rounded where appropriate
2375 if ans._exp > self._exp:
2376 context._raise_error(Rounded)
2377 if ans != self:
2378 context._raise_error(Inexact)
2379 return ans
2380
2381 # exp._exp should be between Etiny and Emax
2382 if not (context.Etiny() <= exp._exp <= context.Emax):
2383 return context._raise_error(InvalidOperation,
2384 'target exponent out of bounds in quantize')
2385
2386 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002387 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002388 return ans._fix(context)
2389
2390 self_adjusted = self.adjusted()
2391 if self_adjusted > context.Emax:
2392 return context._raise_error(InvalidOperation,
2393 'exponent of quantize result too large for current context')
2394 if self_adjusted - exp._exp + 1 > context.prec:
2395 return context._raise_error(InvalidOperation,
2396 'quantize result has too many digits for current context')
2397
2398 ans = self._rescale(exp._exp, rounding)
2399 if ans.adjusted() > context.Emax:
2400 return context._raise_error(InvalidOperation,
2401 'exponent of quantize result too large for current context')
2402 if len(ans._int) > context.prec:
2403 return context._raise_error(InvalidOperation,
2404 'quantize result has too many digits for current context')
2405
2406 # raise appropriate flags
2407 if ans._exp > self._exp:
2408 context._raise_error(Rounded)
2409 if ans != self:
2410 context._raise_error(Inexact)
2411 if ans and ans.adjusted() < context.Emin:
2412 context._raise_error(Subnormal)
2413
2414 # call to fix takes care of any necessary folddown
2415 ans = ans._fix(context)
2416 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002417
2418 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002419 """Return True if self and other have the same exponent; otherwise
2420 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002421
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002422 If either operand is a special value, the following rules are used:
2423 * return True if both operands are infinities
2424 * return True if both operands are NaNs
2425 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002426 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002427 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002428 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002429 return (self.is_nan() and other.is_nan() or
2430 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002431 return self._exp == other._exp
2432
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002433 def _rescale(self, exp, rounding):
2434 """Rescale self so that the exponent is exp, either by padding with zeros
2435 or by truncating digits, using the given rounding mode.
2436
2437 Specials are returned without change. This operation is
2438 quiet: it raises no flags, and uses no information from the
2439 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002440
2441 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002442 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002443 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002444 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002445 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002446 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002447 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002448
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002449 if self._exp >= exp:
2450 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002451 return _dec_from_triple(self._sign,
2452 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002453
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002454 # too many digits; round and lose data. If self.adjusted() <
2455 # exp-1, replace self by 10**(exp-1) before rounding
2456 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002457 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002458 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002459 digits = 0
2460 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002461 changed = this_function(digits)
2462 coeff = self._int[:digits] or '0'
2463 if changed == 1:
2464 coeff = str(int(coeff)+1)
2465 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002466
Christian Heimesf16baeb2008-02-29 14:57:44 +00002467 def _round(self, places, rounding):
2468 """Round a nonzero, nonspecial Decimal to a fixed number of
2469 significant figures, using the given rounding mode.
2470
2471 Infinities, NaNs and zeros are returned unaltered.
2472
2473 This operation is quiet: it raises no flags, and uses no
2474 information from the context.
2475
2476 """
2477 if places <= 0:
2478 raise ValueError("argument should be at least 1 in _round")
2479 if self._is_special or not self:
2480 return Decimal(self)
2481 ans = self._rescale(self.adjusted()+1-places, rounding)
2482 # it can happen that the rescale alters the adjusted exponent;
2483 # for example when rounding 99.97 to 3 significant figures.
2484 # When this happens we end up with an extra 0 at the end of
2485 # the number; a second rescale fixes this.
2486 if ans.adjusted() != self.adjusted():
2487 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2488 return ans
2489
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002490 def to_integral_exact(self, rounding=None, context=None):
2491 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002492
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002493 If no rounding mode is specified, take the rounding mode from
2494 the context. This method raises the Rounded and Inexact flags
2495 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002496
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002497 See also: to_integral_value, which does exactly the same as
2498 this method except that it doesn't raise Inexact or Rounded.
2499 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002500 if self._is_special:
2501 ans = self._check_nans(context=context)
2502 if ans:
2503 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002504 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002505 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002506 return Decimal(self)
2507 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002508 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002509 if context is None:
2510 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002511 if rounding is None:
2512 rounding = context.rounding
2513 context._raise_error(Rounded)
2514 ans = self._rescale(0, rounding)
2515 if ans != self:
2516 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002517 return ans
2518
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002519 def to_integral_value(self, rounding=None, context=None):
2520 """Rounds to the nearest integer, without raising inexact, rounded."""
2521 if context is None:
2522 context = getcontext()
2523 if rounding is None:
2524 rounding = context.rounding
2525 if self._is_special:
2526 ans = self._check_nans(context=context)
2527 if ans:
2528 return ans
2529 return Decimal(self)
2530 if self._exp >= 0:
2531 return Decimal(self)
2532 else:
2533 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002534
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002535 # the method name changed, but we provide also the old one, for compatibility
2536 to_integral = to_integral_value
2537
2538 def sqrt(self, context=None):
2539 """Return the square root of self."""
Christian Heimes0348fb62008-03-26 12:55:56 +00002540 if context is None:
2541 context = getcontext()
2542
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002543 if self._is_special:
2544 ans = self._check_nans(context=context)
2545 if ans:
2546 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002547
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002548 if self._isinfinity() and self._sign == 0:
2549 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002550
2551 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002552 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002553 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002554 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002555
2556 if self._sign == 1:
2557 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2558
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002559 # At this point self represents a positive number. Let p be
2560 # the desired precision and express self in the form c*100**e
2561 # with c a positive real number and e an integer, c and e
2562 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2563 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2564 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2565 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2566 # the closest integer to sqrt(c) with the even integer chosen
2567 # in the case of a tie.
2568 #
2569 # To ensure correct rounding in all cases, we use the
2570 # following trick: we compute the square root to an extra
2571 # place (precision p+1 instead of precision p), rounding down.
2572 # Then, if the result is inexact and its last digit is 0 or 5,
2573 # we increase the last digit to 1 or 6 respectively; if it's
2574 # exact we leave the last digit alone. Now the final round to
2575 # p places (or fewer in the case of underflow) will round
2576 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002577
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002578 # use an extra digit of precision
2579 prec = context.prec+1
2580
2581 # write argument in the form c*100**e where e = self._exp//2
2582 # is the 'ideal' exponent, to be used if the square root is
2583 # exactly representable. l is the number of 'digits' of c in
2584 # base 100, so that 100**(l-1) <= c < 100**l.
2585 op = _WorkRep(self)
2586 e = op.exp >> 1
2587 if op.exp & 1:
2588 c = op.int * 10
2589 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002590 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002591 c = op.int
2592 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002593
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002594 # rescale so that c has exactly prec base 100 'digits'
2595 shift = prec-l
2596 if shift >= 0:
2597 c *= 100**shift
2598 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002599 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002600 c, remainder = divmod(c, 100**-shift)
2601 exact = not remainder
2602 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002603
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002604 # find n = floor(sqrt(c)) using Newton's method
2605 n = 10**prec
2606 while True:
2607 q = c//n
2608 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002609 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002610 else:
2611 n = n + q >> 1
2612 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002613
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002614 if exact:
2615 # result is exact; rescale to use ideal exponent e
2616 if shift >= 0:
2617 # assert n % 10**shift == 0
2618 n //= 10**shift
2619 else:
2620 n *= 10**-shift
2621 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002622 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002623 # result is not exact; fix last digit as described above
2624 if n % 5 == 0:
2625 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002626
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002627 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002628
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002629 # round, and fit to current context
2630 context = context._shallow_copy()
2631 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002632 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002633 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002634
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002635 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002636
2637 def max(self, other, context=None):
2638 """Returns the larger value.
2639
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002640 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002641 NaN (and signals if one is sNaN). Also rounds.
2642 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002643 other = _convert_other(other, raiseit=True)
2644
2645 if context is None:
2646 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002647
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002648 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002649 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002650 # number is always returned
2651 sn = self._isnan()
2652 on = other._isnan()
2653 if sn or on:
2654 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002655 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002656 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002657 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002658 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002659
Christian Heimes77c02eb2008-02-09 02:18:51 +00002660 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002661 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002662 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002663 # then an ordering is applied:
2664 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002665 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002666 # positive sign and min returns the operand with the negative sign
2667 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002668 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002669 # the result. This is exactly the ordering used in compare_total.
2670 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002671
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002672 if c == -1:
2673 ans = other
2674 else:
2675 ans = self
2676
Christian Heimes2c181612007-12-17 20:04:13 +00002677 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002678
2679 def min(self, other, context=None):
2680 """Returns the smaller value.
2681
Guido van Rossumd8faa362007-04-27 19:54:29 +00002682 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002683 NaN (and signals if one is sNaN). Also rounds.
2684 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002685 other = _convert_other(other, raiseit=True)
2686
2687 if context is None:
2688 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002689
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002690 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002691 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002692 # number is always returned
2693 sn = self._isnan()
2694 on = other._isnan()
2695 if sn or on:
2696 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002697 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002698 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002699 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002700 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002701
Christian Heimes77c02eb2008-02-09 02:18:51 +00002702 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002703 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002704 c = self.compare_total(other)
2705
2706 if c == -1:
2707 ans = self
2708 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002709 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002710
Christian Heimes2c181612007-12-17 20:04:13 +00002711 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002712
2713 def _isinteger(self):
2714 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002715 if self._is_special:
2716 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002717 if self._exp >= 0:
2718 return True
2719 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002720 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002721
2722 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002723 """Returns True if self is even. Assumes self is an integer."""
2724 if not self or self._exp > 0:
2725 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002726 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002727
2728 def adjusted(self):
2729 """Return the adjusted exponent of self"""
2730 try:
2731 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002732 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002733 except TypeError:
2734 return 0
2735
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002736 def canonical(self, context=None):
2737 """Returns the same Decimal object.
2738
2739 As we do not have different encodings for the same number, the
2740 received object already is in its canonical form.
2741 """
2742 return self
2743
2744 def compare_signal(self, other, context=None):
2745 """Compares self to the other operand numerically.
2746
2747 It's pretty much like compare(), but all NaNs signal, with signaling
2748 NaNs taking precedence over quiet NaNs.
2749 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002750 other = _convert_other(other, raiseit = True)
2751 ans = self._compare_check_nans(other, context)
2752 if ans:
2753 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002754 return self.compare(other, context=context)
2755
2756 def compare_total(self, other):
2757 """Compares self to other using the abstract representations.
2758
2759 This is not like the standard compare, which use their numerical
2760 value. Note that a total ordering is defined for all possible abstract
2761 representations.
2762 """
2763 # if one is negative and the other is positive, it's easy
2764 if self._sign and not other._sign:
2765 return Dec_n1
2766 if not self._sign and other._sign:
2767 return Dec_p1
2768 sign = self._sign
2769
2770 # let's handle both NaN types
2771 self_nan = self._isnan()
2772 other_nan = other._isnan()
2773 if self_nan or other_nan:
2774 if self_nan == other_nan:
2775 if self._int < other._int:
2776 if sign:
2777 return Dec_p1
2778 else:
2779 return Dec_n1
2780 if self._int > other._int:
2781 if sign:
2782 return Dec_n1
2783 else:
2784 return Dec_p1
2785 return Dec_0
2786
2787 if sign:
2788 if self_nan == 1:
2789 return Dec_n1
2790 if other_nan == 1:
2791 return Dec_p1
2792 if self_nan == 2:
2793 return Dec_n1
2794 if other_nan == 2:
2795 return Dec_p1
2796 else:
2797 if self_nan == 1:
2798 return Dec_p1
2799 if other_nan == 1:
2800 return Dec_n1
2801 if self_nan == 2:
2802 return Dec_p1
2803 if other_nan == 2:
2804 return Dec_n1
2805
2806 if self < other:
2807 return Dec_n1
2808 if self > other:
2809 return Dec_p1
2810
2811 if self._exp < other._exp:
2812 if sign:
2813 return Dec_p1
2814 else:
2815 return Dec_n1
2816 if self._exp > other._exp:
2817 if sign:
2818 return Dec_n1
2819 else:
2820 return Dec_p1
2821 return Dec_0
2822
2823
2824 def compare_total_mag(self, other):
2825 """Compares self to other using abstract repr., ignoring sign.
2826
2827 Like compare_total, but with operand's sign ignored and assumed to be 0.
2828 """
2829 s = self.copy_abs()
2830 o = other.copy_abs()
2831 return s.compare_total(o)
2832
2833 def copy_abs(self):
2834 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002835 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002836
2837 def copy_negate(self):
2838 """Returns a copy with the sign inverted."""
2839 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002840 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002841 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002842 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002843
2844 def copy_sign(self, other):
2845 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002846 return _dec_from_triple(other._sign, self._int,
2847 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002848
2849 def exp(self, context=None):
2850 """Returns e ** self."""
2851
2852 if context is None:
2853 context = getcontext()
2854
2855 # exp(NaN) = NaN
2856 ans = self._check_nans(context=context)
2857 if ans:
2858 return ans
2859
2860 # exp(-Infinity) = 0
2861 if self._isinfinity() == -1:
2862 return Dec_0
2863
2864 # exp(0) = 1
2865 if not self:
2866 return Dec_p1
2867
2868 # exp(Infinity) = Infinity
2869 if self._isinfinity() == 1:
2870 return Decimal(self)
2871
2872 # the result is now guaranteed to be inexact (the true
2873 # mathematical result is transcendental). There's no need to
2874 # raise Rounded and Inexact here---they'll always be raised as
2875 # a result of the call to _fix.
2876 p = context.prec
2877 adj = self.adjusted()
2878
2879 # we only need to do any computation for quite a small range
2880 # of adjusted exponents---for example, -29 <= adj <= 10 for
2881 # the default context. For smaller exponent the result is
2882 # indistinguishable from 1 at the given precision, while for
2883 # larger exponent the result either overflows or underflows.
2884 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2885 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002886 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002887 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2888 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002889 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002890 elif self._sign == 0 and adj < -p:
2891 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002892 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002893 elif self._sign == 1 and adj < -p-1:
2894 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002895 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002896 # general case
2897 else:
2898 op = _WorkRep(self)
2899 c, e = op.int, op.exp
2900 if op.sign == 1:
2901 c = -c
2902
2903 # compute correctly rounded result: increase precision by
2904 # 3 digits at a time until we get an unambiguously
2905 # roundable result
2906 extra = 3
2907 while True:
2908 coeff, exp = _dexp(c, e, p+extra)
2909 if coeff % (5*10**(len(str(coeff))-p-1)):
2910 break
2911 extra += 3
2912
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002913 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002914
2915 # at this stage, ans should round correctly with *any*
2916 # rounding mode, not just with ROUND_HALF_EVEN
2917 context = context._shallow_copy()
2918 rounding = context._set_rounding(ROUND_HALF_EVEN)
2919 ans = ans._fix(context)
2920 context.rounding = rounding
2921
2922 return ans
2923
2924 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002925 """Return True if self is canonical; otherwise return False.
2926
2927 Currently, the encoding of a Decimal instance is always
2928 canonical, so this method returns True for any Decimal.
2929 """
2930 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002931
2932 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002933 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002934
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002935 A Decimal instance is considered finite if it is neither
2936 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002937 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002938 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002939
2940 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002941 """Return True if self is infinite; otherwise return False."""
2942 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002943
2944 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002945 """Return True if self is a qNaN or sNaN; otherwise return False."""
2946 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002947
2948 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002949 """Return True if self is a normal number; otherwise return False."""
2950 if self._is_special or not self:
2951 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002952 if context is None:
2953 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002954 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002955
2956 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002957 """Return True if self is a quiet NaN; otherwise return False."""
2958 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002959
2960 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002961 """Return True if self is negative; otherwise return False."""
2962 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002963
2964 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002965 """Return True if self is a signaling NaN; otherwise return False."""
2966 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002967
2968 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002969 """Return True if self is subnormal; otherwise return False."""
2970 if self._is_special or not self:
2971 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002972 if context is None:
2973 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002974 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002975
2976 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002977 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002978 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002979
2980 def _ln_exp_bound(self):
2981 """Compute a lower bound for the adjusted exponent of self.ln().
2982 In other words, compute r such that self.ln() >= 10**r. Assumes
2983 that self is finite and positive and that self != 1.
2984 """
2985
2986 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2987 adj = self._exp + len(self._int) - 1
2988 if adj >= 1:
2989 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2990 return len(str(adj*23//10)) - 1
2991 if adj <= -2:
2992 # argument <= 0.1
2993 return len(str((-1-adj)*23//10)) - 1
2994 op = _WorkRep(self)
2995 c, e = op.int, op.exp
2996 if adj == 0:
2997 # 1 < self < 10
2998 num = str(c-10**-e)
2999 den = str(c)
3000 return len(num) - len(den) - (num < den)
3001 # adj == -1, 0.1 <= self < 1
3002 return e + len(str(10**-e - c)) - 1
3003
3004
3005 def ln(self, context=None):
3006 """Returns the natural (base e) logarithm of self."""
3007
3008 if context is None:
3009 context = getcontext()
3010
3011 # ln(NaN) = NaN
3012 ans = self._check_nans(context=context)
3013 if ans:
3014 return ans
3015
3016 # ln(0.0) == -Infinity
3017 if not self:
3018 return negInf
3019
3020 # ln(Infinity) = Infinity
3021 if self._isinfinity() == 1:
3022 return Inf
3023
3024 # ln(1.0) == 0.0
3025 if self == Dec_p1:
3026 return Dec_0
3027
3028 # ln(negative) raises InvalidOperation
3029 if self._sign == 1:
3030 return context._raise_error(InvalidOperation,
3031 'ln of a negative value')
3032
3033 # result is irrational, so necessarily inexact
3034 op = _WorkRep(self)
3035 c, e = op.int, op.exp
3036 p = context.prec
3037
3038 # correctly rounded result: repeatedly increase precision by 3
3039 # until we get an unambiguously roundable result
3040 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3041 while True:
3042 coeff = _dlog(c, e, places)
3043 # assert len(str(abs(coeff)))-p >= 1
3044 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3045 break
3046 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003047 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003048
3049 context = context._shallow_copy()
3050 rounding = context._set_rounding(ROUND_HALF_EVEN)
3051 ans = ans._fix(context)
3052 context.rounding = rounding
3053 return ans
3054
3055 def _log10_exp_bound(self):
3056 """Compute a lower bound for the adjusted exponent of self.log10().
3057 In other words, find r such that self.log10() >= 10**r.
3058 Assumes that self is finite and positive and that self != 1.
3059 """
3060
3061 # For x >= 10 or x < 0.1 we only need a bound on the integer
3062 # part of log10(self), and this comes directly from the
3063 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3064 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3065 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3066
3067 adj = self._exp + len(self._int) - 1
3068 if adj >= 1:
3069 # self >= 10
3070 return len(str(adj))-1
3071 if adj <= -2:
3072 # self < 0.1
3073 return len(str(-1-adj))-1
3074 op = _WorkRep(self)
3075 c, e = op.int, op.exp
3076 if adj == 0:
3077 # 1 < self < 10
3078 num = str(c-10**-e)
3079 den = str(231*c)
3080 return len(num) - len(den) - (num < den) + 2
3081 # adj == -1, 0.1 <= self < 1
3082 num = str(10**-e-c)
3083 return len(num) + e - (num < "231") - 1
3084
3085 def log10(self, context=None):
3086 """Returns the base 10 logarithm of self."""
3087
3088 if context is None:
3089 context = getcontext()
3090
3091 # log10(NaN) = NaN
3092 ans = self._check_nans(context=context)
3093 if ans:
3094 return ans
3095
3096 # log10(0.0) == -Infinity
3097 if not self:
3098 return negInf
3099
3100 # log10(Infinity) = Infinity
3101 if self._isinfinity() == 1:
3102 return Inf
3103
3104 # log10(negative or -Infinity) raises InvalidOperation
3105 if self._sign == 1:
3106 return context._raise_error(InvalidOperation,
3107 'log10 of a negative value')
3108
3109 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003110 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003111 # answer may need rounding
3112 ans = Decimal(self._exp + len(self._int) - 1)
3113 else:
3114 # result is irrational, so necessarily inexact
3115 op = _WorkRep(self)
3116 c, e = op.int, op.exp
3117 p = context.prec
3118
3119 # correctly rounded result: repeatedly increase precision
3120 # until result is unambiguously roundable
3121 places = p-self._log10_exp_bound()+2
3122 while True:
3123 coeff = _dlog10(c, e, places)
3124 # assert len(str(abs(coeff)))-p >= 1
3125 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3126 break
3127 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003128 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003129
3130 context = context._shallow_copy()
3131 rounding = context._set_rounding(ROUND_HALF_EVEN)
3132 ans = ans._fix(context)
3133 context.rounding = rounding
3134 return ans
3135
3136 def logb(self, context=None):
3137 """ Returns the exponent of the magnitude of self's MSD.
3138
3139 The result is the integer which is the exponent of the magnitude
3140 of the most significant digit of self (as though it were truncated
3141 to a single digit while maintaining the value of that digit and
3142 without limiting the resulting exponent).
3143 """
3144 # logb(NaN) = NaN
3145 ans = self._check_nans(context=context)
3146 if ans:
3147 return ans
3148
3149 if context is None:
3150 context = getcontext()
3151
3152 # logb(+/-Inf) = +Inf
3153 if self._isinfinity():
3154 return Inf
3155
3156 # logb(0) = -Inf, DivisionByZero
3157 if not self:
3158 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3159
3160 # otherwise, simply return the adjusted exponent of self, as a
3161 # Decimal. Note that no attempt is made to fit the result
3162 # into the current context.
3163 return Decimal(self.adjusted())
3164
3165 def _islogical(self):
3166 """Return True if self is a logical operand.
3167
Christian Heimes679db4a2008-01-18 09:56:22 +00003168 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003169 an exponent of 0, and a coefficient whose digits must all be
3170 either 0 or 1.
3171 """
3172 if self._sign != 0 or self._exp != 0:
3173 return False
3174 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003175 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003176 return False
3177 return True
3178
3179 def _fill_logical(self, context, opa, opb):
3180 dif = context.prec - len(opa)
3181 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003182 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003183 elif dif < 0:
3184 opa = opa[-context.prec:]
3185 dif = context.prec - len(opb)
3186 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003187 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003188 elif dif < 0:
3189 opb = opb[-context.prec:]
3190 return opa, opb
3191
3192 def logical_and(self, other, context=None):
3193 """Applies an 'and' operation between self and other's digits."""
3194 if context is None:
3195 context = getcontext()
3196 if not self._islogical() or not other._islogical():
3197 return context._raise_error(InvalidOperation)
3198
3199 # fill to context.prec
3200 (opa, opb) = self._fill_logical(context, self._int, other._int)
3201
3202 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003203 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3204 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003205
3206 def logical_invert(self, context=None):
3207 """Invert all its digits."""
3208 if context is None:
3209 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003210 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3211 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003212
3213 def logical_or(self, other, context=None):
3214 """Applies an 'or' operation between self and other's digits."""
3215 if context is None:
3216 context = getcontext()
3217 if not self._islogical() or not other._islogical():
3218 return context._raise_error(InvalidOperation)
3219
3220 # fill to context.prec
3221 (opa, opb) = self._fill_logical(context, self._int, other._int)
3222
3223 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003224 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3225 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003226
3227 def logical_xor(self, other, context=None):
3228 """Applies an 'xor' operation between self and other's digits."""
3229 if context is None:
3230 context = getcontext()
3231 if not self._islogical() or not other._islogical():
3232 return context._raise_error(InvalidOperation)
3233
3234 # fill to context.prec
3235 (opa, opb) = self._fill_logical(context, self._int, other._int)
3236
3237 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003238 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3239 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003240
3241 def max_mag(self, other, context=None):
3242 """Compares the values numerically with their sign ignored."""
3243 other = _convert_other(other, raiseit=True)
3244
3245 if context is None:
3246 context = getcontext()
3247
3248 if self._is_special or other._is_special:
3249 # If one operand is a quiet NaN and the other is number, then the
3250 # number is always returned
3251 sn = self._isnan()
3252 on = other._isnan()
3253 if sn or on:
3254 if on == 1 and sn != 2:
3255 return self._fix_nan(context)
3256 if sn == 1 and on != 2:
3257 return other._fix_nan(context)
3258 return self._check_nans(other, context)
3259
Christian Heimes77c02eb2008-02-09 02:18:51 +00003260 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003261 if c == 0:
3262 c = self.compare_total(other)
3263
3264 if c == -1:
3265 ans = other
3266 else:
3267 ans = self
3268
Christian Heimes2c181612007-12-17 20:04:13 +00003269 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003270
3271 def min_mag(self, other, context=None):
3272 """Compares the values numerically with their sign ignored."""
3273 other = _convert_other(other, raiseit=True)
3274
3275 if context is None:
3276 context = getcontext()
3277
3278 if self._is_special or other._is_special:
3279 # If one operand is a quiet NaN and the other is number, then the
3280 # number is always returned
3281 sn = self._isnan()
3282 on = other._isnan()
3283 if sn or on:
3284 if on == 1 and sn != 2:
3285 return self._fix_nan(context)
3286 if sn == 1 and on != 2:
3287 return other._fix_nan(context)
3288 return self._check_nans(other, context)
3289
Christian Heimes77c02eb2008-02-09 02:18:51 +00003290 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003291 if c == 0:
3292 c = self.compare_total(other)
3293
3294 if c == -1:
3295 ans = self
3296 else:
3297 ans = other
3298
Christian Heimes2c181612007-12-17 20:04:13 +00003299 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003300
3301 def next_minus(self, context=None):
3302 """Returns the largest representable number smaller than itself."""
3303 if context is None:
3304 context = getcontext()
3305
3306 ans = self._check_nans(context=context)
3307 if ans:
3308 return ans
3309
3310 if self._isinfinity() == -1:
3311 return negInf
3312 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003313 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003314
3315 context = context.copy()
3316 context._set_rounding(ROUND_FLOOR)
3317 context._ignore_all_flags()
3318 new_self = self._fix(context)
3319 if new_self != self:
3320 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003321 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3322 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003323
3324 def next_plus(self, context=None):
3325 """Returns the smallest representable number larger than itself."""
3326 if context is None:
3327 context = getcontext()
3328
3329 ans = self._check_nans(context=context)
3330 if ans:
3331 return ans
3332
3333 if self._isinfinity() == 1:
3334 return Inf
3335 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003336 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003337
3338 context = context.copy()
3339 context._set_rounding(ROUND_CEILING)
3340 context._ignore_all_flags()
3341 new_self = self._fix(context)
3342 if new_self != self:
3343 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003344 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3345 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003346
3347 def next_toward(self, other, context=None):
3348 """Returns the number closest to self, in the direction towards other.
3349
3350 The result is the closest representable number to self
3351 (excluding self) that is in the direction towards other,
3352 unless both have the same value. If the two operands are
3353 numerically equal, then the result is a copy of self with the
3354 sign set to be the same as the sign of other.
3355 """
3356 other = _convert_other(other, raiseit=True)
3357
3358 if context is None:
3359 context = getcontext()
3360
3361 ans = self._check_nans(other, context)
3362 if ans:
3363 return ans
3364
Christian Heimes77c02eb2008-02-09 02:18:51 +00003365 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003366 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003367 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003368
3369 if comparison == -1:
3370 ans = self.next_plus(context)
3371 else: # comparison == 1
3372 ans = self.next_minus(context)
3373
3374 # decide which flags to raise using value of ans
3375 if ans._isinfinity():
3376 context._raise_error(Overflow,
3377 'Infinite result from next_toward',
3378 ans._sign)
3379 context._raise_error(Rounded)
3380 context._raise_error(Inexact)
3381 elif ans.adjusted() < context.Emin:
3382 context._raise_error(Underflow)
3383 context._raise_error(Subnormal)
3384 context._raise_error(Rounded)
3385 context._raise_error(Inexact)
3386 # if precision == 1 then we don't raise Clamped for a
3387 # result 0E-Etiny.
3388 if not ans:
3389 context._raise_error(Clamped)
3390
3391 return ans
3392
3393 def number_class(self, context=None):
3394 """Returns an indication of the class of self.
3395
3396 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003397 sNaN
3398 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003399 -Infinity
3400 -Normal
3401 -Subnormal
3402 -Zero
3403 +Zero
3404 +Subnormal
3405 +Normal
3406 +Infinity
3407 """
3408 if self.is_snan():
3409 return "sNaN"
3410 if self.is_qnan():
3411 return "NaN"
3412 inf = self._isinfinity()
3413 if inf == 1:
3414 return "+Infinity"
3415 if inf == -1:
3416 return "-Infinity"
3417 if self.is_zero():
3418 if self._sign:
3419 return "-Zero"
3420 else:
3421 return "+Zero"
3422 if context is None:
3423 context = getcontext()
3424 if self.is_subnormal(context=context):
3425 if self._sign:
3426 return "-Subnormal"
3427 else:
3428 return "+Subnormal"
3429 # just a normal, regular, boring number, :)
3430 if self._sign:
3431 return "-Normal"
3432 else:
3433 return "+Normal"
3434
3435 def radix(self):
3436 """Just returns 10, as this is Decimal, :)"""
3437 return Decimal(10)
3438
3439 def rotate(self, other, context=None):
3440 """Returns a rotated copy of self, value-of-other times."""
3441 if context is None:
3442 context = getcontext()
3443
3444 ans = self._check_nans(other, context)
3445 if ans:
3446 return ans
3447
3448 if other._exp != 0:
3449 return context._raise_error(InvalidOperation)
3450 if not (-context.prec <= int(other) <= context.prec):
3451 return context._raise_error(InvalidOperation)
3452
3453 if self._isinfinity():
3454 return Decimal(self)
3455
3456 # get values, pad if necessary
3457 torot = int(other)
3458 rotdig = self._int
3459 topad = context.prec - len(rotdig)
3460 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003461 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003462
3463 # let's rotate!
3464 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003465 return _dec_from_triple(self._sign,
3466 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003467
3468 def scaleb (self, other, context=None):
3469 """Returns self operand after adding the second value to its exp."""
3470 if context is None:
3471 context = getcontext()
3472
3473 ans = self._check_nans(other, context)
3474 if ans:
3475 return ans
3476
3477 if other._exp != 0:
3478 return context._raise_error(InvalidOperation)
3479 liminf = -2 * (context.Emax + context.prec)
3480 limsup = 2 * (context.Emax + context.prec)
3481 if not (liminf <= int(other) <= limsup):
3482 return context._raise_error(InvalidOperation)
3483
3484 if self._isinfinity():
3485 return Decimal(self)
3486
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003487 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003488 d = d._fix(context)
3489 return d
3490
3491 def shift(self, other, context=None):
3492 """Returns a shifted copy of self, value-of-other times."""
3493 if context is None:
3494 context = getcontext()
3495
3496 ans = self._check_nans(other, context)
3497 if ans:
3498 return ans
3499
3500 if other._exp != 0:
3501 return context._raise_error(InvalidOperation)
3502 if not (-context.prec <= int(other) <= context.prec):
3503 return context._raise_error(InvalidOperation)
3504
3505 if self._isinfinity():
3506 return Decimal(self)
3507
3508 # get values, pad if necessary
3509 torot = int(other)
3510 if not torot:
3511 return Decimal(self)
3512 rotdig = self._int
3513 topad = context.prec - len(rotdig)
3514 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003515 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003516
3517 # let's shift!
3518 if torot < 0:
3519 rotated = rotdig[:torot]
3520 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003521 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003522 rotated = rotated[-context.prec:]
3523
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003524 return _dec_from_triple(self._sign,
3525 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003526
Guido van Rossumd8faa362007-04-27 19:54:29 +00003527 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003528 def __reduce__(self):
3529 return (self.__class__, (str(self),))
3530
3531 def __copy__(self):
3532 if type(self) == Decimal:
3533 return self # I'm immutable; therefore I am my own clone
3534 return self.__class__(str(self))
3535
3536 def __deepcopy__(self, memo):
3537 if type(self) == Decimal:
3538 return self # My components are also immutable
3539 return self.__class__(str(self))
3540
Christian Heimesf16baeb2008-02-29 14:57:44 +00003541 # PEP 3101 support. See also _parse_format_specifier and _format_align
3542 def __format__(self, specifier, context=None):
3543 """Format a Decimal instance according to the given specifier.
3544
3545 The specifier should be a standard format specifier, with the
3546 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3547 'F', 'g', 'G', and '%' are supported. If the formatting type
3548 is omitted it defaults to 'g' or 'G', depending on the value
3549 of context.capitals.
3550
3551 At this time the 'n' format specifier type (which is supposed
3552 to use the current locale) is not supported.
3553 """
3554
3555 # Note: PEP 3101 says that if the type is not present then
3556 # there should be at least one digit after the decimal point.
3557 # We take the liberty of ignoring this requirement for
3558 # Decimal---it's presumably there to make sure that
3559 # format(float, '') behaves similarly to str(float).
3560 if context is None:
3561 context = getcontext()
3562
3563 spec = _parse_format_specifier(specifier)
3564
3565 # special values don't care about the type or precision...
3566 if self._is_special:
3567 return _format_align(str(self), spec)
3568
3569 # a type of None defaults to 'g' or 'G', depending on context
3570 # if type is '%', adjust exponent of self accordingly
3571 if spec['type'] is None:
3572 spec['type'] = ['g', 'G'][context.capitals]
3573 elif spec['type'] == '%':
3574 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3575
3576 # round if necessary, taking rounding mode from the context
3577 rounding = context.rounding
3578 precision = spec['precision']
3579 if precision is not None:
3580 if spec['type'] in 'eE':
3581 self = self._round(precision+1, rounding)
3582 elif spec['type'] in 'gG':
3583 if len(self._int) > precision:
3584 self = self._round(precision, rounding)
3585 elif spec['type'] in 'fF%':
3586 self = self._rescale(-precision, rounding)
3587 # special case: zeros with a positive exponent can't be
3588 # represented in fixed point; rescale them to 0e0.
3589 elif not self and self._exp > 0 and spec['type'] in 'fF%':
3590 self = self._rescale(0, rounding)
3591
3592 # figure out placement of the decimal point
3593 leftdigits = self._exp + len(self._int)
3594 if spec['type'] in 'fF%':
3595 dotplace = leftdigits
3596 elif spec['type'] in 'eE':
3597 if not self and precision is not None:
3598 dotplace = 1 - precision
3599 else:
3600 dotplace = 1
3601 elif spec['type'] in 'gG':
3602 if self._exp <= 0 and leftdigits > -6:
3603 dotplace = leftdigits
3604 else:
3605 dotplace = 1
3606
3607 # figure out main part of numeric string...
3608 if dotplace <= 0:
3609 num = '0.' + '0'*(-dotplace) + self._int
3610 elif dotplace >= len(self._int):
3611 # make sure we're not padding a '0' with extra zeros on the right
3612 assert dotplace==len(self._int) or self._int != '0'
3613 num = self._int + '0'*(dotplace-len(self._int))
3614 else:
3615 num = self._int[:dotplace] + '.' + self._int[dotplace:]
3616
3617 # ...then the trailing exponent, or trailing '%'
3618 if leftdigits != dotplace or spec['type'] in 'eE':
3619 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3620 num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3621 elif spec['type'] == '%':
3622 num = num + '%'
3623
3624 # add sign
3625 if self._sign == 1:
3626 num = '-' + num
3627 return _format_align(num, spec)
3628
3629
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003630def _dec_from_triple(sign, coefficient, exponent, special=False):
3631 """Create a decimal instance directly, without any validation,
3632 normalization (e.g. removal of leading zeros) or argument
3633 conversion.
3634
3635 This function is for *internal use only*.
3636 """
3637
3638 self = object.__new__(Decimal)
3639 self._sign = sign
3640 self._int = coefficient
3641 self._exp = exponent
3642 self._is_special = special
3643
3644 return self
3645
Guido van Rossumd8faa362007-04-27 19:54:29 +00003646##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003647
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003648
3649# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003650rounding_functions = [name for name in Decimal.__dict__.keys()
3651 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003652for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003653 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003654 globalname = name[1:].upper()
3655 val = globals()[globalname]
3656 Decimal._pick_rounding_function[val] = name
3657
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003658del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003659
Thomas Wouters89f507f2006-12-13 04:49:30 +00003660class _ContextManager(object):
3661 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003662
Thomas Wouters89f507f2006-12-13 04:49:30 +00003663 Sets a copy of the supplied context in __enter__() and restores
3664 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003665 """
3666 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003667 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003668 def __enter__(self):
3669 self.saved_context = getcontext()
3670 setcontext(self.new_context)
3671 return self.new_context
3672 def __exit__(self, t, v, tb):
3673 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003674
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003675class Context(object):
3676 """Contains the context for a Decimal instance.
3677
3678 Contains:
3679 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003680 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003681 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003682 raised when it is caused. Otherwise, a value is
3683 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003684 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003685 (Whether or not the trap_enabler is set)
3686 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003687 Emin - Minimum exponent
3688 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003689 capitals - If 1, 1*10^1 is printed as 1E+1.
3690 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003691 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003692 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003693
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003694 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003695 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003696 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003697 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003698 _ignored_flags=None):
3699 if flags is None:
3700 flags = []
3701 if _ignored_flags is None:
3702 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003703 if not isinstance(flags, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003704 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003705 if traps is not None and not isinstance(traps, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003706 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003707 for name, val in locals().items():
3708 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003709 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003710 else:
3711 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003712 del self.self
3713
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003714 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003715 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003716 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003717 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3718 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3719 % vars(self))
3720 names = [f.__name__ for f, v in self.flags.items() if v]
3721 s.append('flags=[' + ', '.join(names) + ']')
3722 names = [t.__name__ for t, v in self.traps.items() if v]
3723 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003724 return ', '.join(s) + ')'
3725
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003726 def clear_flags(self):
3727 """Reset all flags to zero"""
3728 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003729 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003730
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003731 def _shallow_copy(self):
3732 """Returns a shallow copy from self."""
Christian Heimes2c181612007-12-17 20:04:13 +00003733 nc = Context(self.prec, self.rounding, self.traps,
3734 self.flags, self.Emin, self.Emax,
3735 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003736 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003737
3738 def copy(self):
3739 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003740 nc = Context(self.prec, self.rounding, self.traps.copy(),
Christian Heimes2c181612007-12-17 20:04:13 +00003741 self.flags.copy(), self.Emin, self.Emax,
3742 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003743 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003744 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003745
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003746 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003747 """Handles an error
3748
3749 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003750 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003751 trap_enabler is set, it reaises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00003752 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003753 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003754 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003755 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003756 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003757 return error().handle(self, *args)
3758
Raymond Hettinger86173da2008-02-01 20:38:12 +00003759 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003760 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003761 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003762 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003763
3764 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003765 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003766 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003767
3768 def _ignore_all_flags(self):
3769 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003770 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003771
3772 def _ignore_flags(self, *flags):
3773 """Ignore the flags, if they are raised"""
3774 # Do not mutate-- This way, copies of a context leave the original
3775 # alone.
3776 self._ignored_flags = (self._ignored_flags + list(flags))
3777 return list(flags)
3778
3779 def _regard_flags(self, *flags):
3780 """Stop ignoring the flags, if they are raised"""
3781 if flags and isinstance(flags[0], (tuple,list)):
3782 flags = flags[0]
3783 for flag in flags:
3784 self._ignored_flags.remove(flag)
3785
Nick Coghland1abd252008-07-15 15:46:38 +00003786 # We inherit object.__hash__, so we must deny this explicitly
3787 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003788
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003789 def Etiny(self):
3790 """Returns Etiny (= Emin - prec + 1)"""
3791 return int(self.Emin - self.prec + 1)
3792
3793 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003794 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003795 return int(self.Emax - self.prec + 1)
3796
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003797 def _set_rounding(self, type):
3798 """Sets the rounding type.
3799
3800 Sets the rounding type, and returns the current (previous)
3801 rounding type. Often used like:
3802
3803 context = context.copy()
3804 # so you don't change the calling context
3805 # if an error occurs in the middle.
3806 rounding = context._set_rounding(ROUND_UP)
3807 val = self.__sub__(other, context=context)
3808 context._set_rounding(rounding)
3809
3810 This will make it round up for that operation.
3811 """
3812 rounding = self.rounding
3813 self.rounding= type
3814 return rounding
3815
Raymond Hettingerfed52962004-07-14 15:41:57 +00003816 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00003817 """Creates a new Decimal instance but using self as context.
3818
3819 This method implements the to-number operation of the
3820 IBM Decimal specification."""
3821
3822 if isinstance(num, str) and num != num.strip():
3823 return self._raise_error(ConversionSyntax,
3824 "no trailing or leading whitespace is "
3825 "permitted.")
3826
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003827 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003828 if d._isnan() and len(d._int) > self.prec - self._clamp:
3829 return self._raise_error(ConversionSyntax,
3830 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003831 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003832
Guido van Rossumd8faa362007-04-27 19:54:29 +00003833 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003834 def abs(self, a):
3835 """Returns the absolute value of the operand.
3836
3837 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003838 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003839 the plus operation on the operand.
3840
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003841 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003842 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003843 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003844 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003845 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003846 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003847 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003848 Decimal('101.5')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003849 """
3850 return a.__abs__(context=self)
3851
3852 def add(self, a, b):
3853 """Return the sum of the two operands.
3854
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003855 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003856 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003857 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003858 Decimal('1.02E+4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003859 """
3860 return a.__add__(b, context=self)
3861
3862 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003863 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003864
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003865 def canonical(self, a):
3866 """Returns the same Decimal object.
3867
3868 As we do not have different encodings for the same number, the
3869 received object already is in its canonical form.
3870
3871 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003872 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003873 """
3874 return a.canonical(context=self)
3875
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003876 def compare(self, a, b):
3877 """Compares values numerically.
3878
3879 If the signs of the operands differ, a value representing each operand
3880 ('-1' if the operand is less than zero, '0' if the operand is zero or
3881 negative zero, or '1' if the operand is greater than zero) is used in
3882 place of that operand for the comparison instead of the actual
3883 operand.
3884
3885 The comparison is then effected by subtracting the second operand from
3886 the first and then returning a value according to the result of the
3887 subtraction: '-1' if the result is less than zero, '0' if the result is
3888 zero or negative zero, or '1' if the result is greater than zero.
3889
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003890 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003891 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003892 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003893 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003894 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003895 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003896 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003897 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003898 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003899 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003900 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003901 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003902 """
3903 return a.compare(b, context=self)
3904
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003905 def compare_signal(self, a, b):
3906 """Compares the values of the two operands numerically.
3907
3908 It's pretty much like compare(), but all NaNs signal, with signaling
3909 NaNs taking precedence over quiet NaNs.
3910
3911 >>> c = ExtendedContext
3912 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003913 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003914 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003915 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003916 >>> c.flags[InvalidOperation] = 0
3917 >>> print(c.flags[InvalidOperation])
3918 0
3919 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003920 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003921 >>> print(c.flags[InvalidOperation])
3922 1
3923 >>> c.flags[InvalidOperation] = 0
3924 >>> print(c.flags[InvalidOperation])
3925 0
3926 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003927 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003928 >>> print(c.flags[InvalidOperation])
3929 1
3930 """
3931 return a.compare_signal(b, context=self)
3932
3933 def compare_total(self, a, b):
3934 """Compares two operands using their abstract representation.
3935
3936 This is not like the standard compare, which use their numerical
3937 value. Note that a total ordering is defined for all possible abstract
3938 representations.
3939
3940 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003941 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003942 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003943 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003944 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003945 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003946 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003947 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003948 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003949 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003950 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003951 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003952 """
3953 return a.compare_total(b)
3954
3955 def compare_total_mag(self, a, b):
3956 """Compares two operands using their abstract representation ignoring sign.
3957
3958 Like compare_total, but with operand's sign ignored and assumed to be 0.
3959 """
3960 return a.compare_total_mag(b)
3961
3962 def copy_abs(self, a):
3963 """Returns a copy of the operand with the sign set to 0.
3964
3965 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003966 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003967 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003968 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003969 """
3970 return a.copy_abs()
3971
3972 def copy_decimal(self, a):
3973 """Returns a copy of the decimal objet.
3974
3975 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003976 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003977 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003978 Decimal('-1.00')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003979 """
3980 return Decimal(a)
3981
3982 def copy_negate(self, a):
3983 """Returns a copy of the operand with the sign inverted.
3984
3985 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003986 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003987 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003988 Decimal('101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003989 """
3990 return a.copy_negate()
3991
3992 def copy_sign(self, a, b):
3993 """Copies the second operand's sign to the first one.
3994
3995 In detail, it returns a copy of the first operand with the sign
3996 equal to the sign of the second operand.
3997
3998 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003999 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004000 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004001 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004002 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004003 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004004 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004005 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004006 """
4007 return a.copy_sign(b)
4008
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004009 def divide(self, a, b):
4010 """Decimal division in a specified context.
4011
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004012 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004013 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004014 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004015 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004016 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004017 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004018 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004019 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004020 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004021 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004022 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004023 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004024 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004025 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004026 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004027 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004028 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004029 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004030 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004031 Decimal('1.20E+6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004032 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00004033 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004034
4035 def divide_int(self, a, b):
4036 """Divides two numbers and returns the integer part of the result.
4037
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004038 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004039 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004040 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004041 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004042 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004043 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004044 """
4045 return a.__floordiv__(b, context=self)
4046
4047 def divmod(self, a, b):
4048 return a.__divmod__(b, context=self)
4049
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004050 def exp(self, a):
4051 """Returns e ** a.
4052
4053 >>> c = ExtendedContext.copy()
4054 >>> c.Emin = -999
4055 >>> c.Emax = 999
4056 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004057 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004058 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004059 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004060 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004061 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004062 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004063 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004064 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004065 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004066 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004067 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004068 """
4069 return a.exp(context=self)
4070
4071 def fma(self, a, b, c):
4072 """Returns a multiplied by b, plus c.
4073
4074 The first two operands are multiplied together, using multiply,
4075 the third operand is then added to the result of that
4076 multiplication, using add, all with only one final rounding.
4077
4078 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004079 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004080 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004081 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004082 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004083 Decimal('1.38435736E+12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004084 """
4085 return a.fma(b, c, context=self)
4086
4087 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004088 """Return True if the operand is canonical; otherwise return False.
4089
4090 Currently, the encoding of a Decimal instance is always
4091 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004092
4093 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004094 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004095 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004096 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004097
4098 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004099 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004100
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004101 A Decimal instance is considered finite if it is neither
4102 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004103
4104 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004105 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004106 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004107 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004108 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004109 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004110 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004111 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004112 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004113 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004114 """
4115 return a.is_finite()
4116
4117 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004118 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004119
4120 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004121 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004122 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004123 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004124 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004125 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004126 """
4127 return a.is_infinite()
4128
4129 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004130 """Return True if the operand is a qNaN or sNaN;
4131 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004132
4133 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004134 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004135 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004136 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004137 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004138 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004139 """
4140 return a.is_nan()
4141
4142 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004143 """Return True if the operand is a normal number;
4144 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004145
4146 >>> c = ExtendedContext.copy()
4147 >>> c.Emin = -999
4148 >>> c.Emax = 999
4149 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004150 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004151 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004152 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004153 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004154 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004155 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004156 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004157 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004158 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004159 """
4160 return a.is_normal(context=self)
4161
4162 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004163 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004164
4165 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004166 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004167 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004168 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004169 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004170 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004171 """
4172 return a.is_qnan()
4173
4174 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004175 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004176
4177 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004178 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004179 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004180 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004181 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004182 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004183 """
4184 return a.is_signed()
4185
4186 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004187 """Return True if the operand is a signaling NaN;
4188 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004189
4190 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004191 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004192 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004193 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004194 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004195 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004196 """
4197 return a.is_snan()
4198
4199 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004200 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004201
4202 >>> c = ExtendedContext.copy()
4203 >>> c.Emin = -999
4204 >>> c.Emax = 999
4205 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004206 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004207 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004208 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004209 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004210 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004211 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004212 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004213 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004214 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004215 """
4216 return a.is_subnormal(context=self)
4217
4218 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004219 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004220
4221 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004222 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004223 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004224 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004225 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004226 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004227 """
4228 return a.is_zero()
4229
4230 def ln(self, a):
4231 """Returns the natural (base e) logarithm of the operand.
4232
4233 >>> c = ExtendedContext.copy()
4234 >>> c.Emin = -999
4235 >>> c.Emax = 999
4236 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004237 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004238 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004239 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004240 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004241 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004242 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004243 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004244 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004245 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004246 """
4247 return a.ln(context=self)
4248
4249 def log10(self, a):
4250 """Returns the base 10 logarithm of the operand.
4251
4252 >>> c = ExtendedContext.copy()
4253 >>> c.Emin = -999
4254 >>> c.Emax = 999
4255 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004256 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004257 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004258 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004259 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004260 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004261 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004262 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004263 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004264 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004265 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004266 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004267 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004268 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004269 """
4270 return a.log10(context=self)
4271
4272 def logb(self, a):
4273 """ Returns the exponent of the magnitude of the operand's MSD.
4274
4275 The result is the integer which is the exponent of the magnitude
4276 of the most significant digit of the operand (as though the
4277 operand were truncated to a single digit while maintaining the
4278 value of that digit and without limiting the resulting exponent).
4279
4280 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004281 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004282 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004283 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004284 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004285 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004286 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004287 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004288 """
4289 return a.logb(context=self)
4290
4291 def logical_and(self, a, b):
4292 """Applies the logical operation 'and' between each operand's digits.
4293
4294 The operands must be both logical numbers.
4295
4296 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004297 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004298 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004299 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004300 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004301 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004302 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004303 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004304 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004305 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004306 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004307 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004308 """
4309 return a.logical_and(b, context=self)
4310
4311 def logical_invert(self, a):
4312 """Invert all the digits in the operand.
4313
4314 The operand must be a logical number.
4315
4316 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004317 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004318 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004319 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004320 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004321 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004322 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004323 Decimal('10101010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004324 """
4325 return a.logical_invert(context=self)
4326
4327 def logical_or(self, a, b):
4328 """Applies the logical operation 'or' between each operand's digits.
4329
4330 The operands must be both logical numbers.
4331
4332 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004333 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004334 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004335 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004336 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004337 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004338 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004339 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004340 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004341 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004342 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004343 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004344 """
4345 return a.logical_or(b, context=self)
4346
4347 def logical_xor(self, a, b):
4348 """Applies the logical operation 'xor' between each operand's digits.
4349
4350 The operands must be both logical numbers.
4351
4352 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004353 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004354 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004355 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004356 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004357 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004358 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004359 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004360 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004361 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004362 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004363 Decimal('1101')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004364 """
4365 return a.logical_xor(b, context=self)
4366
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004367 def max(self, a,b):
4368 """max compares two values numerically and returns the maximum.
4369
4370 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004371 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004372 operation. If they are numerically equal then the left-hand operand
4373 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004374 infinity) of the two operands is chosen as the result.
4375
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004376 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004377 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004378 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004379 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004380 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004381 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004382 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004383 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004384 """
4385 return a.max(b, context=self)
4386
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004387 def max_mag(self, a, b):
4388 """Compares the values numerically with their sign ignored."""
4389 return a.max_mag(b, context=self)
4390
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004391 def min(self, a,b):
4392 """min compares two values numerically and returns the minimum.
4393
4394 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004395 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004396 operation. If they are numerically equal then the left-hand operand
4397 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004398 infinity) of the two operands is chosen as the result.
4399
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004400 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004401 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004402 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004403 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004404 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004405 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004406 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004407 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004408 """
4409 return a.min(b, context=self)
4410
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004411 def min_mag(self, a, b):
4412 """Compares the values numerically with their sign ignored."""
4413 return a.min_mag(b, context=self)
4414
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004415 def minus(self, a):
4416 """Minus corresponds to unary prefix minus in Python.
4417
4418 The operation is evaluated using the same rules as subtract; the
4419 operation minus(a) is calculated as subtract('0', a) where the '0'
4420 has the same exponent as the operand.
4421
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004422 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004423 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004424 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004425 Decimal('1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004426 """
4427 return a.__neg__(context=self)
4428
4429 def multiply(self, a, b):
4430 """multiply multiplies two operands.
4431
4432 If either operand is a special value then the general rules apply.
4433 Otherwise, the operands are multiplied together ('long multiplication'),
4434 resulting in a number which may be as long as the sum of the lengths
4435 of the two operands.
4436
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004437 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004438 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004439 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004440 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004441 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004442 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004443 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004444 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004445 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004446 Decimal('4.28135971E+11')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004447 """
4448 return a.__mul__(b, context=self)
4449
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004450 def next_minus(self, a):
4451 """Returns the largest representable number smaller than a.
4452
4453 >>> c = ExtendedContext.copy()
4454 >>> c.Emin = -999
4455 >>> c.Emax = 999
4456 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004457 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004458 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004459 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004460 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004461 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004462 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004463 Decimal('9.99999999E+999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004464 """
4465 return a.next_minus(context=self)
4466
4467 def next_plus(self, a):
4468 """Returns the smallest representable number larger than a.
4469
4470 >>> c = ExtendedContext.copy()
4471 >>> c.Emin = -999
4472 >>> c.Emax = 999
4473 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004474 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004475 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004476 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004477 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004478 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004479 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004480 Decimal('-9.99999999E+999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004481 """
4482 return a.next_plus(context=self)
4483
4484 def next_toward(self, a, b):
4485 """Returns the number closest to a, in direction towards b.
4486
4487 The result is the closest representable number from the first
4488 operand (but not the first operand) that is in the direction
4489 towards the second operand, unless the operands have the same
4490 value.
4491
4492 >>> c = ExtendedContext.copy()
4493 >>> c.Emin = -999
4494 >>> c.Emax = 999
4495 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004496 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004497 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004498 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004499 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004500 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004501 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004502 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004503 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004504 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004505 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004506 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004507 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004508 Decimal('-0.00')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004509 """
4510 return a.next_toward(b, context=self)
4511
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004512 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004513 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004514
4515 Essentially a plus operation with all trailing zeros removed from the
4516 result.
4517
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004518 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004519 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004520 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004521 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004522 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004523 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004524 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004525 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004526 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004527 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004528 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004529 Decimal('0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004530 """
4531 return a.normalize(context=self)
4532
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004533 def number_class(self, a):
4534 """Returns an indication of the class of the operand.
4535
4536 The class is one of the following strings:
4537 -sNaN
4538 -NaN
4539 -Infinity
4540 -Normal
4541 -Subnormal
4542 -Zero
4543 +Zero
4544 +Subnormal
4545 +Normal
4546 +Infinity
4547
4548 >>> c = Context(ExtendedContext)
4549 >>> c.Emin = -999
4550 >>> c.Emax = 999
4551 >>> c.number_class(Decimal('Infinity'))
4552 '+Infinity'
4553 >>> c.number_class(Decimal('1E-10'))
4554 '+Normal'
4555 >>> c.number_class(Decimal('2.50'))
4556 '+Normal'
4557 >>> c.number_class(Decimal('0.1E-999'))
4558 '+Subnormal'
4559 >>> c.number_class(Decimal('0'))
4560 '+Zero'
4561 >>> c.number_class(Decimal('-0'))
4562 '-Zero'
4563 >>> c.number_class(Decimal('-0.1E-999'))
4564 '-Subnormal'
4565 >>> c.number_class(Decimal('-1E-10'))
4566 '-Normal'
4567 >>> c.number_class(Decimal('-2.50'))
4568 '-Normal'
4569 >>> c.number_class(Decimal('-Infinity'))
4570 '-Infinity'
4571 >>> c.number_class(Decimal('NaN'))
4572 'NaN'
4573 >>> c.number_class(Decimal('-NaN'))
4574 'NaN'
4575 >>> c.number_class(Decimal('sNaN'))
4576 'sNaN'
4577 """
4578 return a.number_class(context=self)
4579
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004580 def plus(self, a):
4581 """Plus corresponds to unary prefix plus in Python.
4582
4583 The operation is evaluated using the same rules as add; the
4584 operation plus(a) is calculated as add('0', a) where the '0'
4585 has the same exponent as the operand.
4586
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004587 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004588 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004589 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004590 Decimal('-1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004591 """
4592 return a.__pos__(context=self)
4593
4594 def power(self, a, b, modulo=None):
4595 """Raises a to the power of b, to modulo if given.
4596
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004597 With two arguments, compute a**b. If a is negative then b
4598 must be integral. The result will be inexact unless b is
4599 integral and the result is finite and can be expressed exactly
4600 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004601
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004602 With three arguments, compute (a**b) % modulo. For the
4603 three argument form, the following restrictions on the
4604 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004605
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004606 - all three arguments must be integral
4607 - b must be nonnegative
4608 - at least one of a or b must be nonzero
4609 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004610
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004611 The result of pow(a, b, modulo) is identical to the result
4612 that would be obtained by computing (a**b) % modulo with
4613 unbounded precision, but is computed more efficiently. It is
4614 always exact.
4615
4616 >>> c = ExtendedContext.copy()
4617 >>> c.Emin = -999
4618 >>> c.Emax = 999
4619 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004620 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004621 >>> c.power(Decimal('-2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004622 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004623 >>> c.power(Decimal('2'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004624 Decimal('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004625 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004626 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004627 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004628 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004629 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004630 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004631 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004632 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004633 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004634 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004635 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004636 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004637 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004638 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004639 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004640 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004641 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004642 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004643 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004644 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004645
4646 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004647 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004648 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004649 Decimal('-11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004650 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004651 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004652 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004653 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004654 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004655 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004656 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004657 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004658 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004659 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004660 """
4661 return a.__pow__(b, modulo, context=self)
4662
4663 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004664 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004665
4666 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004667 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004668 exponent is being increased), multiplied by a positive power of ten (if
4669 the exponent is being decreased), or is unchanged (if the exponent is
4670 already equal to that of the right-hand operand).
4671
4672 Unlike other operations, if the length of the coefficient after the
4673 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004674 operation condition is raised. This guarantees that, unless there is
4675 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004676 equal to that of the right-hand operand.
4677
4678 Also unlike other operations, quantize will never raise Underflow, even
4679 if the result is subnormal and inexact.
4680
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004681 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004682 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004683 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004684 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004685 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004686 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004687 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004688 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004689 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004690 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004691 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004692 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004693 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004694 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004695 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004696 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004697 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004698 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004699 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004700 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004701 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004702 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004703 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004704 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004705 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004706 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004707 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004708 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004709 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004710 Decimal('2E+2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004711 """
4712 return a.quantize(b, context=self)
4713
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004714 def radix(self):
4715 """Just returns 10, as this is Decimal, :)
4716
4717 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004718 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004719 """
4720 return Decimal(10)
4721
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004722 def remainder(self, a, b):
4723 """Returns the remainder from integer division.
4724
4725 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004726 calculating integer division as described for divide-integer, rounded
4727 to precision digits if necessary. The sign of the result, if
4728 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004729
4730 This operation will fail under the same conditions as integer division
4731 (that is, if integer division on the same two operands would fail, the
4732 remainder cannot be calculated).
4733
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004734 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004735 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004736 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004737 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004738 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004739 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004740 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004741 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004742 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004743 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004744 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004745 Decimal('1.0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004746 """
4747 return a.__mod__(b, context=self)
4748
4749 def remainder_near(self, a, b):
4750 """Returns to be "a - b * n", where n is the integer nearest the exact
4751 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004752 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004753 sign of a.
4754
4755 This operation will fail under the same conditions as integer division
4756 (that is, if integer division on the same two operands would fail, the
4757 remainder cannot be calculated).
4758
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004759 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004760 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004761 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004762 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004763 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004764 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004765 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004766 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004767 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004768 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004769 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004770 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004771 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004772 Decimal('-0.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004773 """
4774 return a.remainder_near(b, context=self)
4775
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004776 def rotate(self, a, b):
4777 """Returns a rotated copy of a, b times.
4778
4779 The coefficient of the result is a rotated copy of the digits in
4780 the coefficient of the first operand. The number of places of
4781 rotation is taken from the absolute value of the second operand,
4782 with the rotation being to the left if the second operand is
4783 positive or to the right otherwise.
4784
4785 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004786 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004787 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004788 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004789 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004790 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004791 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004792 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004793 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004794 Decimal('345678912')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004795 """
4796 return a.rotate(b, context=self)
4797
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004798 def same_quantum(self, a, b):
4799 """Returns True if the two operands have the same exponent.
4800
4801 The result is never affected by either the sign or the coefficient of
4802 either operand.
4803
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004804 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004805 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004806 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004807 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004808 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004809 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004810 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004811 True
4812 """
4813 return a.same_quantum(b)
4814
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004815 def scaleb (self, a, b):
4816 """Returns the first operand after adding the second value its exp.
4817
4818 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004819 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004820 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004821 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004822 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004823 Decimal('7.50E+3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004824 """
4825 return a.scaleb (b, context=self)
4826
4827 def shift(self, a, b):
4828 """Returns a shifted copy of a, b times.
4829
4830 The coefficient of the result is a shifted copy of the digits
4831 in the coefficient of the first operand. The number of places
4832 to shift is taken from the absolute value of the second operand,
4833 with the shift being to the left if the second operand is
4834 positive or to the right otherwise. Digits shifted into the
4835 coefficient are zeros.
4836
4837 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004838 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004839 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004840 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004841 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004842 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004843 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004844 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004845 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004846 Decimal('345678900')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004847 """
4848 return a.shift(b, context=self)
4849
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004850 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004851 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004852
4853 If the result must be inexact, it is rounded using the round-half-even
4854 algorithm.
4855
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004856 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004857 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004858 >>> ExtendedContext.sqrt(Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004859 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004860 >>> ExtendedContext.sqrt(Decimal('0.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004861 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004862 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004863 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004864 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004865 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004866 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004867 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004868 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004869 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004870 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004871 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004872 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004873 Decimal('3.16227766')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004874 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004875 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004876 """
4877 return a.sqrt(context=self)
4878
4879 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004880 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004881
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004882 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004883 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004884 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004885 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004886 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004887 Decimal('-0.77')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004888 """
4889 return a.__sub__(b, context=self)
4890
4891 def to_eng_string(self, a):
4892 """Converts a number to a string, using scientific notation.
4893
4894 The operation is not affected by the context.
4895 """
4896 return a.to_eng_string(context=self)
4897
4898 def to_sci_string(self, a):
4899 """Converts a number to a string, using scientific notation.
4900
4901 The operation is not affected by the context.
4902 """
4903 return a.__str__(context=self)
4904
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004905 def to_integral_exact(self, a):
4906 """Rounds to an integer.
4907
4908 When the operand has a negative exponent, the result is the same
4909 as using the quantize() operation using the given operand as the
4910 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4911 of the operand as the precision setting; Inexact and Rounded flags
4912 are allowed in this operation. The rounding mode is taken from the
4913 context.
4914
4915 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004916 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004917 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004918 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004919 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004920 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004921 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004922 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004923 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004924 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004925 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004926 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004927 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004928 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004929 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004930 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004931 """
4932 return a.to_integral_exact(context=self)
4933
4934 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004935 """Rounds to an integer.
4936
4937 When the operand has a negative exponent, the result is the same
4938 as using the quantize() operation using the given operand as the
4939 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4940 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004941 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004942
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004943 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004944 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004945 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004946 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004947 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004948 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004949 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004950 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004951 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004952 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004953 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004954 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004955 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004956 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004957 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004958 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004959 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004960 return a.to_integral_value(context=self)
4961
4962 # the method name changed, but we provide also the old one, for compatibility
4963 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004964
4965class _WorkRep(object):
4966 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004967 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004968 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004969 # exp: None, int, or string
4970
4971 def __init__(self, value=None):
4972 if value is None:
4973 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004974 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004975 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004976 elif isinstance(value, Decimal):
4977 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00004978 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004979 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004980 else:
4981 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004982 self.sign = value[0]
4983 self.int = value[1]
4984 self.exp = value[2]
4985
4986 def __repr__(self):
4987 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4988
4989 __str__ = __repr__
4990
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004991
4992
Christian Heimes2c181612007-12-17 20:04:13 +00004993def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004994 """Normalizes op1, op2 to have the same exp and length of coefficient.
4995
4996 Done during addition.
4997 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004998 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004999 tmp = op2
5000 other = op1
5001 else:
5002 tmp = op1
5003 other = op2
5004
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005005 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5006 # Then adding 10**exp to tmp has the same effect (after rounding)
5007 # as adding any positive quantity smaller than 10**exp; similarly
5008 # for subtraction. So if other is smaller than 10**exp we replace
5009 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00005010 tmp_len = len(str(tmp.int))
5011 other_len = len(str(other.int))
5012 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5013 if other_len + other.exp - 1 < exp:
5014 other.int = 1
5015 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005016
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005017 tmp.int *= 10 ** (tmp.exp - other.exp)
5018 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005019 return op1, op2
5020
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005021##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005022
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005023# This function from Tim Peters was taken from here:
5024# http://mail.python.org/pipermail/python-list/1999-July/007758.html
5025# The correction being in the function definition is for speed, and
5026# the whole function is not resolved with math.log because of avoiding
5027# the use of floats.
5028def _nbits(n, correction = {
5029 '0': 4, '1': 3, '2': 2, '3': 2,
5030 '4': 1, '5': 1, '6': 1, '7': 1,
5031 '8': 0, '9': 0, 'a': 0, 'b': 0,
5032 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
5033 """Number of bits in binary representation of the positive integer n,
5034 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005035 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005036 if n < 0:
5037 raise ValueError("The argument to _nbits should be nonnegative.")
5038 hex_n = "%x" % n
5039 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005040
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005041def _sqrt_nearest(n, a):
5042 """Closest integer to the square root of the positive integer n. a is
5043 an initial approximation to the square root. Any positive integer
5044 will do for a, but the closer a is to the square root of n the
5045 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005046
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005047 """
5048 if n <= 0 or a <= 0:
5049 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5050
5051 b=0
5052 while a != b:
5053 b, a = a, a--n//a>>1
5054 return a
5055
5056def _rshift_nearest(x, shift):
5057 """Given an integer x and a nonnegative integer shift, return closest
5058 integer to x / 2**shift; use round-to-even in case of a tie.
5059
5060 """
5061 b, q = 1 << shift, x >> shift
5062 return q + (2*(x & (b-1)) + (q&1) > b)
5063
5064def _div_nearest(a, b):
5065 """Closest integer to a/b, a and b positive integers; rounds to even
5066 in the case of a tie.
5067
5068 """
5069 q, r = divmod(a, b)
5070 return q + (2*r + (q&1) > b)
5071
5072def _ilog(x, M, L = 8):
5073 """Integer approximation to M*log(x/M), with absolute error boundable
5074 in terms only of x/M.
5075
5076 Given positive integers x and M, return an integer approximation to
5077 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5078 between the approximation and the exact result is at most 22. For
5079 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5080 both cases these are upper bounds on the error; it will usually be
5081 much smaller."""
5082
5083 # The basic algorithm is the following: let log1p be the function
5084 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5085 # the reduction
5086 #
5087 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5088 #
5089 # repeatedly until the argument to log1p is small (< 2**-L in
5090 # absolute value). For small y we can use the Taylor series
5091 # expansion
5092 #
5093 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5094 #
5095 # truncating at T such that y**T is small enough. The whole
5096 # computation is carried out in a form of fixed-point arithmetic,
5097 # with a real number z being represented by an integer
5098 # approximation to z*M. To avoid loss of precision, the y below
5099 # is actually an integer approximation to 2**R*y*M, where R is the
5100 # number of reductions performed so far.
5101
5102 y = x-M
5103 # argument reduction; R = number of reductions performed
5104 R = 0
5105 while (R <= L and abs(y) << L-R >= M or
5106 R > L and abs(y) >> R-L >= M):
5107 y = _div_nearest((M*y) << 1,
5108 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5109 R += 1
5110
5111 # Taylor series with T terms
5112 T = -int(-10*len(str(M))//(3*L))
5113 yshift = _rshift_nearest(y, R)
5114 w = _div_nearest(M, T)
5115 for k in range(T-1, 0, -1):
5116 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5117
5118 return _div_nearest(w*y, M)
5119
5120def _dlog10(c, e, p):
5121 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5122 approximation to 10**p * log10(c*10**e), with an absolute error of
5123 at most 1. Assumes that c*10**e is not exactly 1."""
5124
5125 # increase precision by 2; compensate for this by dividing
5126 # final result by 100
5127 p += 2
5128
5129 # write c*10**e as d*10**f with either:
5130 # f >= 0 and 1 <= d <= 10, or
5131 # f <= 0 and 0.1 <= d <= 1.
5132 # Thus for c*10**e close to 1, f = 0
5133 l = len(str(c))
5134 f = e+l - (e+l >= 1)
5135
5136 if p > 0:
5137 M = 10**p
5138 k = e+p-f
5139 if k >= 0:
5140 c *= 10**k
5141 else:
5142 c = _div_nearest(c, 10**-k)
5143
5144 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005145 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005146 log_d = _div_nearest(log_d*M, log_10)
5147 log_tenpower = f*M # exact
5148 else:
5149 log_d = 0 # error < 2.31
Neal Norwitz2f99b242008-08-24 05:48:10 +00005150 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005151
5152 return _div_nearest(log_tenpower+log_d, 100)
5153
5154def _dlog(c, e, p):
5155 """Given integers c, e and p with c > 0, compute an integer
5156 approximation to 10**p * log(c*10**e), with an absolute error of
5157 at most 1. Assumes that c*10**e is not exactly 1."""
5158
5159 # Increase precision by 2. The precision increase is compensated
5160 # for at the end with a division by 100.
5161 p += 2
5162
5163 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5164 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5165 # as 10**p * log(d) + 10**p*f * log(10).
5166 l = len(str(c))
5167 f = e+l - (e+l >= 1)
5168
5169 # compute approximation to 10**p*log(d), with error < 27
5170 if p > 0:
5171 k = e+p-f
5172 if k >= 0:
5173 c *= 10**k
5174 else:
5175 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5176
5177 # _ilog magnifies existing error in c by a factor of at most 10
5178 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5179 else:
5180 # p <= 0: just approximate the whole thing by 0; error < 2.31
5181 log_d = 0
5182
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005183 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005184 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005185 extra = len(str(abs(f)))-1
5186 if p + extra >= 0:
5187 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5188 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5189 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005190 else:
5191 f_log_ten = 0
5192 else:
5193 f_log_ten = 0
5194
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005195 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005196 return _div_nearest(f_log_ten + log_d, 100)
5197
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005198class _Log10Memoize(object):
5199 """Class to compute, store, and allow retrieval of, digits of the
5200 constant log(10) = 2.302585.... This constant is needed by
5201 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5202 def __init__(self):
5203 self.digits = "23025850929940456840179914546843642076011014886"
5204
5205 def getdigits(self, p):
5206 """Given an integer p >= 0, return floor(10**p)*log(10).
5207
5208 For example, self.getdigits(3) returns 2302.
5209 """
5210 # digits are stored as a string, for quick conversion to
5211 # integer in the case that we've already computed enough
5212 # digits; the stored digits should always be correct
5213 # (truncated, not rounded to nearest).
5214 if p < 0:
5215 raise ValueError("p should be nonnegative")
5216
5217 if p >= len(self.digits):
5218 # compute p+3, p+6, p+9, ... digits; continue until at
5219 # least one of the extra digits is nonzero
5220 extra = 3
5221 while True:
5222 # compute p+extra digits, correct to within 1ulp
5223 M = 10**(p+extra+2)
5224 digits = str(_div_nearest(_ilog(10*M, M), 100))
5225 if digits[-extra:] != '0'*extra:
5226 break
5227 extra += 3
5228 # keep all reliable digits so far; remove trailing zeros
5229 # and next nonzero digit
5230 self.digits = digits.rstrip('0')[:-1]
5231 return int(self.digits[:p+1])
5232
5233_log10_digits = _Log10Memoize().getdigits
5234
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005235def _iexp(x, M, L=8):
5236 """Given integers x and M, M > 0, such that x/M is small in absolute
5237 value, compute an integer approximation to M*exp(x/M). For 0 <=
5238 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5239 is usually much smaller)."""
5240
5241 # Algorithm: to compute exp(z) for a real number z, first divide z
5242 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5243 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5244 # series
5245 #
5246 # expm1(x) = x + x**2/2! + x**3/3! + ...
5247 #
5248 # Now use the identity
5249 #
5250 # expm1(2x) = expm1(x)*(expm1(x)+2)
5251 #
5252 # R times to compute the sequence expm1(z/2**R),
5253 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5254
5255 # Find R such that x/2**R/M <= 2**-L
5256 R = _nbits((x<<L)//M)
5257
5258 # Taylor series. (2**L)**T > M
5259 T = -int(-10*len(str(M))//(3*L))
5260 y = _div_nearest(x, T)
5261 Mshift = M<<R
5262 for i in range(T-1, 0, -1):
5263 y = _div_nearest(x*(Mshift + y), Mshift * i)
5264
5265 # Expansion
5266 for k in range(R-1, -1, -1):
5267 Mshift = M<<(k+2)
5268 y = _div_nearest(y*(y+Mshift), Mshift)
5269
5270 return M+y
5271
5272def _dexp(c, e, p):
5273 """Compute an approximation to exp(c*10**e), with p decimal places of
5274 precision.
5275
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005276 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005277
5278 10**(p-1) <= d <= 10**p, and
5279 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5280
5281 In other words, d*10**f is an approximation to exp(c*10**e) with p
5282 digits of precision, and with an error in d of at most 1. This is
5283 almost, but not quite, the same as the error being < 1ulp: when d
5284 = 10**(p-1) the error could be up to 10 ulp."""
5285
5286 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5287 p += 2
5288
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005289 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005290 extra = max(0, e + len(str(c)) - 1)
5291 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005292
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005293 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005294 # rounding down
5295 shift = e+q
5296 if shift >= 0:
5297 cshift = c*10**shift
5298 else:
5299 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005300 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005301
5302 # reduce remainder back to original precision
5303 rem = _div_nearest(rem, 10**extra)
5304
5305 # error in result of _iexp < 120; error after division < 0.62
5306 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5307
5308def _dpower(xc, xe, yc, ye, p):
5309 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5310 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5311
5312 10**(p-1) <= c <= 10**p, and
5313 (c-1)*10**e < x**y < (c+1)*10**e
5314
5315 in other words, c*10**e is an approximation to x**y with p digits
5316 of precision, and with an error in c of at most 1. (This is
5317 almost, but not quite, the same as the error being < 1ulp: when c
5318 == 10**(p-1) we can only guarantee error < 10ulp.)
5319
5320 We assume that: x is positive and not equal to 1, and y is nonzero.
5321 """
5322
5323 # Find b such that 10**(b-1) <= |y| <= 10**b
5324 b = len(str(abs(yc))) + ye
5325
5326 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5327 lxc = _dlog(xc, xe, p+b+1)
5328
5329 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5330 shift = ye-b
5331 if shift >= 0:
5332 pc = lxc*yc*10**shift
5333 else:
5334 pc = _div_nearest(lxc*yc, 10**-shift)
5335
5336 if pc == 0:
5337 # we prefer a result that isn't exactly 1; this makes it
5338 # easier to compute a correctly rounded result in __pow__
5339 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5340 coeff, exp = 10**(p-1)+1, 1-p
5341 else:
5342 coeff, exp = 10**p-1, -p
5343 else:
5344 coeff, exp = _dexp(pc, -(p+1), p+1)
5345 coeff = _div_nearest(coeff, 10)
5346 exp += 1
5347
5348 return coeff, exp
5349
5350def _log10_lb(c, correction = {
5351 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5352 '6': 23, '7': 16, '8': 10, '9': 5}):
5353 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5354 if c <= 0:
5355 raise ValueError("The argument to _log10_lb should be nonnegative.")
5356 str_c = str(c)
5357 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005358
Guido van Rossumd8faa362007-04-27 19:54:29 +00005359##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005360
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005361def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005362 """Convert other to Decimal.
5363
5364 Verifies that it's ok to use in an implicit construction.
5365 """
5366 if isinstance(other, Decimal):
5367 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005368 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005369 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005370 if raiseit:
5371 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005372 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005373
Guido van Rossumd8faa362007-04-27 19:54:29 +00005374##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005375
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005376# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005377# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005378
5379DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005380 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005381 traps=[DivisionByZero, Overflow, InvalidOperation],
5382 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005383 Emax=999999999,
5384 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005385 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005386)
5387
5388# Pre-made alternate contexts offered by the specification
5389# Don't change these; the user should be able to select these
5390# contexts and be able to reproduce results from other implementations
5391# of the spec.
5392
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005393BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005394 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005395 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5396 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005397)
5398
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005399ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005400 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005401 traps=[],
5402 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005403)
5404
5405
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005406##### crud for parsing strings #############################################
Christian Heimes23daade02008-02-25 12:39:23 +00005407#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005408# Regular expression used for parsing numeric strings. Additional
5409# comments:
5410#
5411# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5412# whitespace. But note that the specification disallows whitespace in
5413# a numeric string.
5414#
5415# 2. For finite numbers (not infinities and NaNs) the body of the
5416# number between the optional sign and the optional exponent must have
5417# at least one decimal digit, possibly after the decimal point. The
Antoine Pitroufd036452008-08-19 17:56:33 +00005418# lookahead expression '(?=[0-9]|\.[0-9])' checks this.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005419#
5420# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5421# other meaning for \d than the numbers [0-9].
5422
5423import re
Benjamin Peterson41181742008-07-02 20:22:54 +00005424_parser = re.compile(r""" # A numeric string consists of:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005425# \s*
Benjamin Peterson41181742008-07-02 20:22:54 +00005426 (?P<sign>[-+])? # an optional sign, followed by either...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005427 (
Benjamin Peterson41181742008-07-02 20:22:54 +00005428 (?=[0-9]|\.[0-9]) # ...a number (with at least one digit)
5429 (?P<int>[0-9]*) # having a (possibly empty) integer part
5430 (\.(?P<frac>[0-9]*))? # followed by an optional fractional part
5431 (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005432 |
Benjamin Peterson41181742008-07-02 20:22:54 +00005433 Inf(inity)? # ...an infinity, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005434 |
Benjamin Peterson41181742008-07-02 20:22:54 +00005435 (?P<signal>s)? # ...an (optionally signaling)
5436 NaN # NaN
5437 (?P<diag>[0-9]*) # with (possibly empty) diagnostic info.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005438 )
5439# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00005440 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005441""", re.VERBOSE | re.IGNORECASE).match
5442
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005443_all_zeros = re.compile('0*$').match
5444_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00005445
5446##### PEP3101 support functions ##############################################
5447# The functions parse_format_specifier and format_align have little to do
5448# with the Decimal class, and could potentially be reused for other pure
5449# Python numeric classes that want to implement __format__
5450#
5451# A format specifier for Decimal looks like:
5452#
5453# [[fill]align][sign][0][minimumwidth][.precision][type]
5454#
5455
5456_parse_format_specifier_regex = re.compile(r"""\A
5457(?:
5458 (?P<fill>.)?
5459 (?P<align>[<>=^])
5460)?
5461(?P<sign>[-+ ])?
5462(?P<zeropad>0)?
5463(?P<minimumwidth>(?!0)\d+)?
5464(?:\.(?P<precision>0|(?!0)\d+))?
5465(?P<type>[eEfFgG%])?
5466\Z
5467""", re.VERBOSE)
5468
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005469del re
5470
Christian Heimesf16baeb2008-02-29 14:57:44 +00005471def _parse_format_specifier(format_spec):
5472 """Parse and validate a format specifier.
5473
5474 Turns a standard numeric format specifier into a dict, with the
5475 following entries:
5476
5477 fill: fill character to pad field to minimum width
5478 align: alignment type, either '<', '>', '=' or '^'
5479 sign: either '+', '-' or ' '
5480 minimumwidth: nonnegative integer giving minimum width
5481 precision: nonnegative integer giving precision, or None
5482 type: one of the characters 'eEfFgG%', or None
5483 unicode: either True or False (always True for Python 3.x)
5484
5485 """
5486 m = _parse_format_specifier_regex.match(format_spec)
5487 if m is None:
5488 raise ValueError("Invalid format specifier: " + format_spec)
5489
5490 # get the dictionary
5491 format_dict = m.groupdict()
5492
5493 # defaults for fill and alignment
5494 fill = format_dict['fill']
5495 align = format_dict['align']
5496 if format_dict.pop('zeropad') is not None:
5497 # in the face of conflict, refuse the temptation to guess
5498 if fill is not None and fill != '0':
5499 raise ValueError("Fill character conflicts with '0'"
5500 " in format specifier: " + format_spec)
5501 if align is not None and align != '=':
5502 raise ValueError("Alignment conflicts with '0' in "
5503 "format specifier: " + format_spec)
5504 fill = '0'
5505 align = '='
5506 format_dict['fill'] = fill or ' '
5507 format_dict['align'] = align or '<'
5508
5509 if format_dict['sign'] is None:
5510 format_dict['sign'] = '-'
5511
5512 # turn minimumwidth and precision entries into integers.
5513 # minimumwidth defaults to 0; precision remains None if not given
5514 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5515 if format_dict['precision'] is not None:
5516 format_dict['precision'] = int(format_dict['precision'])
5517
5518 # if format type is 'g' or 'G' then a precision of 0 makes little
5519 # sense; convert it to 1. Same if format type is unspecified.
5520 if format_dict['precision'] == 0:
5521 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5522 format_dict['precision'] = 1
5523
5524 # record whether return type should be str or unicode
Christian Heimes295f4fa2008-02-29 15:03:39 +00005525 format_dict['unicode'] = True
Christian Heimesf16baeb2008-02-29 14:57:44 +00005526
5527 return format_dict
5528
5529def _format_align(body, spec_dict):
5530 """Given an unpadded, non-aligned numeric string, add padding and
5531 aligment to conform with the given format specifier dictionary (as
5532 output from parse_format_specifier).
5533
5534 It's assumed that if body is negative then it starts with '-'.
5535 Any leading sign ('-' or '+') is stripped from the body before
5536 applying the alignment and padding rules, and replaced in the
5537 appropriate position.
5538
5539 """
5540 # figure out the sign; we only examine the first character, so if
5541 # body has leading whitespace the results may be surprising.
5542 if len(body) > 0 and body[0] in '-+':
5543 sign = body[0]
5544 body = body[1:]
5545 else:
5546 sign = ''
5547
5548 if sign != '-':
5549 if spec_dict['sign'] in ' +':
5550 sign = spec_dict['sign']
5551 else:
5552 sign = ''
5553
5554 # how much extra space do we have to play with?
5555 minimumwidth = spec_dict['minimumwidth']
5556 fill = spec_dict['fill']
5557 padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5558
5559 align = spec_dict['align']
5560 if align == '<':
5561 result = padding + sign + body
5562 elif align == '>':
5563 result = sign + body + padding
5564 elif align == '=':
5565 result = sign + padding + body
5566 else: #align == '^'
5567 half = len(padding)//2
5568 result = padding[:half] + sign + body + padding[half:]
5569
Christian Heimesf16baeb2008-02-29 14:57:44 +00005570 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005571
Guido van Rossumd8faa362007-04-27 19:54:29 +00005572##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005573
Guido van Rossumd8faa362007-04-27 19:54:29 +00005574# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005575Inf = Decimal('Inf')
5576negInf = Decimal('-Inf')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005577NaN = Decimal('NaN')
5578Dec_0 = Decimal(0)
5579Dec_p1 = Decimal(1)
5580Dec_n1 = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005581
Guido van Rossumd8faa362007-04-27 19:54:29 +00005582# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005583Infsign = (Inf, negInf)
5584
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005585
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005586
5587if __name__ == '__main__':
5588 import doctest, sys
5589 doctest.testmod(sys.modules[__name__])