blob: 197269c7d731fb094be15aeff8566ecd2be710c6 [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 Hettinger771ed762009-01-03 19:20:32 +0000139import math as _math
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000140
Christian Heimes25bb7832008-01-11 16:17:00 +0000141try:
142 from collections import namedtuple as _namedtuple
143 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
144except ImportError:
145 DecimalTuple = lambda *args: args
146
Guido van Rossumd8faa362007-04-27 19:54:29 +0000147# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000148ROUND_DOWN = 'ROUND_DOWN'
149ROUND_HALF_UP = 'ROUND_HALF_UP'
150ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
151ROUND_CEILING = 'ROUND_CEILING'
152ROUND_FLOOR = 'ROUND_FLOOR'
153ROUND_UP = 'ROUND_UP'
154ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000155ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000156
Guido van Rossumd8faa362007-04-27 19:54:29 +0000157# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000158
159class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000160 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000161
162 Used exceptions derive from this.
163 If an exception derives from another exception besides this (such as
164 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
165 called if the others are present. This isn't actually used for
166 anything, though.
167
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000168 handle -- Called when context._raise_error is called and the
169 trap_enabler is set. First argument is self, second is the
170 context. More arguments can be given, those being after
171 the explanation in _raise_error (For example,
172 context._raise_error(NewError, '(-x)!', self._sign) would
173 call NewError().handle(context, self._sign).)
174
175 To define a new exception, it should be sufficient to have it derive
176 from DecimalException.
177 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000178 def handle(self, context, *args):
179 pass
180
181
182class Clamped(DecimalException):
183 """Exponent of a 0 changed to fit bounds.
184
185 This occurs and signals clamped if the exponent of a result has been
186 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000187 representation. This may occur when the exponent of a zero result would
188 be outside the bounds of a representation, or when a large normal
189 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000190 this latter case, the exponent is reduced to fit and the corresponding
191 number of zero digits are appended to the coefficient ("fold-down").
192 """
193
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000194class InvalidOperation(DecimalException):
195 """An invalid operation was performed.
196
197 Various bad things cause this:
198
199 Something creates a signaling NaN
200 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000201 0 * (+-)INF
202 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000203 x % 0
204 (+-)INF % x
205 x._rescale( non-integer )
206 sqrt(-x) , x > 0
207 0 ** 0
208 x ** (non-integer)
209 x ** (+-)INF
210 An operand is invalid
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000211
212 The result of the operation after these is a quiet positive NaN,
213 except when the cause is a signaling NaN, in which case the result is
214 also a quiet NaN, but with the original sign, and an optional
215 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000216 """
217 def handle(self, context, *args):
218 if args:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000219 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
220 return ans._fix_nan(context)
Mark Dickinsonf9236412009-01-02 23:23:21 +0000221 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000222
223class ConversionSyntax(InvalidOperation):
224 """Trying to convert badly formed string.
225
226 This occurs and signals invalid-operation if an string is being
227 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000228 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000229 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000230 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000231 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000232
233class DivisionByZero(DecimalException, ZeroDivisionError):
234 """Division by 0.
235
236 This occurs and signals division-by-zero if division of a finite number
237 by zero was attempted (during a divide-integer or divide operation, or a
238 power operation with negative right-hand operand), and the dividend was
239 not zero.
240
241 The result of the operation is [sign,inf], where sign is the exclusive
242 or of the signs of the operands for divide, or is 1 for an odd power of
243 -0, for power.
244 """
245
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000246 def handle(self, context, sign, *args):
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000247 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000248
249class DivisionImpossible(InvalidOperation):
250 """Cannot perform the division adequately.
251
252 This occurs and signals invalid-operation if the integer result of a
253 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000254 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000255 """
256
257 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000258 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000259
260class DivisionUndefined(InvalidOperation, ZeroDivisionError):
261 """Undefined result of division.
262
263 This occurs and signals invalid-operation if division by zero was
264 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000265 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000266 """
267
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000268 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000269 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000270
271class Inexact(DecimalException):
272 """Had to round, losing information.
273
274 This occurs and signals inexact whenever the result of an operation is
275 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000276 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000277 result in all cases is unchanged.
278
279 The inexact signal may be tested (or trapped) to determine if a given
280 operation (or sequence of operations) was inexact.
281 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000282
283class InvalidContext(InvalidOperation):
284 """Invalid context. Unknown rounding, for example.
285
286 This occurs and signals invalid-operation if an invalid context was
Guido van Rossumd8faa362007-04-27 19:54:29 +0000287 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000288 on creation and either the precision exceeds the capability of the
289 underlying concrete representation or an unknown or unsupported rounding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000290 was specified. These aspects of the context need only be checked when
291 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000292 """
293
294 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000295 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000296
297class Rounded(DecimalException):
298 """Number got rounded (not necessarily changed during rounding).
299
300 This occurs and signals rounded whenever the result of an operation is
301 rounded (that is, some zero or non-zero digits were discarded from the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000302 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000303 result in all cases is unchanged.
304
305 The rounded signal may be tested (or trapped) to determine if a given
306 operation (or sequence of operations) caused a loss of precision.
307 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000308
309class Subnormal(DecimalException):
310 """Exponent < Emin before rounding.
311
312 This occurs and signals subnormal whenever the result of a conversion or
313 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000314 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000315
316 The subnormal signal may be tested (or trapped) to determine if a given
317 or operation (or sequence of operations) yielded a subnormal result.
318 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000319
320class Overflow(Inexact, Rounded):
321 """Numerical overflow.
322
323 This occurs and signals overflow if the adjusted exponent of a result
324 (from a conversion or from an operation that is not an attempt to divide
325 by zero), after rounding, would be greater than the largest value that
326 can be handled by the implementation (the value Emax).
327
328 The result depends on the rounding mode:
329
330 For round-half-up and round-half-even (and for round-half-down and
331 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000332 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000333 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000334 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000335 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000336 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000338 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000339 will also be raised.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000340 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000341
342 def handle(self, context, sign, *args):
343 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000344 ROUND_HALF_DOWN, ROUND_UP):
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000345 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000346 if sign == 0:
347 if context.rounding == ROUND_CEILING:
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000348 return _SignedInfinity[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000349 return _dec_from_triple(sign, '9'*context.prec,
350 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000351 if sign == 1:
352 if context.rounding == ROUND_FLOOR:
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000353 return _SignedInfinity[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000354 return _dec_from_triple(sign, '9'*context.prec,
355 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000356
357
358class Underflow(Inexact, Rounded, Subnormal):
359 """Numerical underflow with result rounded to 0.
360
361 This occurs and signals underflow if a result is inexact and the
362 adjusted exponent of the result would be smaller (more negative) than
363 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000364 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000365
366 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000367 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000368 in 0 with the sign of the intermediate result and an exponent of Etiny.
369
370 In all cases, Inexact, Rounded, and Subnormal will also be raised.
371 """
372
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000373# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000374_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000375 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000376
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000377# Map conditions (per the spec) to signals
378_condition_map = {ConversionSyntax:InvalidOperation,
379 DivisionImpossible:InvalidOperation,
380 DivisionUndefined:InvalidOperation,
381 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000382
Guido van Rossumd8faa362007-04-27 19:54:29 +0000383##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000384
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000385# The getcontext() and setcontext() function manage access to a thread-local
386# current context. Py2.4 offers direct support for thread locals. If that
Georg Brandlf9926402008-06-13 06:32:25 +0000387# is not available, use threading.current_thread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000388# work for older Pythons. If threads are not part of the build, create a
389# mock threading object with threading.local() returning the module namespace.
390
391try:
392 import threading
393except ImportError:
394 # Python was compiled without threads; create a mock object instead
395 import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +0000396 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000397 def local(self, sys=sys):
398 return sys.modules[__name__]
399 threading = MockThreading()
400 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000401
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000402try:
403 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000404
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000405except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000406
Guido van Rossumd8faa362007-04-27 19:54:29 +0000407 # To fix reloading, force it to create a new context
408 # Old contexts have different exceptions in their dicts, making problems.
Georg Brandlf9926402008-06-13 06:32:25 +0000409 if hasattr(threading.current_thread(), '__decimal_context__'):
410 del threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000411
412 def setcontext(context):
413 """Set this thread's context to context."""
414 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000415 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000416 context.clear_flags()
Georg Brandlf9926402008-06-13 06:32:25 +0000417 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000418
419 def getcontext():
420 """Returns this thread's context.
421
422 If this thread does not yet have a context, returns
423 a new context and sets this thread's context.
424 New contexts are copies of DefaultContext.
425 """
426 try:
Georg Brandlf9926402008-06-13 06:32:25 +0000427 return threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000428 except AttributeError:
429 context = Context()
Georg Brandlf9926402008-06-13 06:32:25 +0000430 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000431 return context
432
433else:
434
435 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000436 if hasattr(local, '__decimal_context__'):
437 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000438
439 def getcontext(_local=local):
440 """Returns this thread's context.
441
442 If this thread does not yet have a context, returns
443 a new context and sets this thread's context.
444 New contexts are copies of DefaultContext.
445 """
446 try:
447 return _local.__decimal_context__
448 except AttributeError:
449 context = Context()
450 _local.__decimal_context__ = context
451 return context
452
453 def setcontext(context, _local=local):
454 """Set this thread's context to context."""
455 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000456 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000457 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000458 _local.__decimal_context__ = context
459
460 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000461
Thomas Wouters89f507f2006-12-13 04:49:30 +0000462def localcontext(ctx=None):
463 """Return a context manager for a copy of the supplied context
464
465 Uses a copy of the current context if no context is specified
466 The returned context manager creates a local decimal context
467 in a with statement:
468 def sin(x):
469 with localcontext() as ctx:
470 ctx.prec += 2
471 # Rest of sin calculation algorithm
472 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000473 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000474
475 def sin(x):
476 with localcontext(ExtendedContext):
477 # Rest of sin calculation algorithm
478 # uses the Extended Context from the
479 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000480 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000481
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000482 >>> setcontext(DefaultContext)
Guido van Rossum7131f842007-02-09 20:13:25 +0000483 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000484 28
485 >>> with localcontext():
486 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000487 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000488 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000489 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000490 30
491 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000492 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000493 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000494 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000495 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000496 28
497 """
498 if ctx is None: ctx = getcontext()
499 return _ContextManager(ctx)
500
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000501
Guido van Rossumd8faa362007-04-27 19:54:29 +0000502##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000503
Christian Heimes08976cb2008-03-16 00:32:36 +0000504class Decimal(_numbers.Real):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000505 """Floating point class for decimal arithmetic."""
506
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000507 __slots__ = ('_exp','_int','_sign', '_is_special')
508 # Generally, the value of the Decimal instance is given by
509 # (-1)**_sign * _int * 10**_exp
510 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000511
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000512 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000513 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000514 """Create a decimal point instance.
515
516 >>> Decimal('3.14') # string input
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000517 Decimal('3.14')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000518 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000519 Decimal('3.14')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000520 >>> Decimal(314) # int
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000521 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000522 >>> Decimal(Decimal(314)) # another decimal instance
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000523 Decimal('314')
Christian Heimesa62da1d2008-01-12 19:39:10 +0000524 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000525 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000526 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000527
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000528 # Note that the coefficient, self._int, is actually stored as
529 # a string rather than as a tuple of digits. This speeds up
530 # the "digits to integer" and "integer to digits" conversions
531 # that are used in almost every arithmetic operation on
532 # Decimals. This is an internal detail: the as_tuple function
533 # and the Decimal constructor still deal with tuples of
534 # digits.
535
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000536 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000537
Christian Heimesd59c64c2007-11-30 19:27:20 +0000538 # From a string
539 # REs insist on real strings, so we can too.
540 if isinstance(value, str):
Christian Heimesa62da1d2008-01-12 19:39:10 +0000541 m = _parser(value.strip())
Christian Heimesd59c64c2007-11-30 19:27:20 +0000542 if m is None:
543 if context is None:
544 context = getcontext()
545 return context._raise_error(ConversionSyntax,
546 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000547
Christian Heimesd59c64c2007-11-30 19:27:20 +0000548 if m.group('sign') == "-":
549 self._sign = 1
550 else:
551 self._sign = 0
552 intpart = m.group('int')
553 if intpart is not None:
554 # finite number
555 fracpart = m.group('frac')
556 exp = int(m.group('exp') or '0')
557 if fracpart is not None:
558 self._int = (intpart+fracpart).lstrip('0') or '0'
559 self._exp = exp - len(fracpart)
560 else:
561 self._int = intpart.lstrip('0') or '0'
562 self._exp = exp
563 self._is_special = False
564 else:
565 diag = m.group('diag')
566 if diag is not None:
567 # NaN
568 self._int = diag.lstrip('0')
569 if m.group('signal'):
570 self._exp = 'N'
571 else:
572 self._exp = 'n'
573 else:
574 # infinity
575 self._int = '0'
576 self._exp = 'F'
577 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000578 return self
579
580 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000581 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000582 if value >= 0:
583 self._sign = 0
584 else:
585 self._sign = 1
586 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000587 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000588 self._is_special = False
589 return self
590
591 # From another decimal
592 if isinstance(value, Decimal):
593 self._exp = value._exp
594 self._sign = value._sign
595 self._int = value._int
596 self._is_special = value._is_special
597 return self
598
599 # From an internal working value
600 if isinstance(value, _WorkRep):
601 self._sign = value.sign
602 self._int = str(value.int)
603 self._exp = int(value.exp)
604 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000605 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000606
607 # tuple/list conversion (possibly from as_tuple())
608 if isinstance(value, (list,tuple)):
609 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000610 raise ValueError('Invalid tuple size in creation of Decimal '
611 'from list or tuple. The list or tuple '
612 'should have exactly three elements.')
613 # process sign. The isinstance test rejects floats
614 if not (isinstance(value[0], int) and value[0] in (0,1)):
615 raise ValueError("Invalid sign. The first value in the tuple "
616 "should be an integer; either 0 for a "
617 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000618 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000619 if value[2] == 'F':
620 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000621 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000622 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000623 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000624 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000625 # process and validate the digits in value[1]
626 digits = []
627 for digit in value[1]:
628 if isinstance(digit, int) and 0 <= digit <= 9:
629 # skip leading zeros
630 if digits or digit != 0:
631 digits.append(digit)
632 else:
633 raise ValueError("The second value in the tuple must "
634 "be composed of integers in the range "
635 "0 through 9.")
636 if value[2] in ('n', 'N'):
637 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000638 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000639 self._exp = value[2]
640 self._is_special = True
641 elif isinstance(value[2], int):
642 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000643 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000644 self._exp = value[2]
645 self._is_special = False
646 else:
647 raise ValueError("The third value in the tuple must "
648 "be an integer, or one of the "
649 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000650 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000651
Raymond Hettingerbf440692004-07-10 14:14:37 +0000652 if isinstance(value, float):
653 raise TypeError("Cannot convert float to Decimal. " +
654 "First convert the float to a string")
655
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000656 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000657
Raymond Hettinger771ed762009-01-03 19:20:32 +0000658 @classmethod
659 def from_float(cls, f):
660 """Converts a float to a decimal number, exactly.
661
662 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
663 Since 0.1 is not exactly representable in binary floating point, the
664 value is stored as the nearest representable value which is
665 0x1.999999999999ap-4. The exact equivalent of the value in decimal
666 is 0.1000000000000000055511151231257827021181583404541015625.
667
668 >>> Decimal.from_float(0.1)
669 Decimal('0.1000000000000000055511151231257827021181583404541015625')
670 >>> Decimal.from_float(float('nan'))
671 Decimal('NaN')
672 >>> Decimal.from_float(float('inf'))
673 Decimal('Infinity')
674 >>> Decimal.from_float(-float('inf'))
675 Decimal('-Infinity')
676 >>> Decimal.from_float(-0.0)
677 Decimal('-0')
678
679 """
680 if isinstance(f, int): # handle integer inputs
681 return cls(f)
682 if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float
683 return cls(repr(f))
684 sign = 0 if _math.copysign(1.0, f) == 1.0 else 1
685 n, d = abs(f).as_integer_ratio()
686 k = d.bit_length() - 1
687 result = _dec_from_triple(sign, str(n*5**k), -k)
688 return result if cls is Decimal else cls(result)
689
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000690 def _isnan(self):
691 """Returns whether the number is not actually one.
692
693 0 if a number
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000694 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000695 2 if sNaN
696 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000697 if self._is_special:
698 exp = self._exp
699 if exp == 'n':
700 return 1
701 elif exp == 'N':
702 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000703 return 0
704
705 def _isinfinity(self):
706 """Returns whether the number is infinite
707
708 0 if finite or not a number
709 1 if +INF
710 -1 if -INF
711 """
712 if self._exp == 'F':
713 if self._sign:
714 return -1
715 return 1
716 return 0
717
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000718 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000719 """Returns whether the number is not actually one.
720
721 if self, other are sNaN, signal
722 if self, other are NaN return nan
723 return 0
724
725 Done before operations.
726 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000727
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000728 self_is_nan = self._isnan()
729 if other is None:
730 other_is_nan = False
731 else:
732 other_is_nan = other._isnan()
733
734 if self_is_nan or other_is_nan:
735 if context is None:
736 context = getcontext()
737
738 if self_is_nan == 2:
739 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000740 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000741 if other_is_nan == 2:
742 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000743 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000744 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000745 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000746
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000747 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000748 return 0
749
Christian Heimes77c02eb2008-02-09 02:18:51 +0000750 def _compare_check_nans(self, other, context):
751 """Version of _check_nans used for the signaling comparisons
752 compare_signal, __le__, __lt__, __ge__, __gt__.
753
754 Signal InvalidOperation if either self or other is a (quiet
755 or signaling) NaN. Signaling NaNs take precedence over quiet
756 NaNs.
757
758 Return 0 if neither operand is a NaN.
759
760 """
761 if context is None:
762 context = getcontext()
763
764 if self._is_special or other._is_special:
765 if self.is_snan():
766 return context._raise_error(InvalidOperation,
767 'comparison involving sNaN',
768 self)
769 elif other.is_snan():
770 return context._raise_error(InvalidOperation,
771 'comparison involving sNaN',
772 other)
773 elif self.is_qnan():
774 return context._raise_error(InvalidOperation,
775 'comparison involving NaN',
776 self)
777 elif other.is_qnan():
778 return context._raise_error(InvalidOperation,
779 'comparison involving NaN',
780 other)
781 return 0
782
Jack Diederich4dafcc42006-11-28 19:15:13 +0000783 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000784 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000785
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000786 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000787 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000788 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000789
Christian Heimes77c02eb2008-02-09 02:18:51 +0000790 def _cmp(self, other):
791 """Compare the two non-NaN decimal instances self and other.
792
793 Returns -1 if self < other, 0 if self == other and 1
794 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000795
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000796 if self._is_special or other._is_special:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000797 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000798
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000799 # check for zeros; note that cmp(0, -0) should return 0
800 if not self:
801 if not other:
802 return 0
803 else:
804 return -((-1)**other._sign)
805 if not other:
806 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000807
Guido van Rossumd8faa362007-04-27 19:54:29 +0000808 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000809 if other._sign < self._sign:
810 return -1
811 if self._sign < other._sign:
812 return 1
813
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000814 self_adjusted = self.adjusted()
815 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000816 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000817 self_padded = self._int + '0'*(self._exp - other._exp)
818 other_padded = other._int + '0'*(other._exp - self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000819 return cmp(self_padded, other_padded) * (-1)**self._sign
820 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000821 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000822 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000823 return -((-1)**self._sign)
824
Christian Heimes77c02eb2008-02-09 02:18:51 +0000825 # Note: The Decimal standard doesn't cover rich comparisons for
826 # Decimals. In particular, the specification is silent on the
827 # subject of what should happen for a comparison involving a NaN.
828 # We take the following approach:
829 #
830 # == comparisons involving a NaN always return False
831 # != comparisons involving a NaN always return True
832 # <, >, <= and >= comparisons involving a (quiet or signaling)
833 # NaN signal InvalidOperation, and return False if the
Christian Heimes3feef612008-02-11 06:19:17 +0000834 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000835 #
836 # This behavior is designed to conform as closely as possible to
837 # that specified by IEEE 754.
838
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000839 def __eq__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000840 other = _convert_other(other)
841 if other is NotImplemented:
842 return other
843 if self.is_nan() or other.is_nan():
844 return False
845 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000846
847 def __ne__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000848 other = _convert_other(other)
849 if other is NotImplemented:
850 return other
851 if self.is_nan() or other.is_nan():
852 return True
853 return self._cmp(other) != 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000854
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000855
Christian Heimes77c02eb2008-02-09 02:18:51 +0000856 def __lt__(self, other, context=None):
857 other = _convert_other(other)
858 if other is NotImplemented:
859 return other
860 ans = self._compare_check_nans(other, context)
861 if ans:
862 return False
863 return self._cmp(other) < 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000864
Christian Heimes77c02eb2008-02-09 02:18:51 +0000865 def __le__(self, other, context=None):
866 other = _convert_other(other)
867 if other is NotImplemented:
868 return other
869 ans = self._compare_check_nans(other, context)
870 if ans:
871 return False
872 return self._cmp(other) <= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000873
Christian Heimes77c02eb2008-02-09 02:18:51 +0000874 def __gt__(self, other, context=None):
875 other = _convert_other(other)
876 if other is NotImplemented:
877 return other
878 ans = self._compare_check_nans(other, context)
879 if ans:
880 return False
881 return self._cmp(other) > 0
882
883 def __ge__(self, other, context=None):
884 other = _convert_other(other)
885 if other is NotImplemented:
886 return other
887 ans = self._compare_check_nans(other, context)
888 if ans:
889 return False
890 return self._cmp(other) >= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000891
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000892 def compare(self, other, context=None):
893 """Compares one to another.
894
895 -1 => a < b
896 0 => a = b
897 1 => a > b
898 NaN => one is NaN
899 Like __cmp__, but returns Decimal instances.
900 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000901 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000902
Guido van Rossumd8faa362007-04-27 19:54:29 +0000903 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000904 if (self._is_special or other and other._is_special):
905 ans = self._check_nans(other, context)
906 if ans:
907 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000908
Christian Heimes77c02eb2008-02-09 02:18:51 +0000909 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000910
911 def __hash__(self):
912 """x.__hash__() <==> hash(x)"""
913 # Decimal integers must hash the same as the ints
Christian Heimes2380ac72008-01-09 00:17:24 +0000914 #
915 # The hash of a nonspecial noninteger Decimal must depend only
916 # on the value of that Decimal, and not on its representation.
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000917 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000918 if self._is_special:
919 if self._isnan():
920 raise TypeError('Cannot hash a NaN value.')
921 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000922 if not self:
923 return 0
924 if self._isinteger():
925 op = _WorkRep(self.to_integral_value())
926 # to make computation feasible for Decimals with large
927 # exponent, we use the fact that hash(n) == hash(m) for
928 # any two nonzero integers n and m such that (i) n and m
929 # have the same sign, and (ii) n is congruent to m modulo
930 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
931 # hash((-1)**s*c*pow(10, e, 2**64-1).
932 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Christian Heimes2380ac72008-01-09 00:17:24 +0000933 # The value of a nonzero nonspecial Decimal instance is
934 # faithfully represented by the triple consisting of its sign,
935 # its adjusted exponent, and its coefficient with trailing
936 # zeros removed.
937 return hash((self._sign,
938 self._exp+len(self._int),
939 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000940
941 def as_tuple(self):
942 """Represents the number as a triple tuple.
943
944 To show the internals exactly as they are.
945 """
Christian Heimes25bb7832008-01-11 16:17:00 +0000946 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000947
948 def __repr__(self):
949 """Represents the number as an instance of Decimal."""
950 # Invariant: eval(repr(d)) == d
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000951 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000952
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000953 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000954 """Return string representation of the number in scientific notation.
955
956 Captures all of the information in the underlying representation.
957 """
958
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000959 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000960 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000961 if self._exp == 'F':
962 return sign + 'Infinity'
963 elif self._exp == 'n':
964 return sign + 'NaN' + self._int
965 else: # self._exp == 'N'
966 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000967
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000968 # number of digits of self._int to left of decimal point
969 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000970
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000971 # dotplace is number of digits of self._int to the left of the
972 # decimal point in the mantissa of the output string (that is,
973 # after adjusting the exponent)
974 if self._exp <= 0 and leftdigits > -6:
975 # no exponent required
976 dotplace = leftdigits
977 elif not eng:
978 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000979 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000980 elif self._int == '0':
981 # engineering notation, zero
982 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000983 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000984 # engineering notation, nonzero
985 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000986
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000987 if dotplace <= 0:
988 intpart = '0'
989 fracpart = '.' + '0'*(-dotplace) + self._int
990 elif dotplace >= len(self._int):
991 intpart = self._int+'0'*(dotplace-len(self._int))
992 fracpart = ''
993 else:
994 intpart = self._int[:dotplace]
995 fracpart = '.' + self._int[dotplace:]
996 if leftdigits == dotplace:
997 exp = ''
998 else:
999 if context is None:
1000 context = getcontext()
1001 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1002
1003 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001004
1005 def to_eng_string(self, context=None):
1006 """Convert to engineering-type string.
1007
1008 Engineering notation has an exponent which is a multiple of 3, so there
1009 are up to 3 digits left of the decimal place.
1010
1011 Same rules for when in exponential and when as a value as in __str__.
1012 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001013 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001014
1015 def __neg__(self, context=None):
1016 """Returns a copy with the sign switched.
1017
1018 Rounds, if it has reason.
1019 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001020 if self._is_special:
1021 ans = self._check_nans(context=context)
1022 if ans:
1023 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001024
1025 if not self:
1026 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001027 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001028 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001029 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001030
1031 if context is None:
1032 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001033 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001034
1035 def __pos__(self, context=None):
1036 """Returns a copy, unless it is a sNaN.
1037
1038 Rounds the number (if more then precision digits)
1039 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001040 if self._is_special:
1041 ans = self._check_nans(context=context)
1042 if ans:
1043 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001044
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001045 if not self:
1046 # + (-0) = 0
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001047 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001048 else:
1049 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001050
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001051 if context is None:
1052 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001053 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001054
Christian Heimes2c181612007-12-17 20:04:13 +00001055 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001056 """Returns the absolute value of self.
1057
Christian Heimes2c181612007-12-17 20:04:13 +00001058 If the keyword argument 'round' is false, do not round. The
1059 expression self.__abs__(round=False) is equivalent to
1060 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001061 """
Christian Heimes2c181612007-12-17 20:04:13 +00001062 if not round:
1063 return self.copy_abs()
1064
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001065 if self._is_special:
1066 ans = self._check_nans(context=context)
1067 if ans:
1068 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001069
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001070 if self._sign:
1071 ans = self.__neg__(context=context)
1072 else:
1073 ans = self.__pos__(context=context)
1074
1075 return ans
1076
1077 def __add__(self, other, context=None):
1078 """Returns self + other.
1079
1080 -INF + INF (or the reverse) cause InvalidOperation errors.
1081 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001082 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001083 if other is NotImplemented:
1084 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001085
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001086 if context is None:
1087 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001088
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001089 if self._is_special or other._is_special:
1090 ans = self._check_nans(other, context)
1091 if ans:
1092 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001093
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001094 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001095 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001096 if self._sign != other._sign and other._isinfinity():
1097 return context._raise_error(InvalidOperation, '-INF + INF')
1098 return Decimal(self)
1099 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001100 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001101
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001102 exp = min(self._exp, other._exp)
1103 negativezero = 0
1104 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001105 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001106 negativezero = 1
1107
1108 if not self and not other:
1109 sign = min(self._sign, other._sign)
1110 if negativezero:
1111 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001112 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001113 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001114 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001115 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001116 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001117 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001118 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001119 return ans
1120 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001121 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001122 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001123 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001124 return ans
1125
1126 op1 = _WorkRep(self)
1127 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001128 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001129
1130 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001131 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001132 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001133 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001134 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001135 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001137 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001138 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001139 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001140 if op1.sign == 1:
1141 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001142 op1.sign, op2.sign = op2.sign, op1.sign
1143 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001144 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001145 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001146 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001147 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001148 op1.sign, op2.sign = (0, 0)
1149 else:
1150 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001151 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001152
Raymond Hettinger17931de2004-10-27 06:21:46 +00001153 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001154 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001155 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001156 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001157
1158 result.exp = op1.exp
1159 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001160 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001161 return ans
1162
1163 __radd__ = __add__
1164
1165 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001166 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001167 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001168 if other is NotImplemented:
1169 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001170
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001171 if self._is_special or other._is_special:
1172 ans = self._check_nans(other, context=context)
1173 if ans:
1174 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001175
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001176 # self - other is computed as self + other.copy_negate()
1177 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001178
1179 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001180 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001181 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001182 if other is NotImplemented:
1183 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001184
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001185 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001186
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001187 def __mul__(self, other, context=None):
1188 """Return self * other.
1189
1190 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1191 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001192 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001193 if other is NotImplemented:
1194 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001195
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001196 if context is None:
1197 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001198
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001199 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001200
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001201 if self._is_special or other._is_special:
1202 ans = self._check_nans(other, context)
1203 if ans:
1204 return ans
1205
1206 if self._isinfinity():
1207 if not other:
1208 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001209 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001210
1211 if other._isinfinity():
1212 if not self:
1213 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001214 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001215
1216 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001217
1218 # Special case for multiplying by zero
1219 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001220 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001221 # Fixing in case the exponent is out of bounds
1222 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001223 return ans
1224
1225 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001226 if self._int == '1':
1227 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001228 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001229 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001230 if other._int == '1':
1231 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001232 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001233 return ans
1234
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001235 op1 = _WorkRep(self)
1236 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001237
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001238 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001239 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001240
1241 return ans
1242 __rmul__ = __mul__
1243
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001244 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001245 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001246 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001247 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001248 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001249
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001250 if context is None:
1251 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001252
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001253 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001254
1255 if self._is_special or other._is_special:
1256 ans = self._check_nans(other, context)
1257 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001258 return ans
1259
1260 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001261 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001262
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001263 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001264 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001265
1266 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001267 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001268 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001269
1270 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001271 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001272 if not self:
1273 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001274 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001275
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001276 if not self:
1277 exp = self._exp - other._exp
1278 coeff = 0
1279 else:
1280 # OK, so neither = 0, INF or NaN
1281 shift = len(other._int) - len(self._int) + context.prec + 1
1282 exp = self._exp - other._exp - shift
1283 op1 = _WorkRep(self)
1284 op2 = _WorkRep(other)
1285 if shift >= 0:
1286 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1287 else:
1288 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1289 if remainder:
1290 # result is not exact; adjust to ensure correct rounding
1291 if coeff % 5 == 0:
1292 coeff += 1
1293 else:
1294 # result is exact; get as close to ideal exponent as possible
1295 ideal_exp = self._exp - other._exp
1296 while exp < ideal_exp and coeff % 10 == 0:
1297 coeff //= 10
1298 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001299
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001300 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001301 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001302
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001303 def _divide(self, other, context):
1304 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001305
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001306 Assumes that neither self nor other is a NaN, that self is not
1307 infinite and that other is nonzero.
1308 """
1309 sign = self._sign ^ other._sign
1310 if other._isinfinity():
1311 ideal_exp = self._exp
1312 else:
1313 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001314
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001315 expdiff = self.adjusted() - other.adjusted()
1316 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001317 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001318 self._rescale(ideal_exp, context.rounding))
1319 if expdiff <= context.prec:
1320 op1 = _WorkRep(self)
1321 op2 = _WorkRep(other)
1322 if op1.exp >= op2.exp:
1323 op1.int *= 10**(op1.exp - op2.exp)
1324 else:
1325 op2.int *= 10**(op2.exp - op1.exp)
1326 q, r = divmod(op1.int, op2.int)
1327 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001328 return (_dec_from_triple(sign, str(q), 0),
1329 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001330
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001331 # Here the quotient is too large to be representable
1332 ans = context._raise_error(DivisionImpossible,
1333 'quotient too large in //, % or divmod')
1334 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001335
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001336 def __rtruediv__(self, other, context=None):
1337 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001338 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001339 if other is NotImplemented:
1340 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001341 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001342
1343 def __divmod__(self, other, context=None):
1344 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001345 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001346 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001347 other = _convert_other(other)
1348 if other is NotImplemented:
1349 return other
1350
1351 if context is None:
1352 context = getcontext()
1353
1354 ans = self._check_nans(other, context)
1355 if ans:
1356 return (ans, ans)
1357
1358 sign = self._sign ^ other._sign
1359 if self._isinfinity():
1360 if other._isinfinity():
1361 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1362 return ans, ans
1363 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001364 return (_SignedInfinity[sign],
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001365 context._raise_error(InvalidOperation, 'INF % x'))
1366
1367 if not other:
1368 if not self:
1369 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1370 return ans, ans
1371 else:
1372 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1373 context._raise_error(InvalidOperation, 'x % 0'))
1374
1375 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001376 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001377 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001378
1379 def __rdivmod__(self, other, context=None):
1380 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001381 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001382 if other is NotImplemented:
1383 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001384 return other.__divmod__(self, context=context)
1385
1386 def __mod__(self, other, context=None):
1387 """
1388 self % other
1389 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001390 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001391 if other is NotImplemented:
1392 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001393
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001394 if context is None:
1395 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001396
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001397 ans = self._check_nans(other, context)
1398 if ans:
1399 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001400
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001401 if self._isinfinity():
1402 return context._raise_error(InvalidOperation, 'INF % x')
1403 elif not other:
1404 if self:
1405 return context._raise_error(InvalidOperation, 'x % 0')
1406 else:
1407 return context._raise_error(DivisionUndefined, '0 % 0')
1408
1409 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001410 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001411 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001412
1413 def __rmod__(self, other, context=None):
1414 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001415 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001416 if other is NotImplemented:
1417 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001418 return other.__mod__(self, context=context)
1419
1420 def remainder_near(self, other, context=None):
1421 """
1422 Remainder nearest to 0- abs(remainder-near) <= other/2
1423 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001424 if context is None:
1425 context = getcontext()
1426
1427 other = _convert_other(other, raiseit=True)
1428
1429 ans = self._check_nans(other, context)
1430 if ans:
1431 return ans
1432
1433 # self == +/-infinity -> InvalidOperation
1434 if self._isinfinity():
1435 return context._raise_error(InvalidOperation,
1436 'remainder_near(infinity, x)')
1437
1438 # other == 0 -> either InvalidOperation or DivisionUndefined
1439 if not other:
1440 if self:
1441 return context._raise_error(InvalidOperation,
1442 'remainder_near(x, 0)')
1443 else:
1444 return context._raise_error(DivisionUndefined,
1445 'remainder_near(0, 0)')
1446
1447 # other = +/-infinity -> remainder = self
1448 if other._isinfinity():
1449 ans = Decimal(self)
1450 return ans._fix(context)
1451
1452 # self = 0 -> remainder = self, with ideal exponent
1453 ideal_exponent = min(self._exp, other._exp)
1454 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001455 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001456 return ans._fix(context)
1457
1458 # catch most cases of large or small quotient
1459 expdiff = self.adjusted() - other.adjusted()
1460 if expdiff >= context.prec + 1:
1461 # expdiff >= prec+1 => abs(self/other) > 10**prec
1462 return context._raise_error(DivisionImpossible)
1463 if expdiff <= -2:
1464 # expdiff <= -2 => abs(self/other) < 0.1
1465 ans = self._rescale(ideal_exponent, context.rounding)
1466 return ans._fix(context)
1467
1468 # adjust both arguments to have the same exponent, then divide
1469 op1 = _WorkRep(self)
1470 op2 = _WorkRep(other)
1471 if op1.exp >= op2.exp:
1472 op1.int *= 10**(op1.exp - op2.exp)
1473 else:
1474 op2.int *= 10**(op2.exp - op1.exp)
1475 q, r = divmod(op1.int, op2.int)
1476 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1477 # 10**ideal_exponent. Apply correction to ensure that
1478 # abs(remainder) <= abs(other)/2
1479 if 2*r + (q&1) > op2.int:
1480 r -= op2.int
1481 q += 1
1482
1483 if q >= 10**context.prec:
1484 return context._raise_error(DivisionImpossible)
1485
1486 # result has same sign as self unless r is negative
1487 sign = self._sign
1488 if r < 0:
1489 sign = 1-sign
1490 r = -r
1491
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001492 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001493 return ans._fix(context)
1494
1495 def __floordiv__(self, other, context=None):
1496 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001497 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001498 if other is NotImplemented:
1499 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001500
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001501 if context is None:
1502 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001503
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001504 ans = self._check_nans(other, context)
1505 if ans:
1506 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001507
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001508 if self._isinfinity():
1509 if other._isinfinity():
1510 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001511 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001512 return _SignedInfinity[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001513
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001514 if not other:
1515 if self:
1516 return context._raise_error(DivisionByZero, 'x // 0',
1517 self._sign ^ other._sign)
1518 else:
1519 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001520
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001521 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001522
1523 def __rfloordiv__(self, other, context=None):
1524 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001525 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001526 if other is NotImplemented:
1527 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001528 return other.__floordiv__(self, context=context)
1529
1530 def __float__(self):
1531 """Float representation."""
1532 return float(str(self))
1533
1534 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001535 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001536 if self._is_special:
1537 if self._isnan():
1538 context = getcontext()
1539 return context._raise_error(InvalidContext)
1540 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001541 raise OverflowError("Cannot convert infinity to int")
1542 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001543 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001544 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001545 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001546 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001547
Christian Heimes969fe572008-01-25 11:23:10 +00001548 __trunc__ = __int__
1549
Christian Heimes0bd4e112008-02-12 22:59:25 +00001550 @property
1551 def real(self):
1552 return self
1553
1554 @property
1555 def imag(self):
1556 return Decimal(0)
1557
1558 def conjugate(self):
1559 return self
1560
1561 def __complex__(self):
1562 return complex(float(self))
1563
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001564 def _fix_nan(self, context):
1565 """Decapitate the payload of a NaN to fit the context"""
1566 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001567
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001568 # maximum length of payload is precision if _clamp=0,
1569 # precision-1 if _clamp=1.
1570 max_payload_len = context.prec - context._clamp
1571 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001572 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1573 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001574 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001575
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001576 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001577 """Round if it is necessary to keep self within prec precision.
1578
1579 Rounds and fixes the exponent. Does not raise on a sNaN.
1580
1581 Arguments:
1582 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001583 context - context used.
1584 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001585
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001586 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001587 if self._isnan():
1588 # decapitate payload if necessary
1589 return self._fix_nan(context)
1590 else:
1591 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001592 return Decimal(self)
1593
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001594 # if self is zero then exponent should be between Etiny and
1595 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1596 Etiny = context.Etiny()
1597 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001598 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001599 exp_max = [context.Emax, Etop][context._clamp]
1600 new_exp = min(max(self._exp, Etiny), exp_max)
1601 if new_exp != self._exp:
1602 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001603 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001604 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001605 return Decimal(self)
1606
1607 # exp_min is the smallest allowable exponent of the result,
1608 # equal to max(self.adjusted()-context.prec+1, Etiny)
1609 exp_min = len(self._int) + self._exp - context.prec
1610 if exp_min > Etop:
1611 # overflow: exp_min > Etop iff self.adjusted() > Emax
1612 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001613 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001614 return context._raise_error(Overflow, 'above Emax', self._sign)
1615 self_is_subnormal = exp_min < Etiny
1616 if self_is_subnormal:
1617 context._raise_error(Subnormal)
1618 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001619
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001620 # round if self has too many digits
1621 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001622 context._raise_error(Rounded)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001623 digits = len(self._int) + self._exp - exp_min
1624 if digits < 0:
1625 self = _dec_from_triple(self._sign, '1', exp_min-1)
1626 digits = 0
1627 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1628 changed = this_function(digits)
1629 coeff = self._int[:digits] or '0'
1630 if changed == 1:
1631 coeff = str(int(coeff)+1)
1632 ans = _dec_from_triple(self._sign, coeff, exp_min)
1633
1634 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001635 context._raise_error(Inexact)
1636 if self_is_subnormal:
1637 context._raise_error(Underflow)
1638 if not ans:
1639 # raise Clamped on underflow to 0
1640 context._raise_error(Clamped)
1641 elif len(ans._int) == context.prec+1:
1642 # we get here only if rescaling rounds the
1643 # cofficient up to exactly 10**context.prec
1644 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001645 ans = _dec_from_triple(ans._sign,
1646 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001647 else:
1648 # Inexact and Rounded have already been raised
1649 ans = context._raise_error(Overflow, 'above Emax',
1650 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001651 return ans
1652
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001653 # fold down if _clamp == 1 and self has too few digits
1654 if context._clamp == 1 and self._exp > Etop:
1655 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001656 self_padded = self._int + '0'*(self._exp - Etop)
1657 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001658
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001659 # here self was representable to begin with; return unchanged
1660 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001661
1662 _pick_rounding_function = {}
1663
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001664 # for each of the rounding functions below:
1665 # self is a finite, nonzero Decimal
1666 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001667 #
1668 # each function returns either -1, 0, or 1, as follows:
1669 # 1 indicates that self should be rounded up (away from zero)
1670 # 0 indicates that self should be truncated, and that all the
1671 # digits to be truncated are zeros (so the value is unchanged)
1672 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001673
1674 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001675 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001676 if _all_zeros(self._int, prec):
1677 return 0
1678 else:
1679 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001680
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001681 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001682 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001683 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001684
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001685 def _round_half_up(self, prec):
1686 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001687 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001688 return 1
1689 elif _all_zeros(self._int, prec):
1690 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001691 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001692 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001693
1694 def _round_half_down(self, prec):
1695 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001696 if _exact_half(self._int, prec):
1697 return -1
1698 else:
1699 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001700
1701 def _round_half_even(self, prec):
1702 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001703 if _exact_half(self._int, prec) and \
1704 (prec == 0 or self._int[prec-1] in '02468'):
1705 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001706 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001707 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001708
1709 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001710 """Rounds up (not away from 0 if negative.)"""
1711 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001712 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001713 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001714 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001715
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001716 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001717 """Rounds down (not towards 0 if negative)"""
1718 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001719 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001720 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001721 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001722
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001723 def _round_05up(self, prec):
1724 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001725 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001726 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001727 else:
1728 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001729
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001730 def __round__(self, n=None):
1731 """Round self to the nearest integer, or to a given precision.
1732
1733 If only one argument is supplied, round a finite Decimal
1734 instance self to the nearest integer. If self is infinite or
1735 a NaN then a Python exception is raised. If self is finite
1736 and lies exactly halfway between two integers then it is
1737 rounded to the integer with even last digit.
1738
1739 >>> round(Decimal('123.456'))
1740 123
1741 >>> round(Decimal('-456.789'))
1742 -457
1743 >>> round(Decimal('-3.0'))
1744 -3
1745 >>> round(Decimal('2.5'))
1746 2
1747 >>> round(Decimal('3.5'))
1748 4
1749 >>> round(Decimal('Inf'))
1750 Traceback (most recent call last):
1751 ...
1752 ...
1753 ...
1754 OverflowError: cannot round an infinity
1755 >>> round(Decimal('NaN'))
1756 Traceback (most recent call last):
1757 ...
1758 ...
1759 ...
1760 ValueError: cannot round a NaN
1761
1762 If a second argument n is supplied, self is rounded to n
1763 decimal places using the rounding mode for the current
1764 context.
1765
1766 For an integer n, round(self, -n) is exactly equivalent to
1767 self.quantize(Decimal('1En')).
1768
1769 >>> round(Decimal('123.456'), 0)
1770 Decimal('123')
1771 >>> round(Decimal('123.456'), 2)
1772 Decimal('123.46')
1773 >>> round(Decimal('123.456'), -2)
1774 Decimal('1E+2')
1775 >>> round(Decimal('-Infinity'), 37)
1776 Decimal('NaN')
1777 >>> round(Decimal('sNaN123'), 0)
1778 Decimal('NaN123')
1779
1780 """
1781 if n is not None:
1782 # two-argument form: use the equivalent quantize call
1783 if not isinstance(n, int):
1784 raise TypeError('Second argument to round should be integral')
1785 exp = _dec_from_triple(0, '1', -n)
1786 return self.quantize(exp)
1787
1788 # one-argument form
1789 if self._is_special:
1790 if self.is_nan():
1791 raise ValueError("cannot round a NaN")
1792 else:
1793 raise OverflowError("cannot round an infinity")
1794 return int(self._rescale(0, ROUND_HALF_EVEN))
1795
1796 def __floor__(self):
1797 """Return the floor of self, as an integer.
1798
1799 For a finite Decimal instance self, return the greatest
1800 integer n such that n <= self. If self is infinite or a NaN
1801 then a Python exception is raised.
1802
1803 """
1804 if self._is_special:
1805 if self.is_nan():
1806 raise ValueError("cannot round a NaN")
1807 else:
1808 raise OverflowError("cannot round an infinity")
1809 return int(self._rescale(0, ROUND_FLOOR))
1810
1811 def __ceil__(self):
1812 """Return the ceiling of self, as an integer.
1813
1814 For a finite Decimal instance self, return the least integer n
1815 such that n >= self. If self is infinite or a NaN then a
1816 Python exception is raised.
1817
1818 """
1819 if self._is_special:
1820 if self.is_nan():
1821 raise ValueError("cannot round a NaN")
1822 else:
1823 raise OverflowError("cannot round an infinity")
1824 return int(self._rescale(0, ROUND_CEILING))
1825
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001826 def fma(self, other, third, context=None):
1827 """Fused multiply-add.
1828
1829 Returns self*other+third with no rounding of the intermediate
1830 product self*other.
1831
1832 self and other are multiplied together, with no rounding of
1833 the result. The third operand is then added to the result,
1834 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001835 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001836
1837 other = _convert_other(other, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001838
1839 # compute product; raise InvalidOperation if either operand is
1840 # a signaling NaN or if the product is zero times infinity.
1841 if self._is_special or other._is_special:
1842 if context is None:
1843 context = getcontext()
1844 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001845 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001846 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001847 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001848 if self._exp == 'n':
1849 product = self
1850 elif other._exp == 'n':
1851 product = other
1852 elif self._exp == 'F':
1853 if not other:
1854 return context._raise_error(InvalidOperation,
1855 'INF * 0 in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001856 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001857 elif other._exp == 'F':
1858 if not self:
1859 return context._raise_error(InvalidOperation,
1860 '0 * INF in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001861 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001862 else:
1863 product = _dec_from_triple(self._sign ^ other._sign,
1864 str(int(self._int) * int(other._int)),
1865 self._exp + other._exp)
1866
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001867 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001868 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001869
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001870 def _power_modulo(self, other, modulo, context=None):
1871 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001872
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001873 # if can't convert other and modulo to Decimal, raise
1874 # TypeError; there's no point returning NotImplemented (no
1875 # equivalent of __rpow__ for three argument pow)
1876 other = _convert_other(other, raiseit=True)
1877 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001878
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001879 if context is None:
1880 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001881
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001882 # deal with NaNs: if there are any sNaNs then first one wins,
1883 # (i.e. behaviour for NaNs is identical to that of fma)
1884 self_is_nan = self._isnan()
1885 other_is_nan = other._isnan()
1886 modulo_is_nan = modulo._isnan()
1887 if self_is_nan or other_is_nan or modulo_is_nan:
1888 if self_is_nan == 2:
1889 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001890 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001891 if other_is_nan == 2:
1892 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001893 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001894 if modulo_is_nan == 2:
1895 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001896 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001897 if self_is_nan:
1898 return self._fix_nan(context)
1899 if other_is_nan:
1900 return other._fix_nan(context)
1901 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001902
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001903 # check inputs: we apply same restrictions as Python's pow()
1904 if not (self._isinteger() and
1905 other._isinteger() and
1906 modulo._isinteger()):
1907 return context._raise_error(InvalidOperation,
1908 'pow() 3rd argument not allowed '
1909 'unless all arguments are integers')
1910 if other < 0:
1911 return context._raise_error(InvalidOperation,
1912 'pow() 2nd argument cannot be '
1913 'negative when 3rd argument specified')
1914 if not modulo:
1915 return context._raise_error(InvalidOperation,
1916 'pow() 3rd argument cannot be 0')
1917
1918 # additional restriction for decimal: the modulus must be less
1919 # than 10**prec in absolute value
1920 if modulo.adjusted() >= context.prec:
1921 return context._raise_error(InvalidOperation,
1922 'insufficient precision: pow() 3rd '
1923 'argument must not have more than '
1924 'precision digits')
1925
1926 # define 0**0 == NaN, for consistency with two-argument pow
1927 # (even though it hurts!)
1928 if not other and not self:
1929 return context._raise_error(InvalidOperation,
1930 'at least one of pow() 1st argument '
1931 'and 2nd argument must be nonzero ;'
1932 '0**0 is not defined')
1933
1934 # compute sign of result
1935 if other._iseven():
1936 sign = 0
1937 else:
1938 sign = self._sign
1939
1940 # convert modulo to a Python integer, and self and other to
1941 # Decimal integers (i.e. force their exponents to be >= 0)
1942 modulo = abs(int(modulo))
1943 base = _WorkRep(self.to_integral_value())
1944 exponent = _WorkRep(other.to_integral_value())
1945
1946 # compute result using integer pow()
1947 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1948 for i in range(exponent.exp):
1949 base = pow(base, 10, modulo)
1950 base = pow(base, exponent.int, modulo)
1951
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001952 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001953
1954 def _power_exact(self, other, p):
1955 """Attempt to compute self**other exactly.
1956
1957 Given Decimals self and other and an integer p, attempt to
1958 compute an exact result for the power self**other, with p
1959 digits of precision. Return None if self**other is not
1960 exactly representable in p digits.
1961
1962 Assumes that elimination of special cases has already been
1963 performed: self and other must both be nonspecial; self must
1964 be positive and not numerically equal to 1; other must be
1965 nonzero. For efficiency, other._exp should not be too large,
1966 so that 10**abs(other._exp) is a feasible calculation."""
1967
1968 # In the comments below, we write x for the value of self and
1969 # y for the value of other. Write x = xc*10**xe and y =
1970 # yc*10**ye.
1971
1972 # The main purpose of this method is to identify the *failure*
1973 # of x**y to be exactly representable with as little effort as
1974 # possible. So we look for cheap and easy tests that
1975 # eliminate the possibility of x**y being exact. Only if all
1976 # these tests are passed do we go on to actually compute x**y.
1977
1978 # Here's the main idea. First normalize both x and y. We
1979 # express y as a rational m/n, with m and n relatively prime
1980 # and n>0. Then for x**y to be exactly representable (at
1981 # *any* precision), xc must be the nth power of a positive
1982 # integer and xe must be divisible by n. If m is negative
1983 # then additionally xc must be a power of either 2 or 5, hence
1984 # a power of 2**n or 5**n.
1985 #
1986 # There's a limit to how small |y| can be: if y=m/n as above
1987 # then:
1988 #
1989 # (1) if xc != 1 then for the result to be representable we
1990 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1991 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1992 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1993 # representable.
1994 #
1995 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1996 # |y| < 1/|xe| then the result is not representable.
1997 #
1998 # Note that since x is not equal to 1, at least one of (1) and
1999 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2000 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2001 #
2002 # There's also a limit to how large y can be, at least if it's
2003 # positive: the normalized result will have coefficient xc**y,
2004 # so if it's representable then xc**y < 10**p, and y <
2005 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
2006 # not exactly representable.
2007
2008 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2009 # so |y| < 1/xe and the result is not representable.
2010 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2011 # < 1/nbits(xc).
2012
2013 x = _WorkRep(self)
2014 xc, xe = x.int, x.exp
2015 while xc % 10 == 0:
2016 xc //= 10
2017 xe += 1
2018
2019 y = _WorkRep(other)
2020 yc, ye = y.int, y.exp
2021 while yc % 10 == 0:
2022 yc //= 10
2023 ye += 1
2024
2025 # case where xc == 1: result is 10**(xe*y), with xe*y
2026 # required to be an integer
2027 if xc == 1:
2028 if ye >= 0:
2029 exponent = xe*yc*10**ye
2030 else:
2031 exponent, remainder = divmod(xe*yc, 10**-ye)
2032 if remainder:
2033 return None
2034 if y.sign == 1:
2035 exponent = -exponent
2036 # if other is a nonnegative integer, use ideal exponent
2037 if other._isinteger() and other._sign == 0:
2038 ideal_exponent = self._exp*int(other)
2039 zeros = min(exponent-ideal_exponent, p-1)
2040 else:
2041 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002042 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002043
2044 # case where y is negative: xc must be either a power
2045 # of 2 or a power of 5.
2046 if y.sign == 1:
2047 last_digit = xc % 10
2048 if last_digit in (2,4,6,8):
2049 # quick test for power of 2
2050 if xc & -xc != xc:
2051 return None
2052 # now xc is a power of 2; e is its exponent
2053 e = _nbits(xc)-1
2054 # find e*y and xe*y; both must be integers
2055 if ye >= 0:
2056 y_as_int = yc*10**ye
2057 e = e*y_as_int
2058 xe = xe*y_as_int
2059 else:
2060 ten_pow = 10**-ye
2061 e, remainder = divmod(e*yc, ten_pow)
2062 if remainder:
2063 return None
2064 xe, remainder = divmod(xe*yc, ten_pow)
2065 if remainder:
2066 return None
2067
2068 if e*65 >= p*93: # 93/65 > log(10)/log(5)
2069 return None
2070 xc = 5**e
2071
2072 elif last_digit == 5:
2073 # e >= log_5(xc) if xc is a power of 5; we have
2074 # equality all the way up to xc=5**2658
2075 e = _nbits(xc)*28//65
2076 xc, remainder = divmod(5**e, xc)
2077 if remainder:
2078 return None
2079 while xc % 5 == 0:
2080 xc //= 5
2081 e -= 1
2082 if ye >= 0:
2083 y_as_integer = yc*10**ye
2084 e = e*y_as_integer
2085 xe = xe*y_as_integer
2086 else:
2087 ten_pow = 10**-ye
2088 e, remainder = divmod(e*yc, ten_pow)
2089 if remainder:
2090 return None
2091 xe, remainder = divmod(xe*yc, ten_pow)
2092 if remainder:
2093 return None
2094 if e*3 >= p*10: # 10/3 > log(10)/log(2)
2095 return None
2096 xc = 2**e
2097 else:
2098 return None
2099
2100 if xc >= 10**p:
2101 return None
2102 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002103 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002104
2105 # now y is positive; find m and n such that y = m/n
2106 if ye >= 0:
2107 m, n = yc*10**ye, 1
2108 else:
2109 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2110 return None
2111 xc_bits = _nbits(xc)
2112 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2113 return None
2114 m, n = yc, 10**(-ye)
2115 while m % 2 == n % 2 == 0:
2116 m //= 2
2117 n //= 2
2118 while m % 5 == n % 5 == 0:
2119 m //= 5
2120 n //= 5
2121
2122 # compute nth root of xc*10**xe
2123 if n > 1:
2124 # if 1 < xc < 2**n then xc isn't an nth power
2125 if xc != 1 and xc_bits <= n:
2126 return None
2127
2128 xe, rem = divmod(xe, n)
2129 if rem != 0:
2130 return None
2131
2132 # compute nth root of xc using Newton's method
2133 a = 1 << -(-_nbits(xc)//n) # initial estimate
2134 while True:
2135 q, r = divmod(xc, a**(n-1))
2136 if a <= q:
2137 break
2138 else:
2139 a = (a*(n-1) + q)//n
2140 if not (a == q and r == 0):
2141 return None
2142 xc = a
2143
2144 # now xc*10**xe is the nth root of the original xc*10**xe
2145 # compute mth power of xc*10**xe
2146
2147 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2148 # 10**p and the result is not representable.
2149 if xc > 1 and m > p*100//_log10_lb(xc):
2150 return None
2151 xc = xc**m
2152 xe *= m
2153 if xc > 10**p:
2154 return None
2155
2156 # by this point the result *is* exactly representable
2157 # adjust the exponent to get as close as possible to the ideal
2158 # exponent, if necessary
2159 str_xc = str(xc)
2160 if other._isinteger() and other._sign == 0:
2161 ideal_exponent = self._exp*int(other)
2162 zeros = min(xe-ideal_exponent, p-len(str_xc))
2163 else:
2164 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002165 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002166
2167 def __pow__(self, other, modulo=None, context=None):
2168 """Return self ** other [ % modulo].
2169
2170 With two arguments, compute self**other.
2171
2172 With three arguments, compute (self**other) % modulo. For the
2173 three argument form, the following restrictions on the
2174 arguments hold:
2175
2176 - all three arguments must be integral
2177 - other must be nonnegative
2178 - either self or other (or both) must be nonzero
2179 - modulo must be nonzero and must have at most p digits,
2180 where p is the context precision.
2181
2182 If any of these restrictions is violated the InvalidOperation
2183 flag is raised.
2184
2185 The result of pow(self, other, modulo) is identical to the
2186 result that would be obtained by computing (self**other) %
2187 modulo with unbounded precision, but is computed more
2188 efficiently. It is always exact.
2189 """
2190
2191 if modulo is not None:
2192 return self._power_modulo(other, modulo, context)
2193
2194 other = _convert_other(other)
2195 if other is NotImplemented:
2196 return other
2197
2198 if context is None:
2199 context = getcontext()
2200
2201 # either argument is a NaN => result is NaN
2202 ans = self._check_nans(other, context)
2203 if ans:
2204 return ans
2205
2206 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2207 if not other:
2208 if not self:
2209 return context._raise_error(InvalidOperation, '0 ** 0')
2210 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002211 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002212
2213 # result has sign 1 iff self._sign is 1 and other is an odd integer
2214 result_sign = 0
2215 if self._sign == 1:
2216 if other._isinteger():
2217 if not other._iseven():
2218 result_sign = 1
2219 else:
2220 # -ve**noninteger = NaN
2221 # (-0)**noninteger = 0**noninteger
2222 if self:
2223 return context._raise_error(InvalidOperation,
2224 'x ** y with x negative and y not an integer')
2225 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002226 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002227
2228 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2229 if not self:
2230 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002231 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002232 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002233 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002234
2235 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002236 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002237 if other._sign == 0:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002238 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002239 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002240 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002241
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002242 # 1**other = 1, but the choice of exponent and the flags
2243 # depend on the exponent of self, and on whether other is a
2244 # positive integer, a negative integer, or neither
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002245 if self == _One:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002246 if other._isinteger():
2247 # exp = max(self._exp*max(int(other), 0),
2248 # 1-context.prec) but evaluating int(other) directly
2249 # is dangerous until we know other is small (other
2250 # could be 1e999999999)
2251 if other._sign == 1:
2252 multiplier = 0
2253 elif other > context.prec:
2254 multiplier = context.prec
2255 else:
2256 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002257
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002258 exp = self._exp * multiplier
2259 if exp < 1-context.prec:
2260 exp = 1-context.prec
2261 context._raise_error(Rounded)
2262 else:
2263 context._raise_error(Inexact)
2264 context._raise_error(Rounded)
2265 exp = 1-context.prec
2266
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002267 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002268
2269 # compute adjusted exponent of self
2270 self_adj = self.adjusted()
2271
2272 # self ** infinity is infinity if self > 1, 0 if self < 1
2273 # self ** -infinity is infinity if self < 1, 0 if self > 1
2274 if other._isinfinity():
2275 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002276 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002277 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002278 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002279
2280 # from here on, the result always goes through the call
2281 # to _fix at the end of this function.
2282 ans = None
2283
2284 # crude test to catch cases of extreme overflow/underflow. If
2285 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2286 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2287 # self**other >= 10**(Emax+1), so overflow occurs. The test
2288 # for underflow is similar.
2289 bound = self._log10_exp_bound() + other.adjusted()
2290 if (self_adj >= 0) == (other._sign == 0):
2291 # self > 1 and other +ve, or self < 1 and other -ve
2292 # possibility of overflow
2293 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002294 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002295 else:
2296 # self > 1 and other -ve, or self < 1 and other +ve
2297 # possibility of underflow to 0
2298 Etiny = context.Etiny()
2299 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002300 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002301
2302 # try for an exact result with precision +1
2303 if ans is None:
2304 ans = self._power_exact(other, context.prec + 1)
2305 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002306 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002307
2308 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2309 if ans is None:
2310 p = context.prec
2311 x = _WorkRep(self)
2312 xc, xe = x.int, x.exp
2313 y = _WorkRep(other)
2314 yc, ye = y.int, y.exp
2315 if y.sign == 1:
2316 yc = -yc
2317
2318 # compute correctly rounded result: start with precision +3,
2319 # then increase precision until result is unambiguously roundable
2320 extra = 3
2321 while True:
2322 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2323 if coeff % (5*10**(len(str(coeff))-p-1)):
2324 break
2325 extra += 3
2326
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002327 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002328
2329 # the specification says that for non-integer other we need to
2330 # raise Inexact, even when the result is actually exact. In
2331 # the same way, we need to raise Underflow here if the result
2332 # is subnormal. (The call to _fix will take care of raising
2333 # Rounded and Subnormal, as usual.)
2334 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002335 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002336 # pad with zeros up to length context.prec+1 if necessary
2337 if len(ans._int) <= context.prec:
2338 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002339 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2340 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002341 if ans.adjusted() < context.Emin:
2342 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002343
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002344 # unlike exp, ln and log10, the power function respects the
2345 # rounding mode; no need to use ROUND_HALF_EVEN here
2346 ans = ans._fix(context)
2347 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002348
2349 def __rpow__(self, other, context=None):
2350 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002351 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002352 if other is NotImplemented:
2353 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002354 return other.__pow__(self, context=context)
2355
2356 def normalize(self, context=None):
2357 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002358
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002359 if context is None:
2360 context = getcontext()
2361
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002362 if self._is_special:
2363 ans = self._check_nans(context=context)
2364 if ans:
2365 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002366
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002367 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002368 if dup._isinfinity():
2369 return dup
2370
2371 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002372 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002373 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002374 end = len(dup._int)
2375 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002376 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002377 exp += 1
2378 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002379 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002380
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002381 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002382 """Quantize self so its exponent is the same as that of exp.
2383
2384 Similar to self._rescale(exp._exp) but with error checking.
2385 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002386 exp = _convert_other(exp, raiseit=True)
2387
2388 if context is None:
2389 context = getcontext()
2390 if rounding is None:
2391 rounding = context.rounding
2392
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002393 if self._is_special or exp._is_special:
2394 ans = self._check_nans(exp, context)
2395 if ans:
2396 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002397
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002398 if exp._isinfinity() or self._isinfinity():
2399 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002400 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002401 return context._raise_error(InvalidOperation,
2402 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002403
2404 # if we're not watching exponents, do a simple rescale
2405 if not watchexp:
2406 ans = self._rescale(exp._exp, rounding)
2407 # raise Inexact and Rounded where appropriate
2408 if ans._exp > self._exp:
2409 context._raise_error(Rounded)
2410 if ans != self:
2411 context._raise_error(Inexact)
2412 return ans
2413
2414 # exp._exp should be between Etiny and Emax
2415 if not (context.Etiny() <= exp._exp <= context.Emax):
2416 return context._raise_error(InvalidOperation,
2417 'target exponent out of bounds in quantize')
2418
2419 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002420 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002421 return ans._fix(context)
2422
2423 self_adjusted = self.adjusted()
2424 if self_adjusted > context.Emax:
2425 return context._raise_error(InvalidOperation,
2426 'exponent of quantize result too large for current context')
2427 if self_adjusted - exp._exp + 1 > context.prec:
2428 return context._raise_error(InvalidOperation,
2429 'quantize result has too many digits for current context')
2430
2431 ans = self._rescale(exp._exp, rounding)
2432 if ans.adjusted() > context.Emax:
2433 return context._raise_error(InvalidOperation,
2434 'exponent of quantize result too large for current context')
2435 if len(ans._int) > context.prec:
2436 return context._raise_error(InvalidOperation,
2437 'quantize result has too many digits for current context')
2438
2439 # raise appropriate flags
2440 if ans._exp > self._exp:
2441 context._raise_error(Rounded)
2442 if ans != self:
2443 context._raise_error(Inexact)
2444 if ans and ans.adjusted() < context.Emin:
2445 context._raise_error(Subnormal)
2446
2447 # call to fix takes care of any necessary folddown
2448 ans = ans._fix(context)
2449 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002450
2451 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002452 """Return True if self and other have the same exponent; otherwise
2453 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002454
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002455 If either operand is a special value, the following rules are used:
2456 * return True if both operands are infinities
2457 * return True if both operands are NaNs
2458 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002459 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002460 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002461 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002462 return (self.is_nan() and other.is_nan() or
2463 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002464 return self._exp == other._exp
2465
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002466 def _rescale(self, exp, rounding):
2467 """Rescale self so that the exponent is exp, either by padding with zeros
2468 or by truncating digits, using the given rounding mode.
2469
2470 Specials are returned without change. This operation is
2471 quiet: it raises no flags, and uses no information from the
2472 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002473
2474 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002475 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002476 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002477 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002478 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002479 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002480 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002481
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002482 if self._exp >= exp:
2483 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002484 return _dec_from_triple(self._sign,
2485 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002486
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002487 # too many digits; round and lose data. If self.adjusted() <
2488 # exp-1, replace self by 10**(exp-1) before rounding
2489 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002490 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002491 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002492 digits = 0
2493 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002494 changed = this_function(digits)
2495 coeff = self._int[:digits] or '0'
2496 if changed == 1:
2497 coeff = str(int(coeff)+1)
2498 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002499
Christian Heimesf16baeb2008-02-29 14:57:44 +00002500 def _round(self, places, rounding):
2501 """Round a nonzero, nonspecial Decimal to a fixed number of
2502 significant figures, using the given rounding mode.
2503
2504 Infinities, NaNs and zeros are returned unaltered.
2505
2506 This operation is quiet: it raises no flags, and uses no
2507 information from the context.
2508
2509 """
2510 if places <= 0:
2511 raise ValueError("argument should be at least 1 in _round")
2512 if self._is_special or not self:
2513 return Decimal(self)
2514 ans = self._rescale(self.adjusted()+1-places, rounding)
2515 # it can happen that the rescale alters the adjusted exponent;
2516 # for example when rounding 99.97 to 3 significant figures.
2517 # When this happens we end up with an extra 0 at the end of
2518 # the number; a second rescale fixes this.
2519 if ans.adjusted() != self.adjusted():
2520 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2521 return ans
2522
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002523 def to_integral_exact(self, rounding=None, context=None):
2524 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002525
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002526 If no rounding mode is specified, take the rounding mode from
2527 the context. This method raises the Rounded and Inexact flags
2528 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002529
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002530 See also: to_integral_value, which does exactly the same as
2531 this method except that it doesn't raise Inexact or Rounded.
2532 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002533 if self._is_special:
2534 ans = self._check_nans(context=context)
2535 if ans:
2536 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002537 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002538 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002539 return Decimal(self)
2540 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002541 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002542 if context is None:
2543 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002544 if rounding is None:
2545 rounding = context.rounding
2546 context._raise_error(Rounded)
2547 ans = self._rescale(0, rounding)
2548 if ans != self:
2549 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002550 return ans
2551
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002552 def to_integral_value(self, rounding=None, context=None):
2553 """Rounds to the nearest integer, without raising inexact, rounded."""
2554 if context is None:
2555 context = getcontext()
2556 if rounding is None:
2557 rounding = context.rounding
2558 if self._is_special:
2559 ans = self._check_nans(context=context)
2560 if ans:
2561 return ans
2562 return Decimal(self)
2563 if self._exp >= 0:
2564 return Decimal(self)
2565 else:
2566 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002567
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002568 # the method name changed, but we provide also the old one, for compatibility
2569 to_integral = to_integral_value
2570
2571 def sqrt(self, context=None):
2572 """Return the square root of self."""
Christian Heimes0348fb62008-03-26 12:55:56 +00002573 if context is None:
2574 context = getcontext()
2575
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002576 if self._is_special:
2577 ans = self._check_nans(context=context)
2578 if ans:
2579 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002580
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002581 if self._isinfinity() and self._sign == 0:
2582 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002583
2584 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002585 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002586 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002587 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002588
2589 if self._sign == 1:
2590 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2591
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002592 # At this point self represents a positive number. Let p be
2593 # the desired precision and express self in the form c*100**e
2594 # with c a positive real number and e an integer, c and e
2595 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2596 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2597 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2598 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2599 # the closest integer to sqrt(c) with the even integer chosen
2600 # in the case of a tie.
2601 #
2602 # To ensure correct rounding in all cases, we use the
2603 # following trick: we compute the square root to an extra
2604 # place (precision p+1 instead of precision p), rounding down.
2605 # Then, if the result is inexact and its last digit is 0 or 5,
2606 # we increase the last digit to 1 or 6 respectively; if it's
2607 # exact we leave the last digit alone. Now the final round to
2608 # p places (or fewer in the case of underflow) will round
2609 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002610
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002611 # use an extra digit of precision
2612 prec = context.prec+1
2613
2614 # write argument in the form c*100**e where e = self._exp//2
2615 # is the 'ideal' exponent, to be used if the square root is
2616 # exactly representable. l is the number of 'digits' of c in
2617 # base 100, so that 100**(l-1) <= c < 100**l.
2618 op = _WorkRep(self)
2619 e = op.exp >> 1
2620 if op.exp & 1:
2621 c = op.int * 10
2622 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002623 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002624 c = op.int
2625 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002626
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002627 # rescale so that c has exactly prec base 100 'digits'
2628 shift = prec-l
2629 if shift >= 0:
2630 c *= 100**shift
2631 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002632 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002633 c, remainder = divmod(c, 100**-shift)
2634 exact = not remainder
2635 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002636
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002637 # find n = floor(sqrt(c)) using Newton's method
2638 n = 10**prec
2639 while True:
2640 q = c//n
2641 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002642 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002643 else:
2644 n = n + q >> 1
2645 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002646
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002647 if exact:
2648 # result is exact; rescale to use ideal exponent e
2649 if shift >= 0:
2650 # assert n % 10**shift == 0
2651 n //= 10**shift
2652 else:
2653 n *= 10**-shift
2654 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002655 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002656 # result is not exact; fix last digit as described above
2657 if n % 5 == 0:
2658 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002659
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002660 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002661
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002662 # round, and fit to current context
2663 context = context._shallow_copy()
2664 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002665 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002666 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002667
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002668 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002669
2670 def max(self, other, context=None):
2671 """Returns the larger value.
2672
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002673 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002674 NaN (and signals if one is sNaN). Also rounds.
2675 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002676 other = _convert_other(other, raiseit=True)
2677
2678 if context is None:
2679 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002680
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002681 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002682 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002683 # number is always returned
2684 sn = self._isnan()
2685 on = other._isnan()
2686 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002687 if on == 1 and sn == 0:
2688 return self._fix(context)
2689 if sn == 1 and on == 0:
2690 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002691 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002692
Christian Heimes77c02eb2008-02-09 02:18:51 +00002693 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002694 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002695 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002696 # then an ordering is applied:
2697 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002698 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002699 # positive sign and min returns the operand with the negative sign
2700 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002701 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002702 # the result. This is exactly the ordering used in compare_total.
2703 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002704
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002705 if c == -1:
2706 ans = other
2707 else:
2708 ans = self
2709
Christian Heimes2c181612007-12-17 20:04:13 +00002710 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002711
2712 def min(self, other, context=None):
2713 """Returns the smaller value.
2714
Guido van Rossumd8faa362007-04-27 19:54:29 +00002715 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002716 NaN (and signals if one is sNaN). Also rounds.
2717 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002718 other = _convert_other(other, raiseit=True)
2719
2720 if context is None:
2721 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002722
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002723 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002724 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002725 # number is always returned
2726 sn = self._isnan()
2727 on = other._isnan()
2728 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002729 if on == 1 and sn == 0:
2730 return self._fix(context)
2731 if sn == 1 and on == 0:
2732 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002733 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002734
Christian Heimes77c02eb2008-02-09 02:18:51 +00002735 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002736 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002737 c = self.compare_total(other)
2738
2739 if c == -1:
2740 ans = self
2741 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002742 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002743
Christian Heimes2c181612007-12-17 20:04:13 +00002744 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002745
2746 def _isinteger(self):
2747 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002748 if self._is_special:
2749 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002750 if self._exp >= 0:
2751 return True
2752 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002753 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002754
2755 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002756 """Returns True if self is even. Assumes self is an integer."""
2757 if not self or self._exp > 0:
2758 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002759 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002760
2761 def adjusted(self):
2762 """Return the adjusted exponent of self"""
2763 try:
2764 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002765 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002766 except TypeError:
2767 return 0
2768
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002769 def canonical(self, context=None):
2770 """Returns the same Decimal object.
2771
2772 As we do not have different encodings for the same number, the
2773 received object already is in its canonical form.
2774 """
2775 return self
2776
2777 def compare_signal(self, other, context=None):
2778 """Compares self to the other operand numerically.
2779
2780 It's pretty much like compare(), but all NaNs signal, with signaling
2781 NaNs taking precedence over quiet NaNs.
2782 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002783 other = _convert_other(other, raiseit = True)
2784 ans = self._compare_check_nans(other, context)
2785 if ans:
2786 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002787 return self.compare(other, context=context)
2788
2789 def compare_total(self, other):
2790 """Compares self to other using the abstract representations.
2791
2792 This is not like the standard compare, which use their numerical
2793 value. Note that a total ordering is defined for all possible abstract
2794 representations.
2795 """
2796 # if one is negative and the other is positive, it's easy
2797 if self._sign and not other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002798 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002799 if not self._sign and other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002800 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002801 sign = self._sign
2802
2803 # let's handle both NaN types
2804 self_nan = self._isnan()
2805 other_nan = other._isnan()
2806 if self_nan or other_nan:
2807 if self_nan == other_nan:
2808 if self._int < other._int:
2809 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002810 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002811 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002812 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002813 if self._int > other._int:
2814 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002815 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002816 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002817 return _One
2818 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002819
2820 if sign:
2821 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002822 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002823 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002824 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002825 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002826 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002827 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002828 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002829 else:
2830 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002831 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002832 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002833 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002834 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002835 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002836 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002837 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002838
2839 if self < other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002840 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002841 if self > other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002842 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002843
2844 if self._exp < other._exp:
2845 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002846 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002847 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002848 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002849 if self._exp > other._exp:
2850 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002851 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002852 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002853 return _One
2854 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002855
2856
2857 def compare_total_mag(self, other):
2858 """Compares self to other using abstract repr., ignoring sign.
2859
2860 Like compare_total, but with operand's sign ignored and assumed to be 0.
2861 """
2862 s = self.copy_abs()
2863 o = other.copy_abs()
2864 return s.compare_total(o)
2865
2866 def copy_abs(self):
2867 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002868 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002869
2870 def copy_negate(self):
2871 """Returns a copy with the sign inverted."""
2872 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002873 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002874 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002875 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002876
2877 def copy_sign(self, other):
2878 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002879 return _dec_from_triple(other._sign, self._int,
2880 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002881
2882 def exp(self, context=None):
2883 """Returns e ** self."""
2884
2885 if context is None:
2886 context = getcontext()
2887
2888 # exp(NaN) = NaN
2889 ans = self._check_nans(context=context)
2890 if ans:
2891 return ans
2892
2893 # exp(-Infinity) = 0
2894 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002895 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002896
2897 # exp(0) = 1
2898 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002899 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002900
2901 # exp(Infinity) = Infinity
2902 if self._isinfinity() == 1:
2903 return Decimal(self)
2904
2905 # the result is now guaranteed to be inexact (the true
2906 # mathematical result is transcendental). There's no need to
2907 # raise Rounded and Inexact here---they'll always be raised as
2908 # a result of the call to _fix.
2909 p = context.prec
2910 adj = self.adjusted()
2911
2912 # we only need to do any computation for quite a small range
2913 # of adjusted exponents---for example, -29 <= adj <= 10 for
2914 # the default context. For smaller exponent the result is
2915 # indistinguishable from 1 at the given precision, while for
2916 # larger exponent the result either overflows or underflows.
2917 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2918 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002919 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002920 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2921 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002922 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002923 elif self._sign == 0 and adj < -p:
2924 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002925 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002926 elif self._sign == 1 and adj < -p-1:
2927 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002928 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002929 # general case
2930 else:
2931 op = _WorkRep(self)
2932 c, e = op.int, op.exp
2933 if op.sign == 1:
2934 c = -c
2935
2936 # compute correctly rounded result: increase precision by
2937 # 3 digits at a time until we get an unambiguously
2938 # roundable result
2939 extra = 3
2940 while True:
2941 coeff, exp = _dexp(c, e, p+extra)
2942 if coeff % (5*10**(len(str(coeff))-p-1)):
2943 break
2944 extra += 3
2945
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002946 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002947
2948 # at this stage, ans should round correctly with *any*
2949 # rounding mode, not just with ROUND_HALF_EVEN
2950 context = context._shallow_copy()
2951 rounding = context._set_rounding(ROUND_HALF_EVEN)
2952 ans = ans._fix(context)
2953 context.rounding = rounding
2954
2955 return ans
2956
2957 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002958 """Return True if self is canonical; otherwise return False.
2959
2960 Currently, the encoding of a Decimal instance is always
2961 canonical, so this method returns True for any Decimal.
2962 """
2963 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002964
2965 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002966 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002967
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002968 A Decimal instance is considered finite if it is neither
2969 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002970 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002971 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002972
2973 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002974 """Return True if self is infinite; otherwise return False."""
2975 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002976
2977 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002978 """Return True if self is a qNaN or sNaN; otherwise return False."""
2979 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002980
2981 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002982 """Return True if self is a normal number; otherwise return False."""
2983 if self._is_special or not self:
2984 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002985 if context is None:
2986 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002987 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002988
2989 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002990 """Return True if self is a quiet NaN; otherwise return False."""
2991 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002992
2993 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002994 """Return True if self is negative; otherwise return False."""
2995 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002996
2997 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002998 """Return True if self is a signaling NaN; otherwise return False."""
2999 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003000
3001 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003002 """Return True if self is subnormal; otherwise return False."""
3003 if self._is_special or not self:
3004 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003005 if context is None:
3006 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003007 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003008
3009 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003010 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003011 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003012
3013 def _ln_exp_bound(self):
3014 """Compute a lower bound for the adjusted exponent of self.ln().
3015 In other words, compute r such that self.ln() >= 10**r. Assumes
3016 that self is finite and positive and that self != 1.
3017 """
3018
3019 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
3020 adj = self._exp + len(self._int) - 1
3021 if adj >= 1:
3022 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
3023 return len(str(adj*23//10)) - 1
3024 if adj <= -2:
3025 # argument <= 0.1
3026 return len(str((-1-adj)*23//10)) - 1
3027 op = _WorkRep(self)
3028 c, e = op.int, op.exp
3029 if adj == 0:
3030 # 1 < self < 10
3031 num = str(c-10**-e)
3032 den = str(c)
3033 return len(num) - len(den) - (num < den)
3034 # adj == -1, 0.1 <= self < 1
3035 return e + len(str(10**-e - c)) - 1
3036
3037
3038 def ln(self, context=None):
3039 """Returns the natural (base e) logarithm of self."""
3040
3041 if context is None:
3042 context = getcontext()
3043
3044 # ln(NaN) = NaN
3045 ans = self._check_nans(context=context)
3046 if ans:
3047 return ans
3048
3049 # ln(0.0) == -Infinity
3050 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003051 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003052
3053 # ln(Infinity) = Infinity
3054 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003055 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003056
3057 # ln(1.0) == 0.0
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003058 if self == _One:
3059 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003060
3061 # ln(negative) raises InvalidOperation
3062 if self._sign == 1:
3063 return context._raise_error(InvalidOperation,
3064 'ln of a negative value')
3065
3066 # result is irrational, so necessarily inexact
3067 op = _WorkRep(self)
3068 c, e = op.int, op.exp
3069 p = context.prec
3070
3071 # correctly rounded result: repeatedly increase precision by 3
3072 # until we get an unambiguously roundable result
3073 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3074 while True:
3075 coeff = _dlog(c, e, places)
3076 # assert len(str(abs(coeff)))-p >= 1
3077 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3078 break
3079 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003080 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003081
3082 context = context._shallow_copy()
3083 rounding = context._set_rounding(ROUND_HALF_EVEN)
3084 ans = ans._fix(context)
3085 context.rounding = rounding
3086 return ans
3087
3088 def _log10_exp_bound(self):
3089 """Compute a lower bound for the adjusted exponent of self.log10().
3090 In other words, find r such that self.log10() >= 10**r.
3091 Assumes that self is finite and positive and that self != 1.
3092 """
3093
3094 # For x >= 10 or x < 0.1 we only need a bound on the integer
3095 # part of log10(self), and this comes directly from the
3096 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3097 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3098 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3099
3100 adj = self._exp + len(self._int) - 1
3101 if adj >= 1:
3102 # self >= 10
3103 return len(str(adj))-1
3104 if adj <= -2:
3105 # self < 0.1
3106 return len(str(-1-adj))-1
3107 op = _WorkRep(self)
3108 c, e = op.int, op.exp
3109 if adj == 0:
3110 # 1 < self < 10
3111 num = str(c-10**-e)
3112 den = str(231*c)
3113 return len(num) - len(den) - (num < den) + 2
3114 # adj == -1, 0.1 <= self < 1
3115 num = str(10**-e-c)
3116 return len(num) + e - (num < "231") - 1
3117
3118 def log10(self, context=None):
3119 """Returns the base 10 logarithm of self."""
3120
3121 if context is None:
3122 context = getcontext()
3123
3124 # log10(NaN) = NaN
3125 ans = self._check_nans(context=context)
3126 if ans:
3127 return ans
3128
3129 # log10(0.0) == -Infinity
3130 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003131 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003132
3133 # log10(Infinity) = Infinity
3134 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003135 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003136
3137 # log10(negative or -Infinity) raises InvalidOperation
3138 if self._sign == 1:
3139 return context._raise_error(InvalidOperation,
3140 'log10 of a negative value')
3141
3142 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003143 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003144 # answer may need rounding
3145 ans = Decimal(self._exp + len(self._int) - 1)
3146 else:
3147 # result is irrational, so necessarily inexact
3148 op = _WorkRep(self)
3149 c, e = op.int, op.exp
3150 p = context.prec
3151
3152 # correctly rounded result: repeatedly increase precision
3153 # until result is unambiguously roundable
3154 places = p-self._log10_exp_bound()+2
3155 while True:
3156 coeff = _dlog10(c, e, places)
3157 # assert len(str(abs(coeff)))-p >= 1
3158 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3159 break
3160 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003161 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003162
3163 context = context._shallow_copy()
3164 rounding = context._set_rounding(ROUND_HALF_EVEN)
3165 ans = ans._fix(context)
3166 context.rounding = rounding
3167 return ans
3168
3169 def logb(self, context=None):
3170 """ Returns the exponent of the magnitude of self's MSD.
3171
3172 The result is the integer which is the exponent of the magnitude
3173 of the most significant digit of self (as though it were truncated
3174 to a single digit while maintaining the value of that digit and
3175 without limiting the resulting exponent).
3176 """
3177 # logb(NaN) = NaN
3178 ans = self._check_nans(context=context)
3179 if ans:
3180 return ans
3181
3182 if context is None:
3183 context = getcontext()
3184
3185 # logb(+/-Inf) = +Inf
3186 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003187 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003188
3189 # logb(0) = -Inf, DivisionByZero
3190 if not self:
3191 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3192
3193 # otherwise, simply return the adjusted exponent of self, as a
3194 # Decimal. Note that no attempt is made to fit the result
3195 # into the current context.
3196 return Decimal(self.adjusted())
3197
3198 def _islogical(self):
3199 """Return True if self is a logical operand.
3200
Christian Heimes679db4a2008-01-18 09:56:22 +00003201 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003202 an exponent of 0, and a coefficient whose digits must all be
3203 either 0 or 1.
3204 """
3205 if self._sign != 0 or self._exp != 0:
3206 return False
3207 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003208 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003209 return False
3210 return True
3211
3212 def _fill_logical(self, context, opa, opb):
3213 dif = context.prec - len(opa)
3214 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003215 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003216 elif dif < 0:
3217 opa = opa[-context.prec:]
3218 dif = context.prec - len(opb)
3219 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003220 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003221 elif dif < 0:
3222 opb = opb[-context.prec:]
3223 return opa, opb
3224
3225 def logical_and(self, other, context=None):
3226 """Applies an 'and' operation between self and other's digits."""
3227 if context is None:
3228 context = getcontext()
3229 if not self._islogical() or not other._islogical():
3230 return context._raise_error(InvalidOperation)
3231
3232 # fill to context.prec
3233 (opa, opb) = self._fill_logical(context, self._int, other._int)
3234
3235 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003236 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3237 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003238
3239 def logical_invert(self, context=None):
3240 """Invert all its digits."""
3241 if context is None:
3242 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003243 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3244 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003245
3246 def logical_or(self, other, context=None):
3247 """Applies an 'or' operation between self and other's digits."""
3248 if context is None:
3249 context = getcontext()
3250 if not self._islogical() or not other._islogical():
3251 return context._raise_error(InvalidOperation)
3252
3253 # fill to context.prec
3254 (opa, opb) = self._fill_logical(context, self._int, other._int)
3255
3256 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003257 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3258 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003259
3260 def logical_xor(self, other, context=None):
3261 """Applies an 'xor' operation between self and other's digits."""
3262 if context is None:
3263 context = getcontext()
3264 if not self._islogical() or not other._islogical():
3265 return context._raise_error(InvalidOperation)
3266
3267 # fill to context.prec
3268 (opa, opb) = self._fill_logical(context, self._int, other._int)
3269
3270 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003271 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3272 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003273
3274 def max_mag(self, other, context=None):
3275 """Compares the values numerically with their sign ignored."""
3276 other = _convert_other(other, raiseit=True)
3277
3278 if context is None:
3279 context = getcontext()
3280
3281 if self._is_special or other._is_special:
3282 # If one operand is a quiet NaN and the other is number, then the
3283 # number is always returned
3284 sn = self._isnan()
3285 on = other._isnan()
3286 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003287 if on == 1 and sn == 0:
3288 return self._fix(context)
3289 if sn == 1 and on == 0:
3290 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003291 return self._check_nans(other, context)
3292
Christian Heimes77c02eb2008-02-09 02:18:51 +00003293 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003294 if c == 0:
3295 c = self.compare_total(other)
3296
3297 if c == -1:
3298 ans = other
3299 else:
3300 ans = self
3301
Christian Heimes2c181612007-12-17 20:04:13 +00003302 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003303
3304 def min_mag(self, other, context=None):
3305 """Compares the values numerically with their sign ignored."""
3306 other = _convert_other(other, raiseit=True)
3307
3308 if context is None:
3309 context = getcontext()
3310
3311 if self._is_special or other._is_special:
3312 # If one operand is a quiet NaN and the other is number, then the
3313 # number is always returned
3314 sn = self._isnan()
3315 on = other._isnan()
3316 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003317 if on == 1 and sn == 0:
3318 return self._fix(context)
3319 if sn == 1 and on == 0:
3320 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003321 return self._check_nans(other, context)
3322
Christian Heimes77c02eb2008-02-09 02:18:51 +00003323 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003324 if c == 0:
3325 c = self.compare_total(other)
3326
3327 if c == -1:
3328 ans = self
3329 else:
3330 ans = other
3331
Christian Heimes2c181612007-12-17 20:04:13 +00003332 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003333
3334 def next_minus(self, context=None):
3335 """Returns the largest representable number smaller than itself."""
3336 if context is None:
3337 context = getcontext()
3338
3339 ans = self._check_nans(context=context)
3340 if ans:
3341 return ans
3342
3343 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003344 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003345 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003346 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003347
3348 context = context.copy()
3349 context._set_rounding(ROUND_FLOOR)
3350 context._ignore_all_flags()
3351 new_self = self._fix(context)
3352 if new_self != self:
3353 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003354 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3355 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003356
3357 def next_plus(self, context=None):
3358 """Returns the smallest representable number larger than itself."""
3359 if context is None:
3360 context = getcontext()
3361
3362 ans = self._check_nans(context=context)
3363 if ans:
3364 return ans
3365
3366 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003367 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003368 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003369 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003370
3371 context = context.copy()
3372 context._set_rounding(ROUND_CEILING)
3373 context._ignore_all_flags()
3374 new_self = self._fix(context)
3375 if new_self != self:
3376 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003377 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3378 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003379
3380 def next_toward(self, other, context=None):
3381 """Returns the number closest to self, in the direction towards other.
3382
3383 The result is the closest representable number to self
3384 (excluding self) that is in the direction towards other,
3385 unless both have the same value. If the two operands are
3386 numerically equal, then the result is a copy of self with the
3387 sign set to be the same as the sign of other.
3388 """
3389 other = _convert_other(other, raiseit=True)
3390
3391 if context is None:
3392 context = getcontext()
3393
3394 ans = self._check_nans(other, context)
3395 if ans:
3396 return ans
3397
Christian Heimes77c02eb2008-02-09 02:18:51 +00003398 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003399 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003400 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003401
3402 if comparison == -1:
3403 ans = self.next_plus(context)
3404 else: # comparison == 1
3405 ans = self.next_minus(context)
3406
3407 # decide which flags to raise using value of ans
3408 if ans._isinfinity():
3409 context._raise_error(Overflow,
3410 'Infinite result from next_toward',
3411 ans._sign)
3412 context._raise_error(Rounded)
3413 context._raise_error(Inexact)
3414 elif ans.adjusted() < context.Emin:
3415 context._raise_error(Underflow)
3416 context._raise_error(Subnormal)
3417 context._raise_error(Rounded)
3418 context._raise_error(Inexact)
3419 # if precision == 1 then we don't raise Clamped for a
3420 # result 0E-Etiny.
3421 if not ans:
3422 context._raise_error(Clamped)
3423
3424 return ans
3425
3426 def number_class(self, context=None):
3427 """Returns an indication of the class of self.
3428
3429 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003430 sNaN
3431 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003432 -Infinity
3433 -Normal
3434 -Subnormal
3435 -Zero
3436 +Zero
3437 +Subnormal
3438 +Normal
3439 +Infinity
3440 """
3441 if self.is_snan():
3442 return "sNaN"
3443 if self.is_qnan():
3444 return "NaN"
3445 inf = self._isinfinity()
3446 if inf == 1:
3447 return "+Infinity"
3448 if inf == -1:
3449 return "-Infinity"
3450 if self.is_zero():
3451 if self._sign:
3452 return "-Zero"
3453 else:
3454 return "+Zero"
3455 if context is None:
3456 context = getcontext()
3457 if self.is_subnormal(context=context):
3458 if self._sign:
3459 return "-Subnormal"
3460 else:
3461 return "+Subnormal"
3462 # just a normal, regular, boring number, :)
3463 if self._sign:
3464 return "-Normal"
3465 else:
3466 return "+Normal"
3467
3468 def radix(self):
3469 """Just returns 10, as this is Decimal, :)"""
3470 return Decimal(10)
3471
3472 def rotate(self, other, context=None):
3473 """Returns a rotated copy of self, value-of-other times."""
3474 if context is None:
3475 context = getcontext()
3476
3477 ans = self._check_nans(other, context)
3478 if ans:
3479 return ans
3480
3481 if other._exp != 0:
3482 return context._raise_error(InvalidOperation)
3483 if not (-context.prec <= int(other) <= context.prec):
3484 return context._raise_error(InvalidOperation)
3485
3486 if self._isinfinity():
3487 return Decimal(self)
3488
3489 # get values, pad if necessary
3490 torot = int(other)
3491 rotdig = self._int
3492 topad = context.prec - len(rotdig)
3493 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003494 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003495
3496 # let's rotate!
3497 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003498 return _dec_from_triple(self._sign,
3499 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003500
3501 def scaleb (self, other, context=None):
3502 """Returns self operand after adding the second value to its exp."""
3503 if context is None:
3504 context = getcontext()
3505
3506 ans = self._check_nans(other, context)
3507 if ans:
3508 return ans
3509
3510 if other._exp != 0:
3511 return context._raise_error(InvalidOperation)
3512 liminf = -2 * (context.Emax + context.prec)
3513 limsup = 2 * (context.Emax + context.prec)
3514 if not (liminf <= int(other) <= limsup):
3515 return context._raise_error(InvalidOperation)
3516
3517 if self._isinfinity():
3518 return Decimal(self)
3519
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003520 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003521 d = d._fix(context)
3522 return d
3523
3524 def shift(self, other, context=None):
3525 """Returns a shifted copy of self, value-of-other times."""
3526 if context is None:
3527 context = getcontext()
3528
3529 ans = self._check_nans(other, context)
3530 if ans:
3531 return ans
3532
3533 if other._exp != 0:
3534 return context._raise_error(InvalidOperation)
3535 if not (-context.prec <= int(other) <= context.prec):
3536 return context._raise_error(InvalidOperation)
3537
3538 if self._isinfinity():
3539 return Decimal(self)
3540
3541 # get values, pad if necessary
3542 torot = int(other)
3543 if not torot:
3544 return Decimal(self)
3545 rotdig = self._int
3546 topad = context.prec - len(rotdig)
3547 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003548 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003549
3550 # let's shift!
3551 if torot < 0:
3552 rotated = rotdig[:torot]
3553 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003554 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003555 rotated = rotated[-context.prec:]
3556
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003557 return _dec_from_triple(self._sign,
3558 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003559
Guido van Rossumd8faa362007-04-27 19:54:29 +00003560 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003561 def __reduce__(self):
3562 return (self.__class__, (str(self),))
3563
3564 def __copy__(self):
3565 if type(self) == Decimal:
3566 return self # I'm immutable; therefore I am my own clone
3567 return self.__class__(str(self))
3568
3569 def __deepcopy__(self, memo):
3570 if type(self) == Decimal:
3571 return self # My components are also immutable
3572 return self.__class__(str(self))
3573
Christian Heimesf16baeb2008-02-29 14:57:44 +00003574 # PEP 3101 support. See also _parse_format_specifier and _format_align
3575 def __format__(self, specifier, context=None):
3576 """Format a Decimal instance according to the given specifier.
3577
3578 The specifier should be a standard format specifier, with the
3579 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3580 'F', 'g', 'G', and '%' are supported. If the formatting type
3581 is omitted it defaults to 'g' or 'G', depending on the value
3582 of context.capitals.
3583
3584 At this time the 'n' format specifier type (which is supposed
3585 to use the current locale) is not supported.
3586 """
3587
3588 # Note: PEP 3101 says that if the type is not present then
3589 # there should be at least one digit after the decimal point.
3590 # We take the liberty of ignoring this requirement for
3591 # Decimal---it's presumably there to make sure that
3592 # format(float, '') behaves similarly to str(float).
3593 if context is None:
3594 context = getcontext()
3595
3596 spec = _parse_format_specifier(specifier)
3597
3598 # special values don't care about the type or precision...
3599 if self._is_special:
3600 return _format_align(str(self), spec)
3601
3602 # a type of None defaults to 'g' or 'G', depending on context
3603 # if type is '%', adjust exponent of self accordingly
3604 if spec['type'] is None:
3605 spec['type'] = ['g', 'G'][context.capitals]
3606 elif spec['type'] == '%':
3607 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3608
3609 # round if necessary, taking rounding mode from the context
3610 rounding = context.rounding
3611 precision = spec['precision']
3612 if precision is not None:
3613 if spec['type'] in 'eE':
3614 self = self._round(precision+1, rounding)
3615 elif spec['type'] in 'gG':
3616 if len(self._int) > precision:
3617 self = self._round(precision, rounding)
3618 elif spec['type'] in 'fF%':
3619 self = self._rescale(-precision, rounding)
3620 # special case: zeros with a positive exponent can't be
3621 # represented in fixed point; rescale them to 0e0.
3622 elif not self and self._exp > 0 and spec['type'] in 'fF%':
3623 self = self._rescale(0, rounding)
3624
3625 # figure out placement of the decimal point
3626 leftdigits = self._exp + len(self._int)
3627 if spec['type'] in 'fF%':
3628 dotplace = leftdigits
3629 elif spec['type'] in 'eE':
3630 if not self and precision is not None:
3631 dotplace = 1 - precision
3632 else:
3633 dotplace = 1
3634 elif spec['type'] in 'gG':
3635 if self._exp <= 0 and leftdigits > -6:
3636 dotplace = leftdigits
3637 else:
3638 dotplace = 1
3639
3640 # figure out main part of numeric string...
3641 if dotplace <= 0:
3642 num = '0.' + '0'*(-dotplace) + self._int
3643 elif dotplace >= len(self._int):
3644 # make sure we're not padding a '0' with extra zeros on the right
3645 assert dotplace==len(self._int) or self._int != '0'
3646 num = self._int + '0'*(dotplace-len(self._int))
3647 else:
3648 num = self._int[:dotplace] + '.' + self._int[dotplace:]
3649
3650 # ...then the trailing exponent, or trailing '%'
3651 if leftdigits != dotplace or spec['type'] in 'eE':
3652 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3653 num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3654 elif spec['type'] == '%':
3655 num = num + '%'
3656
3657 # add sign
3658 if self._sign == 1:
3659 num = '-' + num
3660 return _format_align(num, spec)
3661
3662
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003663def _dec_from_triple(sign, coefficient, exponent, special=False):
3664 """Create a decimal instance directly, without any validation,
3665 normalization (e.g. removal of leading zeros) or argument
3666 conversion.
3667
3668 This function is for *internal use only*.
3669 """
3670
3671 self = object.__new__(Decimal)
3672 self._sign = sign
3673 self._int = coefficient
3674 self._exp = exponent
3675 self._is_special = special
3676
3677 return self
3678
Guido van Rossumd8faa362007-04-27 19:54:29 +00003679##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003680
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003681
3682# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003683rounding_functions = [name for name in Decimal.__dict__.keys()
3684 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003685for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003686 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003687 globalname = name[1:].upper()
3688 val = globals()[globalname]
3689 Decimal._pick_rounding_function[val] = name
3690
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003691del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003692
Thomas Wouters89f507f2006-12-13 04:49:30 +00003693class _ContextManager(object):
3694 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003695
Thomas Wouters89f507f2006-12-13 04:49:30 +00003696 Sets a copy of the supplied context in __enter__() and restores
3697 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003698 """
3699 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003700 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003701 def __enter__(self):
3702 self.saved_context = getcontext()
3703 setcontext(self.new_context)
3704 return self.new_context
3705 def __exit__(self, t, v, tb):
3706 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003707
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003708class Context(object):
3709 """Contains the context for a Decimal instance.
3710
3711 Contains:
3712 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003713 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003714 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003715 raised when it is caused. Otherwise, a value is
3716 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003717 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003718 (Whether or not the trap_enabler is set)
3719 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003720 Emin - Minimum exponent
3721 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003722 capitals - If 1, 1*10^1 is printed as 1E+1.
3723 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003724 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003725 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003726
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003727 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003728 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003729 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003730 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003731 _ignored_flags=None):
3732 if flags is None:
3733 flags = []
3734 if _ignored_flags is None:
3735 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003736 if not isinstance(flags, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003737 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003738 if traps is not None and not isinstance(traps, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003739 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003740 for name, val in locals().items():
3741 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003742 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003743 else:
3744 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003745 del self.self
3746
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003747 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003748 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003749 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003750 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3751 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3752 % vars(self))
3753 names = [f.__name__ for f, v in self.flags.items() if v]
3754 s.append('flags=[' + ', '.join(names) + ']')
3755 names = [t.__name__ for t, v in self.traps.items() if v]
3756 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003757 return ', '.join(s) + ')'
3758
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003759 def clear_flags(self):
3760 """Reset all flags to zero"""
3761 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003762 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003763
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003764 def _shallow_copy(self):
3765 """Returns a shallow copy from self."""
Christian Heimes2c181612007-12-17 20:04:13 +00003766 nc = Context(self.prec, self.rounding, self.traps,
3767 self.flags, self.Emin, self.Emax,
3768 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003769 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003770
3771 def copy(self):
3772 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003773 nc = Context(self.prec, self.rounding, self.traps.copy(),
Christian Heimes2c181612007-12-17 20:04:13 +00003774 self.flags.copy(), self.Emin, self.Emax,
3775 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003776 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003777 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003778
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003779 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003780 """Handles an error
3781
3782 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003783 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003784 trap_enabler is set, it reaises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00003785 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003786 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003787 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003788 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003789 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003790 return error().handle(self, *args)
3791
Raymond Hettinger86173da2008-02-01 20:38:12 +00003792 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003793 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003794 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003795 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003796
3797 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003798 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003799 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003800
3801 def _ignore_all_flags(self):
3802 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003803 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003804
3805 def _ignore_flags(self, *flags):
3806 """Ignore the flags, if they are raised"""
3807 # Do not mutate-- This way, copies of a context leave the original
3808 # alone.
3809 self._ignored_flags = (self._ignored_flags + list(flags))
3810 return list(flags)
3811
3812 def _regard_flags(self, *flags):
3813 """Stop ignoring the flags, if they are raised"""
3814 if flags and isinstance(flags[0], (tuple,list)):
3815 flags = flags[0]
3816 for flag in flags:
3817 self._ignored_flags.remove(flag)
3818
Nick Coghland1abd252008-07-15 15:46:38 +00003819 # We inherit object.__hash__, so we must deny this explicitly
3820 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003821
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003822 def Etiny(self):
3823 """Returns Etiny (= Emin - prec + 1)"""
3824 return int(self.Emin - self.prec + 1)
3825
3826 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003827 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003828 return int(self.Emax - self.prec + 1)
3829
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003830 def _set_rounding(self, type):
3831 """Sets the rounding type.
3832
3833 Sets the rounding type, and returns the current (previous)
3834 rounding type. Often used like:
3835
3836 context = context.copy()
3837 # so you don't change the calling context
3838 # if an error occurs in the middle.
3839 rounding = context._set_rounding(ROUND_UP)
3840 val = self.__sub__(other, context=context)
3841 context._set_rounding(rounding)
3842
3843 This will make it round up for that operation.
3844 """
3845 rounding = self.rounding
3846 self.rounding= type
3847 return rounding
3848
Raymond Hettingerfed52962004-07-14 15:41:57 +00003849 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00003850 """Creates a new Decimal instance but using self as context.
3851
3852 This method implements the to-number operation of the
3853 IBM Decimal specification."""
3854
3855 if isinstance(num, str) and num != num.strip():
3856 return self._raise_error(ConversionSyntax,
3857 "no trailing or leading whitespace is "
3858 "permitted.")
3859
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003860 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003861 if d._isnan() and len(d._int) > self.prec - self._clamp:
3862 return self._raise_error(ConversionSyntax,
3863 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003864 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003865
Raymond Hettinger771ed762009-01-03 19:20:32 +00003866 def create_decimal_from_float(self, f):
3867 """Creates a new Decimal instance from a float but rounding using self
3868 as the context.
3869
3870 >>> context = Context(prec=5, rounding=ROUND_DOWN)
3871 >>> context.create_decimal_from_float(3.1415926535897932)
3872 Decimal('3.1415')
3873 >>> context = Context(prec=5, traps=[Inexact])
3874 >>> context.create_decimal_from_float(3.1415926535897932)
3875 Traceback (most recent call last):
3876 ...
3877 decimal.Inexact: None
3878
3879 """
3880 d = Decimal.from_float(f) # An exact conversion
3881 return d._fix(self) # Apply the context rounding
3882
Guido van Rossumd8faa362007-04-27 19:54:29 +00003883 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003884 def abs(self, a):
3885 """Returns the absolute value of the operand.
3886
3887 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003888 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003889 the plus operation on the operand.
3890
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003891 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003892 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003893 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003894 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003895 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003896 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003897 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003898 Decimal('101.5')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003899 """
3900 return a.__abs__(context=self)
3901
3902 def add(self, a, b):
3903 """Return the sum of the two operands.
3904
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003905 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003906 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003907 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003908 Decimal('1.02E+4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003909 """
3910 return a.__add__(b, context=self)
3911
3912 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003913 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003914
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003915 def canonical(self, a):
3916 """Returns the same Decimal object.
3917
3918 As we do not have different encodings for the same number, the
3919 received object already is in its canonical form.
3920
3921 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003922 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003923 """
3924 return a.canonical(context=self)
3925
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003926 def compare(self, a, b):
3927 """Compares values numerically.
3928
3929 If the signs of the operands differ, a value representing each operand
3930 ('-1' if the operand is less than zero, '0' if the operand is zero or
3931 negative zero, or '1' if the operand is greater than zero) is used in
3932 place of that operand for the comparison instead of the actual
3933 operand.
3934
3935 The comparison is then effected by subtracting the second operand from
3936 the first and then returning a value according to the result of the
3937 subtraction: '-1' if the result is less than zero, '0' if the result is
3938 zero or negative zero, or '1' if the result is greater than zero.
3939
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003940 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003941 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003942 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003943 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003944 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003945 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003946 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003947 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003948 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003949 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003950 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003951 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003952 """
3953 return a.compare(b, context=self)
3954
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003955 def compare_signal(self, a, b):
3956 """Compares the values of the two operands numerically.
3957
3958 It's pretty much like compare(), but all NaNs signal, with signaling
3959 NaNs taking precedence over quiet NaNs.
3960
3961 >>> c = ExtendedContext
3962 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003963 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003964 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003965 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003966 >>> c.flags[InvalidOperation] = 0
3967 >>> print(c.flags[InvalidOperation])
3968 0
3969 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003970 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003971 >>> print(c.flags[InvalidOperation])
3972 1
3973 >>> c.flags[InvalidOperation] = 0
3974 >>> print(c.flags[InvalidOperation])
3975 0
3976 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003977 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003978 >>> print(c.flags[InvalidOperation])
3979 1
3980 """
3981 return a.compare_signal(b, context=self)
3982
3983 def compare_total(self, a, b):
3984 """Compares two operands using their abstract representation.
3985
3986 This is not like the standard compare, which use their numerical
3987 value. Note that a total ordering is defined for all possible abstract
3988 representations.
3989
3990 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003991 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003992 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003993 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003994 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003995 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003996 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003997 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003998 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003999 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004000 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004001 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004002 """
4003 return a.compare_total(b)
4004
4005 def compare_total_mag(self, a, b):
4006 """Compares two operands using their abstract representation ignoring sign.
4007
4008 Like compare_total, but with operand's sign ignored and assumed to be 0.
4009 """
4010 return a.compare_total_mag(b)
4011
4012 def copy_abs(self, a):
4013 """Returns a copy of the operand with the sign set to 0.
4014
4015 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004016 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004017 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004018 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004019 """
4020 return a.copy_abs()
4021
4022 def copy_decimal(self, a):
4023 """Returns a copy of the decimal objet.
4024
4025 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004026 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004027 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004028 Decimal('-1.00')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004029 """
4030 return Decimal(a)
4031
4032 def copy_negate(self, a):
4033 """Returns a copy of the operand with the sign inverted.
4034
4035 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004036 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004037 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004038 Decimal('101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004039 """
4040 return a.copy_negate()
4041
4042 def copy_sign(self, a, b):
4043 """Copies the second operand's sign to the first one.
4044
4045 In detail, it returns a copy of the first operand with the sign
4046 equal to the sign of the second operand.
4047
4048 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004049 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004050 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004051 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004052 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004053 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004054 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004055 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004056 """
4057 return a.copy_sign(b)
4058
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004059 def divide(self, a, b):
4060 """Decimal division in a specified context.
4061
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004062 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004063 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004064 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004065 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004066 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004067 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004068 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004069 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004070 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004071 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004072 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004073 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004074 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004075 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004076 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004077 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004078 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004079 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004080 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004081 Decimal('1.20E+6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004082 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00004083 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004084
4085 def divide_int(self, a, b):
4086 """Divides two numbers and returns the integer part of the result.
4087
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004088 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004089 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004090 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004091 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004092 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004093 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004094 """
4095 return a.__floordiv__(b, context=self)
4096
4097 def divmod(self, a, b):
4098 return a.__divmod__(b, context=self)
4099
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004100 def exp(self, a):
4101 """Returns e ** a.
4102
4103 >>> c = ExtendedContext.copy()
4104 >>> c.Emin = -999
4105 >>> c.Emax = 999
4106 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004107 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004108 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004109 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004110 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004111 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004112 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004113 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004114 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004115 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004116 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004117 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004118 """
4119 return a.exp(context=self)
4120
4121 def fma(self, a, b, c):
4122 """Returns a multiplied by b, plus c.
4123
4124 The first two operands are multiplied together, using multiply,
4125 the third operand is then added to the result of that
4126 multiplication, using add, all with only one final rounding.
4127
4128 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004129 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004130 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004131 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004132 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004133 Decimal('1.38435736E+12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004134 """
4135 return a.fma(b, c, context=self)
4136
4137 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004138 """Return True if the operand is canonical; otherwise return False.
4139
4140 Currently, the encoding of a Decimal instance is always
4141 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004142
4143 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004144 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004145 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004146 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004147
4148 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004149 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004150
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004151 A Decimal instance is considered finite if it is neither
4152 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004153
4154 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004155 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004156 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004157 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004158 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004159 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004160 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004161 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004162 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004163 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004164 """
4165 return a.is_finite()
4166
4167 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004168 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004169
4170 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004171 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004172 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004173 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004174 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004175 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004176 """
4177 return a.is_infinite()
4178
4179 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004180 """Return True if the operand is a qNaN or sNaN;
4181 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004182
4183 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004184 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004185 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004186 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004187 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004188 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004189 """
4190 return a.is_nan()
4191
4192 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004193 """Return True if the operand is a normal number;
4194 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004195
4196 >>> c = ExtendedContext.copy()
4197 >>> c.Emin = -999
4198 >>> c.Emax = 999
4199 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004200 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004201 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004202 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004203 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004204 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004205 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004206 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004207 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004208 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004209 """
4210 return a.is_normal(context=self)
4211
4212 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004213 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004214
4215 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004216 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004217 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004218 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004219 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004220 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004221 """
4222 return a.is_qnan()
4223
4224 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004225 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004226
4227 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004228 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004229 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004230 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004231 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004232 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004233 """
4234 return a.is_signed()
4235
4236 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004237 """Return True if the operand is a signaling NaN;
4238 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004239
4240 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004241 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004242 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004243 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004244 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004245 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004246 """
4247 return a.is_snan()
4248
4249 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004250 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004251
4252 >>> c = ExtendedContext.copy()
4253 >>> c.Emin = -999
4254 >>> c.Emax = 999
4255 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004256 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004257 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004258 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004259 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004260 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004261 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004262 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004263 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004264 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004265 """
4266 return a.is_subnormal(context=self)
4267
4268 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004269 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004270
4271 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004272 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004273 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004274 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004275 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004276 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004277 """
4278 return a.is_zero()
4279
4280 def ln(self, a):
4281 """Returns the natural (base e) logarithm of the operand.
4282
4283 >>> c = ExtendedContext.copy()
4284 >>> c.Emin = -999
4285 >>> c.Emax = 999
4286 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004287 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004288 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004289 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004290 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004291 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004292 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004293 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004294 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004295 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004296 """
4297 return a.ln(context=self)
4298
4299 def log10(self, a):
4300 """Returns the base 10 logarithm of the operand.
4301
4302 >>> c = ExtendedContext.copy()
4303 >>> c.Emin = -999
4304 >>> c.Emax = 999
4305 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004306 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004307 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004308 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004309 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004310 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004311 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004312 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004313 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004314 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004315 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004316 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004317 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004318 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004319 """
4320 return a.log10(context=self)
4321
4322 def logb(self, a):
4323 """ Returns the exponent of the magnitude of the operand's MSD.
4324
4325 The result is the integer which is the exponent of the magnitude
4326 of the most significant digit of the operand (as though the
4327 operand were truncated to a single digit while maintaining the
4328 value of that digit and without limiting the resulting exponent).
4329
4330 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004331 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004332 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004333 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004334 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004335 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004336 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004337 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004338 """
4339 return a.logb(context=self)
4340
4341 def logical_and(self, a, b):
4342 """Applies the logical operation 'and' between each operand's digits.
4343
4344 The operands must be both logical numbers.
4345
4346 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004347 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004348 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004349 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004350 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004351 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004352 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004353 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004354 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004355 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004356 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004357 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004358 """
4359 return a.logical_and(b, context=self)
4360
4361 def logical_invert(self, a):
4362 """Invert all the digits in the operand.
4363
4364 The operand must be a logical number.
4365
4366 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004367 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004368 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004369 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004370 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004371 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004372 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004373 Decimal('10101010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004374 """
4375 return a.logical_invert(context=self)
4376
4377 def logical_or(self, a, b):
4378 """Applies the logical operation 'or' between each operand's digits.
4379
4380 The operands must be both logical numbers.
4381
4382 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004383 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004384 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004385 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004386 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004387 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004388 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004389 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004390 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004391 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004392 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004393 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004394 """
4395 return a.logical_or(b, context=self)
4396
4397 def logical_xor(self, a, b):
4398 """Applies the logical operation 'xor' between each operand's digits.
4399
4400 The operands must be both logical numbers.
4401
4402 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004403 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004404 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004405 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004406 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004407 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004408 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004409 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004410 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004411 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004412 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004413 Decimal('1101')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004414 """
4415 return a.logical_xor(b, context=self)
4416
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004417 def max(self, a,b):
4418 """max compares two values numerically and returns the maximum.
4419
4420 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004421 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004422 operation. If they are numerically equal then the left-hand operand
4423 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004424 infinity) of the two operands is chosen as the result.
4425
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004426 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004427 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004428 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004429 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004430 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004431 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004432 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004433 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004434 """
4435 return a.max(b, context=self)
4436
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004437 def max_mag(self, a, b):
4438 """Compares the values numerically with their sign ignored."""
4439 return a.max_mag(b, context=self)
4440
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004441 def min(self, a,b):
4442 """min compares two values numerically and returns the minimum.
4443
4444 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004445 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004446 operation. If they are numerically equal then the left-hand operand
4447 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004448 infinity) of the two operands is chosen as the result.
4449
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004450 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004451 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004452 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004453 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004454 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004455 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004456 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004457 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004458 """
4459 return a.min(b, context=self)
4460
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004461 def min_mag(self, a, b):
4462 """Compares the values numerically with their sign ignored."""
4463 return a.min_mag(b, context=self)
4464
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004465 def minus(self, a):
4466 """Minus corresponds to unary prefix minus in Python.
4467
4468 The operation is evaluated using the same rules as subtract; the
4469 operation minus(a) is calculated as subtract('0', a) where the '0'
4470 has the same exponent as the operand.
4471
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004472 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004473 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004474 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004475 Decimal('1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004476 """
4477 return a.__neg__(context=self)
4478
4479 def multiply(self, a, b):
4480 """multiply multiplies two operands.
4481
4482 If either operand is a special value then the general rules apply.
4483 Otherwise, the operands are multiplied together ('long multiplication'),
4484 resulting in a number which may be as long as the sum of the lengths
4485 of the two operands.
4486
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004487 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004488 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004489 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004490 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004491 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004492 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004493 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004494 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004495 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004496 Decimal('4.28135971E+11')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004497 """
4498 return a.__mul__(b, context=self)
4499
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004500 def next_minus(self, a):
4501 """Returns the largest representable number smaller than a.
4502
4503 >>> c = ExtendedContext.copy()
4504 >>> c.Emin = -999
4505 >>> c.Emax = 999
4506 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004507 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004508 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004509 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004510 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004511 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004512 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004513 Decimal('9.99999999E+999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004514 """
4515 return a.next_minus(context=self)
4516
4517 def next_plus(self, a):
4518 """Returns the smallest representable number larger than a.
4519
4520 >>> c = ExtendedContext.copy()
4521 >>> c.Emin = -999
4522 >>> c.Emax = 999
4523 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004524 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004525 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004526 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004527 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004528 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004529 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004530 Decimal('-9.99999999E+999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004531 """
4532 return a.next_plus(context=self)
4533
4534 def next_toward(self, a, b):
4535 """Returns the number closest to a, in direction towards b.
4536
4537 The result is the closest representable number from the first
4538 operand (but not the first operand) that is in the direction
4539 towards the second operand, unless the operands have the same
4540 value.
4541
4542 >>> c = ExtendedContext.copy()
4543 >>> c.Emin = -999
4544 >>> c.Emax = 999
4545 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004546 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004547 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004548 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004549 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004550 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004551 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004552 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004553 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004554 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004555 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004556 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004557 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004558 Decimal('-0.00')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004559 """
4560 return a.next_toward(b, context=self)
4561
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004562 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004563 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004564
4565 Essentially a plus operation with all trailing zeros removed from the
4566 result.
4567
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004568 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004569 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004570 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004571 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004572 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004573 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004574 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004575 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004576 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004577 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004578 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004579 Decimal('0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004580 """
4581 return a.normalize(context=self)
4582
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004583 def number_class(self, a):
4584 """Returns an indication of the class of the operand.
4585
4586 The class is one of the following strings:
4587 -sNaN
4588 -NaN
4589 -Infinity
4590 -Normal
4591 -Subnormal
4592 -Zero
4593 +Zero
4594 +Subnormal
4595 +Normal
4596 +Infinity
4597
4598 >>> c = Context(ExtendedContext)
4599 >>> c.Emin = -999
4600 >>> c.Emax = 999
4601 >>> c.number_class(Decimal('Infinity'))
4602 '+Infinity'
4603 >>> c.number_class(Decimal('1E-10'))
4604 '+Normal'
4605 >>> c.number_class(Decimal('2.50'))
4606 '+Normal'
4607 >>> c.number_class(Decimal('0.1E-999'))
4608 '+Subnormal'
4609 >>> c.number_class(Decimal('0'))
4610 '+Zero'
4611 >>> c.number_class(Decimal('-0'))
4612 '-Zero'
4613 >>> c.number_class(Decimal('-0.1E-999'))
4614 '-Subnormal'
4615 >>> c.number_class(Decimal('-1E-10'))
4616 '-Normal'
4617 >>> c.number_class(Decimal('-2.50'))
4618 '-Normal'
4619 >>> c.number_class(Decimal('-Infinity'))
4620 '-Infinity'
4621 >>> c.number_class(Decimal('NaN'))
4622 'NaN'
4623 >>> c.number_class(Decimal('-NaN'))
4624 'NaN'
4625 >>> c.number_class(Decimal('sNaN'))
4626 'sNaN'
4627 """
4628 return a.number_class(context=self)
4629
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004630 def plus(self, a):
4631 """Plus corresponds to unary prefix plus in Python.
4632
4633 The operation is evaluated using the same rules as add; the
4634 operation plus(a) is calculated as add('0', a) where the '0'
4635 has the same exponent as the operand.
4636
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004637 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004638 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004639 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004640 Decimal('-1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004641 """
4642 return a.__pos__(context=self)
4643
4644 def power(self, a, b, modulo=None):
4645 """Raises a to the power of b, to modulo if given.
4646
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004647 With two arguments, compute a**b. If a is negative then b
4648 must be integral. The result will be inexact unless b is
4649 integral and the result is finite and can be expressed exactly
4650 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004651
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004652 With three arguments, compute (a**b) % modulo. For the
4653 three argument form, the following restrictions on the
4654 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004655
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004656 - all three arguments must be integral
4657 - b must be nonnegative
4658 - at least one of a or b must be nonzero
4659 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004660
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004661 The result of pow(a, b, modulo) is identical to the result
4662 that would be obtained by computing (a**b) % modulo with
4663 unbounded precision, but is computed more efficiently. It is
4664 always exact.
4665
4666 >>> c = ExtendedContext.copy()
4667 >>> c.Emin = -999
4668 >>> c.Emax = 999
4669 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004670 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004671 >>> c.power(Decimal('-2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004672 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004673 >>> c.power(Decimal('2'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004674 Decimal('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004675 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004676 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004677 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004678 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004679 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004680 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004681 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004682 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004683 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004684 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004685 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004686 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004687 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004688 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004689 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004690 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004691 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004692 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004693 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004694 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004695
4696 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004697 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004698 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004699 Decimal('-11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004700 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004701 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004702 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004703 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004704 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004705 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004706 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004707 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004708 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004709 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004710 """
4711 return a.__pow__(b, modulo, context=self)
4712
4713 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004714 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004715
4716 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004717 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004718 exponent is being increased), multiplied by a positive power of ten (if
4719 the exponent is being decreased), or is unchanged (if the exponent is
4720 already equal to that of the right-hand operand).
4721
4722 Unlike other operations, if the length of the coefficient after the
4723 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004724 operation condition is raised. This guarantees that, unless there is
4725 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004726 equal to that of the right-hand operand.
4727
4728 Also unlike other operations, quantize will never raise Underflow, even
4729 if the result is subnormal and inexact.
4730
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004731 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004732 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004733 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004734 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004735 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004736 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004737 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004738 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004739 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004740 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004741 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004742 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004743 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004744 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004745 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004746 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004747 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004748 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004749 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004750 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004751 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004752 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004753 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004754 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004755 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004756 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004757 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004758 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004759 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004760 Decimal('2E+2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004761 """
4762 return a.quantize(b, context=self)
4763
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004764 def radix(self):
4765 """Just returns 10, as this is Decimal, :)
4766
4767 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004768 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004769 """
4770 return Decimal(10)
4771
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004772 def remainder(self, a, b):
4773 """Returns the remainder from integer division.
4774
4775 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004776 calculating integer division as described for divide-integer, rounded
4777 to precision digits if necessary. The sign of the result, if
4778 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004779
4780 This operation will fail under the same conditions as integer division
4781 (that is, if integer division on the same two operands would fail, the
4782 remainder cannot be calculated).
4783
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004784 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004785 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004786 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004787 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004788 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004789 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004790 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004791 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004792 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004793 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004794 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004795 Decimal('1.0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004796 """
4797 return a.__mod__(b, context=self)
4798
4799 def remainder_near(self, a, b):
4800 """Returns to be "a - b * n", where n is the integer nearest the exact
4801 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004802 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004803 sign of a.
4804
4805 This operation will fail under the same conditions as integer division
4806 (that is, if integer division on the same two operands would fail, the
4807 remainder cannot be calculated).
4808
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004809 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004810 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004811 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004812 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004813 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004814 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004815 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004816 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004817 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004818 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004819 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004820 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004821 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004822 Decimal('-0.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004823 """
4824 return a.remainder_near(b, context=self)
4825
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004826 def rotate(self, a, b):
4827 """Returns a rotated copy of a, b times.
4828
4829 The coefficient of the result is a rotated copy of the digits in
4830 the coefficient of the first operand. The number of places of
4831 rotation is taken from the absolute value of the second operand,
4832 with the rotation being to the left if the second operand is
4833 positive or to the right otherwise.
4834
4835 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004836 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004837 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004838 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004839 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004840 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004841 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004842 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004843 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004844 Decimal('345678912')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004845 """
4846 return a.rotate(b, context=self)
4847
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004848 def same_quantum(self, a, b):
4849 """Returns True if the two operands have the same exponent.
4850
4851 The result is never affected by either the sign or the coefficient of
4852 either operand.
4853
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004854 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004855 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004856 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004857 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004858 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004859 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004860 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004861 True
4862 """
4863 return a.same_quantum(b)
4864
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004865 def scaleb (self, a, b):
4866 """Returns the first operand after adding the second value its exp.
4867
4868 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004869 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004870 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004871 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004872 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004873 Decimal('7.50E+3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004874 """
4875 return a.scaleb (b, context=self)
4876
4877 def shift(self, a, b):
4878 """Returns a shifted copy of a, b times.
4879
4880 The coefficient of the result is a shifted copy of the digits
4881 in the coefficient of the first operand. The number of places
4882 to shift is taken from the absolute value of the second operand,
4883 with the shift being to the left if the second operand is
4884 positive or to the right otherwise. Digits shifted into the
4885 coefficient are zeros.
4886
4887 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004888 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004889 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004890 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004891 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004892 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004893 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004894 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004895 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004896 Decimal('345678900')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004897 """
4898 return a.shift(b, context=self)
4899
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004900 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004901 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004902
4903 If the result must be inexact, it is rounded using the round-half-even
4904 algorithm.
4905
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004906 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004907 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004908 >>> ExtendedContext.sqrt(Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004909 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004910 >>> ExtendedContext.sqrt(Decimal('0.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004911 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004912 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004913 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004914 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004915 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004916 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004917 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004918 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004919 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004920 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004921 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004922 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004923 Decimal('3.16227766')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004924 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004925 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004926 """
4927 return a.sqrt(context=self)
4928
4929 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004930 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004931
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004932 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004933 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004934 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004935 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004936 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004937 Decimal('-0.77')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004938 """
4939 return a.__sub__(b, context=self)
4940
4941 def to_eng_string(self, a):
4942 """Converts a number to a string, using scientific notation.
4943
4944 The operation is not affected by the context.
4945 """
4946 return a.to_eng_string(context=self)
4947
4948 def to_sci_string(self, a):
4949 """Converts a number to a string, using scientific notation.
4950
4951 The operation is not affected by the context.
4952 """
4953 return a.__str__(context=self)
4954
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004955 def to_integral_exact(self, a):
4956 """Rounds to an integer.
4957
4958 When the operand has a negative exponent, the result is the same
4959 as using the quantize() operation using the given operand as the
4960 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4961 of the operand as the precision setting; Inexact and Rounded flags
4962 are allowed in this operation. The rounding mode is taken from the
4963 context.
4964
4965 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004966 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004967 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004968 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004969 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004970 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004971 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004972 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004973 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004974 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004975 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004976 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004977 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004978 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004979 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004980 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004981 """
4982 return a.to_integral_exact(context=self)
4983
4984 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004985 """Rounds to an integer.
4986
4987 When the operand has a negative exponent, the result is the same
4988 as using the quantize() operation using the given operand as the
4989 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4990 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004991 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004992
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004993 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004994 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004995 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004996 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004997 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004998 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004999 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005000 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005001 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005002 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005003 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005004 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005005 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005006 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005007 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005008 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005009 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005010 return a.to_integral_value(context=self)
5011
5012 # the method name changed, but we provide also the old one, for compatibility
5013 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005014
5015class _WorkRep(object):
5016 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005017 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005018 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005019 # exp: None, int, or string
5020
5021 def __init__(self, value=None):
5022 if value is None:
5023 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005024 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005025 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005026 elif isinstance(value, Decimal):
5027 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005028 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005029 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005030 else:
5031 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005032 self.sign = value[0]
5033 self.int = value[1]
5034 self.exp = value[2]
5035
5036 def __repr__(self):
5037 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5038
5039 __str__ = __repr__
5040
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005041
5042
Christian Heimes2c181612007-12-17 20:04:13 +00005043def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005044 """Normalizes op1, op2 to have the same exp and length of coefficient.
5045
5046 Done during addition.
5047 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005048 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005049 tmp = op2
5050 other = op1
5051 else:
5052 tmp = op1
5053 other = op2
5054
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005055 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5056 # Then adding 10**exp to tmp has the same effect (after rounding)
5057 # as adding any positive quantity smaller than 10**exp; similarly
5058 # for subtraction. So if other is smaller than 10**exp we replace
5059 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00005060 tmp_len = len(str(tmp.int))
5061 other_len = len(str(other.int))
5062 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5063 if other_len + other.exp - 1 < exp:
5064 other.int = 1
5065 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005066
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005067 tmp.int *= 10 ** (tmp.exp - other.exp)
5068 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005069 return op1, op2
5070
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005071##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005072
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005073# This function from Tim Peters was taken from here:
5074# http://mail.python.org/pipermail/python-list/1999-July/007758.html
5075# The correction being in the function definition is for speed, and
5076# the whole function is not resolved with math.log because of avoiding
5077# the use of floats.
5078def _nbits(n, correction = {
5079 '0': 4, '1': 3, '2': 2, '3': 2,
5080 '4': 1, '5': 1, '6': 1, '7': 1,
5081 '8': 0, '9': 0, 'a': 0, 'b': 0,
5082 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
5083 """Number of bits in binary representation of the positive integer n,
5084 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005085 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005086 if n < 0:
5087 raise ValueError("The argument to _nbits should be nonnegative.")
5088 hex_n = "%x" % n
5089 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005090
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005091def _sqrt_nearest(n, a):
5092 """Closest integer to the square root of the positive integer n. a is
5093 an initial approximation to the square root. Any positive integer
5094 will do for a, but the closer a is to the square root of n the
5095 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005096
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005097 """
5098 if n <= 0 or a <= 0:
5099 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5100
5101 b=0
5102 while a != b:
5103 b, a = a, a--n//a>>1
5104 return a
5105
5106def _rshift_nearest(x, shift):
5107 """Given an integer x and a nonnegative integer shift, return closest
5108 integer to x / 2**shift; use round-to-even in case of a tie.
5109
5110 """
5111 b, q = 1 << shift, x >> shift
5112 return q + (2*(x & (b-1)) + (q&1) > b)
5113
5114def _div_nearest(a, b):
5115 """Closest integer to a/b, a and b positive integers; rounds to even
5116 in the case of a tie.
5117
5118 """
5119 q, r = divmod(a, b)
5120 return q + (2*r + (q&1) > b)
5121
5122def _ilog(x, M, L = 8):
5123 """Integer approximation to M*log(x/M), with absolute error boundable
5124 in terms only of x/M.
5125
5126 Given positive integers x and M, return an integer approximation to
5127 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5128 between the approximation and the exact result is at most 22. For
5129 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5130 both cases these are upper bounds on the error; it will usually be
5131 much smaller."""
5132
5133 # The basic algorithm is the following: let log1p be the function
5134 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5135 # the reduction
5136 #
5137 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5138 #
5139 # repeatedly until the argument to log1p is small (< 2**-L in
5140 # absolute value). For small y we can use the Taylor series
5141 # expansion
5142 #
5143 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5144 #
5145 # truncating at T such that y**T is small enough. The whole
5146 # computation is carried out in a form of fixed-point arithmetic,
5147 # with a real number z being represented by an integer
5148 # approximation to z*M. To avoid loss of precision, the y below
5149 # is actually an integer approximation to 2**R*y*M, where R is the
5150 # number of reductions performed so far.
5151
5152 y = x-M
5153 # argument reduction; R = number of reductions performed
5154 R = 0
5155 while (R <= L and abs(y) << L-R >= M or
5156 R > L and abs(y) >> R-L >= M):
5157 y = _div_nearest((M*y) << 1,
5158 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5159 R += 1
5160
5161 # Taylor series with T terms
5162 T = -int(-10*len(str(M))//(3*L))
5163 yshift = _rshift_nearest(y, R)
5164 w = _div_nearest(M, T)
5165 for k in range(T-1, 0, -1):
5166 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5167
5168 return _div_nearest(w*y, M)
5169
5170def _dlog10(c, e, p):
5171 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5172 approximation to 10**p * log10(c*10**e), with an absolute error of
5173 at most 1. Assumes that c*10**e is not exactly 1."""
5174
5175 # increase precision by 2; compensate for this by dividing
5176 # final result by 100
5177 p += 2
5178
5179 # write c*10**e as d*10**f with either:
5180 # f >= 0 and 1 <= d <= 10, or
5181 # f <= 0 and 0.1 <= d <= 1.
5182 # Thus for c*10**e close to 1, f = 0
5183 l = len(str(c))
5184 f = e+l - (e+l >= 1)
5185
5186 if p > 0:
5187 M = 10**p
5188 k = e+p-f
5189 if k >= 0:
5190 c *= 10**k
5191 else:
5192 c = _div_nearest(c, 10**-k)
5193
5194 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005195 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005196 log_d = _div_nearest(log_d*M, log_10)
5197 log_tenpower = f*M # exact
5198 else:
5199 log_d = 0 # error < 2.31
Neal Norwitz2f99b242008-08-24 05:48:10 +00005200 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005201
5202 return _div_nearest(log_tenpower+log_d, 100)
5203
5204def _dlog(c, e, p):
5205 """Given integers c, e and p with c > 0, compute an integer
5206 approximation to 10**p * log(c*10**e), with an absolute error of
5207 at most 1. Assumes that c*10**e is not exactly 1."""
5208
5209 # Increase precision by 2. The precision increase is compensated
5210 # for at the end with a division by 100.
5211 p += 2
5212
5213 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5214 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5215 # as 10**p * log(d) + 10**p*f * log(10).
5216 l = len(str(c))
5217 f = e+l - (e+l >= 1)
5218
5219 # compute approximation to 10**p*log(d), with error < 27
5220 if p > 0:
5221 k = e+p-f
5222 if k >= 0:
5223 c *= 10**k
5224 else:
5225 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5226
5227 # _ilog magnifies existing error in c by a factor of at most 10
5228 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5229 else:
5230 # p <= 0: just approximate the whole thing by 0; error < 2.31
5231 log_d = 0
5232
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005233 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005234 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005235 extra = len(str(abs(f)))-1
5236 if p + extra >= 0:
5237 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5238 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5239 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005240 else:
5241 f_log_ten = 0
5242 else:
5243 f_log_ten = 0
5244
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005245 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005246 return _div_nearest(f_log_ten + log_d, 100)
5247
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005248class _Log10Memoize(object):
5249 """Class to compute, store, and allow retrieval of, digits of the
5250 constant log(10) = 2.302585.... This constant is needed by
5251 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5252 def __init__(self):
5253 self.digits = "23025850929940456840179914546843642076011014886"
5254
5255 def getdigits(self, p):
5256 """Given an integer p >= 0, return floor(10**p)*log(10).
5257
5258 For example, self.getdigits(3) returns 2302.
5259 """
5260 # digits are stored as a string, for quick conversion to
5261 # integer in the case that we've already computed enough
5262 # digits; the stored digits should always be correct
5263 # (truncated, not rounded to nearest).
5264 if p < 0:
5265 raise ValueError("p should be nonnegative")
5266
5267 if p >= len(self.digits):
5268 # compute p+3, p+6, p+9, ... digits; continue until at
5269 # least one of the extra digits is nonzero
5270 extra = 3
5271 while True:
5272 # compute p+extra digits, correct to within 1ulp
5273 M = 10**(p+extra+2)
5274 digits = str(_div_nearest(_ilog(10*M, M), 100))
5275 if digits[-extra:] != '0'*extra:
5276 break
5277 extra += 3
5278 # keep all reliable digits so far; remove trailing zeros
5279 # and next nonzero digit
5280 self.digits = digits.rstrip('0')[:-1]
5281 return int(self.digits[:p+1])
5282
5283_log10_digits = _Log10Memoize().getdigits
5284
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005285def _iexp(x, M, L=8):
5286 """Given integers x and M, M > 0, such that x/M is small in absolute
5287 value, compute an integer approximation to M*exp(x/M). For 0 <=
5288 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5289 is usually much smaller)."""
5290
5291 # Algorithm: to compute exp(z) for a real number z, first divide z
5292 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5293 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5294 # series
5295 #
5296 # expm1(x) = x + x**2/2! + x**3/3! + ...
5297 #
5298 # Now use the identity
5299 #
5300 # expm1(2x) = expm1(x)*(expm1(x)+2)
5301 #
5302 # R times to compute the sequence expm1(z/2**R),
5303 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5304
5305 # Find R such that x/2**R/M <= 2**-L
5306 R = _nbits((x<<L)//M)
5307
5308 # Taylor series. (2**L)**T > M
5309 T = -int(-10*len(str(M))//(3*L))
5310 y = _div_nearest(x, T)
5311 Mshift = M<<R
5312 for i in range(T-1, 0, -1):
5313 y = _div_nearest(x*(Mshift + y), Mshift * i)
5314
5315 # Expansion
5316 for k in range(R-1, -1, -1):
5317 Mshift = M<<(k+2)
5318 y = _div_nearest(y*(y+Mshift), Mshift)
5319
5320 return M+y
5321
5322def _dexp(c, e, p):
5323 """Compute an approximation to exp(c*10**e), with p decimal places of
5324 precision.
5325
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005326 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005327
5328 10**(p-1) <= d <= 10**p, and
5329 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5330
5331 In other words, d*10**f is an approximation to exp(c*10**e) with p
5332 digits of precision, and with an error in d of at most 1. This is
5333 almost, but not quite, the same as the error being < 1ulp: when d
5334 = 10**(p-1) the error could be up to 10 ulp."""
5335
5336 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5337 p += 2
5338
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005339 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005340 extra = max(0, e + len(str(c)) - 1)
5341 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005342
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005343 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005344 # rounding down
5345 shift = e+q
5346 if shift >= 0:
5347 cshift = c*10**shift
5348 else:
5349 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005350 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005351
5352 # reduce remainder back to original precision
5353 rem = _div_nearest(rem, 10**extra)
5354
5355 # error in result of _iexp < 120; error after division < 0.62
5356 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5357
5358def _dpower(xc, xe, yc, ye, p):
5359 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5360 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5361
5362 10**(p-1) <= c <= 10**p, and
5363 (c-1)*10**e < x**y < (c+1)*10**e
5364
5365 in other words, c*10**e is an approximation to x**y with p digits
5366 of precision, and with an error in c of at most 1. (This is
5367 almost, but not quite, the same as the error being < 1ulp: when c
5368 == 10**(p-1) we can only guarantee error < 10ulp.)
5369
5370 We assume that: x is positive and not equal to 1, and y is nonzero.
5371 """
5372
5373 # Find b such that 10**(b-1) <= |y| <= 10**b
5374 b = len(str(abs(yc))) + ye
5375
5376 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5377 lxc = _dlog(xc, xe, p+b+1)
5378
5379 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5380 shift = ye-b
5381 if shift >= 0:
5382 pc = lxc*yc*10**shift
5383 else:
5384 pc = _div_nearest(lxc*yc, 10**-shift)
5385
5386 if pc == 0:
5387 # we prefer a result that isn't exactly 1; this makes it
5388 # easier to compute a correctly rounded result in __pow__
5389 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5390 coeff, exp = 10**(p-1)+1, 1-p
5391 else:
5392 coeff, exp = 10**p-1, -p
5393 else:
5394 coeff, exp = _dexp(pc, -(p+1), p+1)
5395 coeff = _div_nearest(coeff, 10)
5396 exp += 1
5397
5398 return coeff, exp
5399
5400def _log10_lb(c, correction = {
5401 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5402 '6': 23, '7': 16, '8': 10, '9': 5}):
5403 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5404 if c <= 0:
5405 raise ValueError("The argument to _log10_lb should be nonnegative.")
5406 str_c = str(c)
5407 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005408
Guido van Rossumd8faa362007-04-27 19:54:29 +00005409##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005410
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005411def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005412 """Convert other to Decimal.
5413
5414 Verifies that it's ok to use in an implicit construction.
5415 """
5416 if isinstance(other, Decimal):
5417 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005418 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005419 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005420 if raiseit:
5421 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005422 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005423
Guido van Rossumd8faa362007-04-27 19:54:29 +00005424##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005425
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005426# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005427# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005428
5429DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005430 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005431 traps=[DivisionByZero, Overflow, InvalidOperation],
5432 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005433 Emax=999999999,
5434 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005435 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005436)
5437
5438# Pre-made alternate contexts offered by the specification
5439# Don't change these; the user should be able to select these
5440# contexts and be able to reproduce results from other implementations
5441# of the spec.
5442
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005443BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005444 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005445 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5446 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005447)
5448
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005449ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005450 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005451 traps=[],
5452 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005453)
5454
5455
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005456##### crud for parsing strings #############################################
Christian Heimes23daade02008-02-25 12:39:23 +00005457#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005458# Regular expression used for parsing numeric strings. Additional
5459# comments:
5460#
5461# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5462# whitespace. But note that the specification disallows whitespace in
5463# a numeric string.
5464#
5465# 2. For finite numbers (not infinities and NaNs) the body of the
5466# number between the optional sign and the optional exponent must have
5467# at least one decimal digit, possibly after the decimal point. The
Antoine Pitroufd036452008-08-19 17:56:33 +00005468# lookahead expression '(?=[0-9]|\.[0-9])' checks this.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005469#
5470# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5471# other meaning for \d than the numbers [0-9].
5472
5473import re
Benjamin Peterson41181742008-07-02 20:22:54 +00005474_parser = re.compile(r""" # A numeric string consists of:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005475# \s*
Benjamin Peterson41181742008-07-02 20:22:54 +00005476 (?P<sign>[-+])? # an optional sign, followed by either...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005477 (
Benjamin Peterson41181742008-07-02 20:22:54 +00005478 (?=[0-9]|\.[0-9]) # ...a number (with at least one digit)
5479 (?P<int>[0-9]*) # having a (possibly empty) integer part
5480 (\.(?P<frac>[0-9]*))? # followed by an optional fractional part
5481 (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005482 |
Benjamin Peterson41181742008-07-02 20:22:54 +00005483 Inf(inity)? # ...an infinity, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005484 |
Benjamin Peterson41181742008-07-02 20:22:54 +00005485 (?P<signal>s)? # ...an (optionally signaling)
5486 NaN # NaN
5487 (?P<diag>[0-9]*) # with (possibly empty) diagnostic info.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005488 )
5489# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00005490 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005491""", re.VERBOSE | re.IGNORECASE).match
5492
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005493_all_zeros = re.compile('0*$').match
5494_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00005495
5496##### PEP3101 support functions ##############################################
5497# The functions parse_format_specifier and format_align have little to do
5498# with the Decimal class, and could potentially be reused for other pure
5499# Python numeric classes that want to implement __format__
5500#
5501# A format specifier for Decimal looks like:
5502#
5503# [[fill]align][sign][0][minimumwidth][.precision][type]
5504#
5505
5506_parse_format_specifier_regex = re.compile(r"""\A
5507(?:
5508 (?P<fill>.)?
5509 (?P<align>[<>=^])
5510)?
5511(?P<sign>[-+ ])?
5512(?P<zeropad>0)?
5513(?P<minimumwidth>(?!0)\d+)?
5514(?:\.(?P<precision>0|(?!0)\d+))?
5515(?P<type>[eEfFgG%])?
5516\Z
5517""", re.VERBOSE)
5518
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005519del re
5520
Christian Heimesf16baeb2008-02-29 14:57:44 +00005521def _parse_format_specifier(format_spec):
5522 """Parse and validate a format specifier.
5523
5524 Turns a standard numeric format specifier into a dict, with the
5525 following entries:
5526
5527 fill: fill character to pad field to minimum width
5528 align: alignment type, either '<', '>', '=' or '^'
5529 sign: either '+', '-' or ' '
5530 minimumwidth: nonnegative integer giving minimum width
5531 precision: nonnegative integer giving precision, or None
5532 type: one of the characters 'eEfFgG%', or None
5533 unicode: either True or False (always True for Python 3.x)
5534
5535 """
5536 m = _parse_format_specifier_regex.match(format_spec)
5537 if m is None:
5538 raise ValueError("Invalid format specifier: " + format_spec)
5539
5540 # get the dictionary
5541 format_dict = m.groupdict()
5542
5543 # defaults for fill and alignment
5544 fill = format_dict['fill']
5545 align = format_dict['align']
5546 if format_dict.pop('zeropad') is not None:
5547 # in the face of conflict, refuse the temptation to guess
5548 if fill is not None and fill != '0':
5549 raise ValueError("Fill character conflicts with '0'"
5550 " in format specifier: " + format_spec)
5551 if align is not None and align != '=':
5552 raise ValueError("Alignment conflicts with '0' in "
5553 "format specifier: " + format_spec)
5554 fill = '0'
5555 align = '='
5556 format_dict['fill'] = fill or ' '
5557 format_dict['align'] = align or '<'
5558
5559 if format_dict['sign'] is None:
5560 format_dict['sign'] = '-'
5561
5562 # turn minimumwidth and precision entries into integers.
5563 # minimumwidth defaults to 0; precision remains None if not given
5564 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5565 if format_dict['precision'] is not None:
5566 format_dict['precision'] = int(format_dict['precision'])
5567
5568 # if format type is 'g' or 'G' then a precision of 0 makes little
5569 # sense; convert it to 1. Same if format type is unspecified.
5570 if format_dict['precision'] == 0:
5571 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5572 format_dict['precision'] = 1
5573
5574 # record whether return type should be str or unicode
Christian Heimes295f4fa2008-02-29 15:03:39 +00005575 format_dict['unicode'] = True
Christian Heimesf16baeb2008-02-29 14:57:44 +00005576
5577 return format_dict
5578
5579def _format_align(body, spec_dict):
5580 """Given an unpadded, non-aligned numeric string, add padding and
5581 aligment to conform with the given format specifier dictionary (as
5582 output from parse_format_specifier).
5583
5584 It's assumed that if body is negative then it starts with '-'.
5585 Any leading sign ('-' or '+') is stripped from the body before
5586 applying the alignment and padding rules, and replaced in the
5587 appropriate position.
5588
5589 """
5590 # figure out the sign; we only examine the first character, so if
5591 # body has leading whitespace the results may be surprising.
5592 if len(body) > 0 and body[0] in '-+':
5593 sign = body[0]
5594 body = body[1:]
5595 else:
5596 sign = ''
5597
5598 if sign != '-':
5599 if spec_dict['sign'] in ' +':
5600 sign = spec_dict['sign']
5601 else:
5602 sign = ''
5603
5604 # how much extra space do we have to play with?
5605 minimumwidth = spec_dict['minimumwidth']
5606 fill = spec_dict['fill']
5607 padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5608
5609 align = spec_dict['align']
5610 if align == '<':
5611 result = padding + sign + body
5612 elif align == '>':
5613 result = sign + body + padding
5614 elif align == '=':
5615 result = sign + padding + body
5616 else: #align == '^'
5617 half = len(padding)//2
5618 result = padding[:half] + sign + body + padding[half:]
5619
Christian Heimesf16baeb2008-02-29 14:57:44 +00005620 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005621
Guido van Rossumd8faa362007-04-27 19:54:29 +00005622##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005623
Guido van Rossumd8faa362007-04-27 19:54:29 +00005624# Reusable defaults
Mark Dickinson627cf6a2009-01-03 12:11:47 +00005625_Infinity = Decimal('Inf')
5626_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonf9236412009-01-02 23:23:21 +00005627_NaN = Decimal('NaN')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00005628_Zero = Decimal(0)
5629_One = Decimal(1)
5630_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005631
Mark Dickinson627cf6a2009-01-03 12:11:47 +00005632# _SignedInfinity[sign] is infinity w/ that sign
5633_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005634
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005635
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005636
5637if __name__ == '__main__':
5638 import doctest, sys
5639 doctest.testmod(sys.modules[__name__])