blob: c46037e474b7c42b59634d023efb04eff21d53db [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
Raymond Hettingereb260842005-06-07 18:52:34 +0000137import copy as _copy
Raymond Hettinger771ed762009-01-03 19:20:32 +0000138import math as _math
Raymond Hettinger82417ca2009-02-03 03:54:28 +0000139import numbers as _numbers
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
Raymond Hettingera0fd8882009-01-20 07:24:44 +0000504# Do not subclass Decimal from numbers.Real and do not register it as such
505# (because Decimals are not interoperable with floats). See the notes in
506# numbers.py for more detail.
507
508class Decimal(object):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000509 """Floating point class for decimal arithmetic."""
510
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000511 __slots__ = ('_exp','_int','_sign', '_is_special')
512 # Generally, the value of the Decimal instance is given by
513 # (-1)**_sign * _int * 10**_exp
514 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000515
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000516 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000517 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000518 """Create a decimal point instance.
519
520 >>> Decimal('3.14') # string input
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000521 Decimal('3.14')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000522 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000523 Decimal('3.14')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000524 >>> Decimal(314) # int
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000525 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000526 >>> Decimal(Decimal(314)) # another decimal instance
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000527 Decimal('314')
Christian Heimesa62da1d2008-01-12 19:39:10 +0000528 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000529 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000530 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000531
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000532 # Note that the coefficient, self._int, is actually stored as
533 # a string rather than as a tuple of digits. This speeds up
534 # the "digits to integer" and "integer to digits" conversions
535 # that are used in almost every arithmetic operation on
536 # Decimals. This is an internal detail: the as_tuple function
537 # and the Decimal constructor still deal with tuples of
538 # digits.
539
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000540 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000541
Christian Heimesd59c64c2007-11-30 19:27:20 +0000542 # From a string
543 # REs insist on real strings, so we can too.
544 if isinstance(value, str):
Christian Heimesa62da1d2008-01-12 19:39:10 +0000545 m = _parser(value.strip())
Christian Heimesd59c64c2007-11-30 19:27:20 +0000546 if m is None:
547 if context is None:
548 context = getcontext()
549 return context._raise_error(ConversionSyntax,
550 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000551
Christian Heimesd59c64c2007-11-30 19:27:20 +0000552 if m.group('sign') == "-":
553 self._sign = 1
554 else:
555 self._sign = 0
556 intpart = m.group('int')
557 if intpart is not None:
558 # finite number
559 fracpart = m.group('frac')
560 exp = int(m.group('exp') or '0')
561 if fracpart is not None:
562 self._int = (intpart+fracpart).lstrip('0') or '0'
563 self._exp = exp - len(fracpart)
564 else:
565 self._int = intpart.lstrip('0') or '0'
566 self._exp = exp
567 self._is_special = False
568 else:
569 diag = m.group('diag')
570 if diag is not None:
571 # NaN
572 self._int = diag.lstrip('0')
573 if m.group('signal'):
574 self._exp = 'N'
575 else:
576 self._exp = 'n'
577 else:
578 # infinity
579 self._int = '0'
580 self._exp = 'F'
581 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000582 return self
583
584 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000585 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000586 if value >= 0:
587 self._sign = 0
588 else:
589 self._sign = 1
590 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000591 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000592 self._is_special = False
593 return self
594
595 # From another decimal
596 if isinstance(value, Decimal):
597 self._exp = value._exp
598 self._sign = value._sign
599 self._int = value._int
600 self._is_special = value._is_special
601 return self
602
603 # From an internal working value
604 if isinstance(value, _WorkRep):
605 self._sign = value.sign
606 self._int = str(value.int)
607 self._exp = int(value.exp)
608 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000609 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000610
611 # tuple/list conversion (possibly from as_tuple())
612 if isinstance(value, (list,tuple)):
613 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000614 raise ValueError('Invalid tuple size in creation of Decimal '
615 'from list or tuple. The list or tuple '
616 'should have exactly three elements.')
617 # process sign. The isinstance test rejects floats
618 if not (isinstance(value[0], int) and value[0] in (0,1)):
619 raise ValueError("Invalid sign. The first value in the tuple "
620 "should be an integer; either 0 for a "
621 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000622 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000623 if value[2] == 'F':
624 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000625 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000626 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000627 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000628 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000629 # process and validate the digits in value[1]
630 digits = []
631 for digit in value[1]:
632 if isinstance(digit, int) and 0 <= digit <= 9:
633 # skip leading zeros
634 if digits or digit != 0:
635 digits.append(digit)
636 else:
637 raise ValueError("The second value in the tuple must "
638 "be composed of integers in the range "
639 "0 through 9.")
640 if value[2] in ('n', 'N'):
641 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000642 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000643 self._exp = value[2]
644 self._is_special = True
645 elif isinstance(value[2], int):
646 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000647 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000648 self._exp = value[2]
649 self._is_special = False
650 else:
651 raise ValueError("The third value in the tuple must "
652 "be an integer, or one of the "
653 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000654 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000655
Raymond Hettingerbf440692004-07-10 14:14:37 +0000656 if isinstance(value, float):
657 raise TypeError("Cannot convert float to Decimal. " +
658 "First convert the float to a string")
659
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000660 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000661
Mark Dickinsonba298e42009-01-04 21:17:43 +0000662 # @classmethod, but @decorator is not valid Python 2.3 syntax, so
663 # don't use it (see notes on Py2.3 compatibility at top of file)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000664 def from_float(cls, f):
665 """Converts a float to a decimal number, exactly.
666
667 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
668 Since 0.1 is not exactly representable in binary floating point, the
669 value is stored as the nearest representable value which is
670 0x1.999999999999ap-4. The exact equivalent of the value in decimal
671 is 0.1000000000000000055511151231257827021181583404541015625.
672
673 >>> Decimal.from_float(0.1)
674 Decimal('0.1000000000000000055511151231257827021181583404541015625')
675 >>> Decimal.from_float(float('nan'))
676 Decimal('NaN')
677 >>> Decimal.from_float(float('inf'))
678 Decimal('Infinity')
679 >>> Decimal.from_float(-float('inf'))
680 Decimal('-Infinity')
681 >>> Decimal.from_float(-0.0)
682 Decimal('-0')
683
684 """
685 if isinstance(f, int): # handle integer inputs
686 return cls(f)
687 if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float
688 return cls(repr(f))
Mark Dickinsonba298e42009-01-04 21:17:43 +0000689 if _math.copysign(1.0, f) == 1.0:
690 sign = 0
691 else:
692 sign = 1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000693 n, d = abs(f).as_integer_ratio()
694 k = d.bit_length() - 1
695 result = _dec_from_triple(sign, str(n*5**k), -k)
Mark Dickinsonba298e42009-01-04 21:17:43 +0000696 if cls is Decimal:
697 return result
698 else:
699 return cls(result)
700 from_float = classmethod(from_float)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000701
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000702 def _isnan(self):
703 """Returns whether the number is not actually one.
704
705 0 if a number
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000706 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000707 2 if sNaN
708 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000709 if self._is_special:
710 exp = self._exp
711 if exp == 'n':
712 return 1
713 elif exp == 'N':
714 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000715 return 0
716
717 def _isinfinity(self):
718 """Returns whether the number is infinite
719
720 0 if finite or not a number
721 1 if +INF
722 -1 if -INF
723 """
724 if self._exp == 'F':
725 if self._sign:
726 return -1
727 return 1
728 return 0
729
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000730 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000731 """Returns whether the number is not actually one.
732
733 if self, other are sNaN, signal
734 if self, other are NaN return nan
735 return 0
736
737 Done before operations.
738 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000739
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000740 self_is_nan = self._isnan()
741 if other is None:
742 other_is_nan = False
743 else:
744 other_is_nan = other._isnan()
745
746 if self_is_nan or other_is_nan:
747 if context is None:
748 context = getcontext()
749
750 if self_is_nan == 2:
751 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000752 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000753 if other_is_nan == 2:
754 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000755 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000756 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000757 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000758
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000759 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000760 return 0
761
Christian Heimes77c02eb2008-02-09 02:18:51 +0000762 def _compare_check_nans(self, other, context):
763 """Version of _check_nans used for the signaling comparisons
764 compare_signal, __le__, __lt__, __ge__, __gt__.
765
766 Signal InvalidOperation if either self or other is a (quiet
767 or signaling) NaN. Signaling NaNs take precedence over quiet
768 NaNs.
769
770 Return 0 if neither operand is a NaN.
771
772 """
773 if context is None:
774 context = getcontext()
775
776 if self._is_special or other._is_special:
777 if self.is_snan():
778 return context._raise_error(InvalidOperation,
779 'comparison involving sNaN',
780 self)
781 elif other.is_snan():
782 return context._raise_error(InvalidOperation,
783 'comparison involving sNaN',
784 other)
785 elif self.is_qnan():
786 return context._raise_error(InvalidOperation,
787 'comparison involving NaN',
788 self)
789 elif other.is_qnan():
790 return context._raise_error(InvalidOperation,
791 'comparison involving NaN',
792 other)
793 return 0
794
Jack Diederich4dafcc42006-11-28 19:15:13 +0000795 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000796 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000797
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000798 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000799 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000800 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000801
Christian Heimes77c02eb2008-02-09 02:18:51 +0000802 def _cmp(self, other):
803 """Compare the two non-NaN decimal instances self and other.
804
805 Returns -1 if self < other, 0 if self == other and 1
806 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000807
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000808 if self._is_special or other._is_special:
Mark Dickinsone6aad752009-01-25 10:48:51 +0000809 self_inf = self._isinfinity()
810 other_inf = other._isinfinity()
811 if self_inf == other_inf:
812 return 0
813 elif self_inf < other_inf:
814 return -1
815 else:
816 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000817
Mark Dickinsone6aad752009-01-25 10:48:51 +0000818 # check for zeros; Decimal('0') == Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000819 if not self:
820 if not other:
821 return 0
822 else:
823 return -((-1)**other._sign)
824 if not other:
825 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000826
Guido van Rossumd8faa362007-04-27 19:54:29 +0000827 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000828 if other._sign < self._sign:
829 return -1
830 if self._sign < other._sign:
831 return 1
832
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000833 self_adjusted = self.adjusted()
834 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000835 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000836 self_padded = self._int + '0'*(self._exp - other._exp)
837 other_padded = other._int + '0'*(other._exp - self._exp)
Mark Dickinsone6aad752009-01-25 10:48:51 +0000838 if self_padded == other_padded:
839 return 0
840 elif self_padded < other_padded:
841 return -(-1)**self._sign
842 else:
843 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000844 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000845 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000846 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000847 return -((-1)**self._sign)
848
Christian Heimes77c02eb2008-02-09 02:18:51 +0000849 # Note: The Decimal standard doesn't cover rich comparisons for
850 # Decimals. In particular, the specification is silent on the
851 # subject of what should happen for a comparison involving a NaN.
852 # We take the following approach:
853 #
854 # == comparisons involving a NaN always return False
855 # != comparisons involving a NaN always return True
856 # <, >, <= and >= comparisons involving a (quiet or signaling)
857 # NaN signal InvalidOperation, and return False if the
Christian Heimes3feef612008-02-11 06:19:17 +0000858 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000859 #
860 # This behavior is designed to conform as closely as possible to
861 # that specified by IEEE 754.
862
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000863 def __eq__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000864 other = _convert_other(other)
865 if other is NotImplemented:
866 return other
867 if self.is_nan() or other.is_nan():
868 return False
869 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000870
871 def __ne__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000872 other = _convert_other(other)
873 if other is NotImplemented:
874 return other
875 if self.is_nan() or other.is_nan():
876 return True
877 return self._cmp(other) != 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000878
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000879
Christian Heimes77c02eb2008-02-09 02:18:51 +0000880 def __lt__(self, other, context=None):
881 other = _convert_other(other)
882 if other is NotImplemented:
883 return other
884 ans = self._compare_check_nans(other, context)
885 if ans:
886 return False
887 return self._cmp(other) < 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000888
Christian Heimes77c02eb2008-02-09 02:18:51 +0000889 def __le__(self, other, context=None):
890 other = _convert_other(other)
891 if other is NotImplemented:
892 return other
893 ans = self._compare_check_nans(other, context)
894 if ans:
895 return False
896 return self._cmp(other) <= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000897
Christian Heimes77c02eb2008-02-09 02:18:51 +0000898 def __gt__(self, other, context=None):
899 other = _convert_other(other)
900 if other is NotImplemented:
901 return other
902 ans = self._compare_check_nans(other, context)
903 if ans:
904 return False
905 return self._cmp(other) > 0
906
907 def __ge__(self, other, context=None):
908 other = _convert_other(other)
909 if other is NotImplemented:
910 return other
911 ans = self._compare_check_nans(other, context)
912 if ans:
913 return False
914 return self._cmp(other) >= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000915
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000916 def compare(self, other, context=None):
917 """Compares one to another.
918
919 -1 => a < b
920 0 => a = b
921 1 => a > b
922 NaN => one is NaN
923 Like __cmp__, but returns Decimal instances.
924 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000925 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000926
Guido van Rossumd8faa362007-04-27 19:54:29 +0000927 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000928 if (self._is_special or other and other._is_special):
929 ans = self._check_nans(other, context)
930 if ans:
931 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000932
Christian Heimes77c02eb2008-02-09 02:18:51 +0000933 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000934
935 def __hash__(self):
936 """x.__hash__() <==> hash(x)"""
937 # Decimal integers must hash the same as the ints
Christian Heimes2380ac72008-01-09 00:17:24 +0000938 #
939 # The hash of a nonspecial noninteger Decimal must depend only
940 # on the value of that Decimal, and not on its representation.
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000941 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000942 if self._is_special:
943 if self._isnan():
944 raise TypeError('Cannot hash a NaN value.')
945 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000946 if not self:
947 return 0
948 if self._isinteger():
949 op = _WorkRep(self.to_integral_value())
950 # to make computation feasible for Decimals with large
951 # exponent, we use the fact that hash(n) == hash(m) for
952 # any two nonzero integers n and m such that (i) n and m
953 # have the same sign, and (ii) n is congruent to m modulo
954 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
955 # hash((-1)**s*c*pow(10, e, 2**64-1).
956 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Christian Heimes2380ac72008-01-09 00:17:24 +0000957 # The value of a nonzero nonspecial Decimal instance is
958 # faithfully represented by the triple consisting of its sign,
959 # its adjusted exponent, and its coefficient with trailing
960 # zeros removed.
961 return hash((self._sign,
962 self._exp+len(self._int),
963 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000964
965 def as_tuple(self):
966 """Represents the number as a triple tuple.
967
968 To show the internals exactly as they are.
969 """
Christian Heimes25bb7832008-01-11 16:17:00 +0000970 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971
972 def __repr__(self):
973 """Represents the number as an instance of Decimal."""
974 # Invariant: eval(repr(d)) == d
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000975 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000976
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000977 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000978 """Return string representation of the number in scientific notation.
979
980 Captures all of the information in the underlying representation.
981 """
982
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000983 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000984 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000985 if self._exp == 'F':
986 return sign + 'Infinity'
987 elif self._exp == 'n':
988 return sign + 'NaN' + self._int
989 else: # self._exp == 'N'
990 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000991
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000992 # number of digits of self._int to left of decimal point
993 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000994
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000995 # dotplace is number of digits of self._int to the left of the
996 # decimal point in the mantissa of the output string (that is,
997 # after adjusting the exponent)
998 if self._exp <= 0 and leftdigits > -6:
999 # no exponent required
1000 dotplace = leftdigits
1001 elif not eng:
1002 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001003 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001004 elif self._int == '0':
1005 # engineering notation, zero
1006 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001007 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001008 # engineering notation, nonzero
1009 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001010
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001011 if dotplace <= 0:
1012 intpart = '0'
1013 fracpart = '.' + '0'*(-dotplace) + self._int
1014 elif dotplace >= len(self._int):
1015 intpart = self._int+'0'*(dotplace-len(self._int))
1016 fracpart = ''
1017 else:
1018 intpart = self._int[:dotplace]
1019 fracpart = '.' + self._int[dotplace:]
1020 if leftdigits == dotplace:
1021 exp = ''
1022 else:
1023 if context is None:
1024 context = getcontext()
1025 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1026
1027 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001028
1029 def to_eng_string(self, context=None):
1030 """Convert to engineering-type string.
1031
1032 Engineering notation has an exponent which is a multiple of 3, so there
1033 are up to 3 digits left of the decimal place.
1034
1035 Same rules for when in exponential and when as a value as in __str__.
1036 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001037 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001038
1039 def __neg__(self, context=None):
1040 """Returns a copy with the sign switched.
1041
1042 Rounds, if it has reason.
1043 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001044 if self._is_special:
1045 ans = self._check_nans(context=context)
1046 if ans:
1047 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001048
1049 if not self:
1050 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001051 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001052 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001053 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001054
1055 if context is None:
1056 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001057 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001058
1059 def __pos__(self, context=None):
1060 """Returns a copy, unless it is a sNaN.
1061
1062 Rounds the number (if more then precision digits)
1063 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001064 if self._is_special:
1065 ans = self._check_nans(context=context)
1066 if ans:
1067 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001068
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001069 if not self:
1070 # + (-0) = 0
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001071 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001072 else:
1073 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001074
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001075 if context is None:
1076 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001077 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001078
Christian Heimes2c181612007-12-17 20:04:13 +00001079 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001080 """Returns the absolute value of self.
1081
Christian Heimes2c181612007-12-17 20:04:13 +00001082 If the keyword argument 'round' is false, do not round. The
1083 expression self.__abs__(round=False) is equivalent to
1084 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001085 """
Christian Heimes2c181612007-12-17 20:04:13 +00001086 if not round:
1087 return self.copy_abs()
1088
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001089 if self._is_special:
1090 ans = self._check_nans(context=context)
1091 if ans:
1092 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001093
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001094 if self._sign:
1095 ans = self.__neg__(context=context)
1096 else:
1097 ans = self.__pos__(context=context)
1098
1099 return ans
1100
1101 def __add__(self, other, context=None):
1102 """Returns self + other.
1103
1104 -INF + INF (or the reverse) cause InvalidOperation errors.
1105 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001106 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001107 if other is NotImplemented:
1108 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001109
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001110 if context is None:
1111 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001112
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001113 if self._is_special or other._is_special:
1114 ans = self._check_nans(other, context)
1115 if ans:
1116 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001117
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001118 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001119 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001120 if self._sign != other._sign and other._isinfinity():
1121 return context._raise_error(InvalidOperation, '-INF + INF')
1122 return Decimal(self)
1123 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001124 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001125
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001126 exp = min(self._exp, other._exp)
1127 negativezero = 0
1128 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001129 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001130 negativezero = 1
1131
1132 if not self and not other:
1133 sign = min(self._sign, other._sign)
1134 if negativezero:
1135 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001136 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001137 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001138 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001139 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001140 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001141 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001142 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001143 return ans
1144 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001145 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001146 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001147 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001148 return ans
1149
1150 op1 = _WorkRep(self)
1151 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001152 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001153
1154 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001155 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001156 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001157 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001158 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001159 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001160 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001161 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001162 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001163 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001164 if op1.sign == 1:
1165 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001166 op1.sign, op2.sign = op2.sign, op1.sign
1167 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001168 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001169 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001170 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001171 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001172 op1.sign, op2.sign = (0, 0)
1173 else:
1174 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001175 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001176
Raymond Hettinger17931de2004-10-27 06:21:46 +00001177 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001178 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001179 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001180 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001181
1182 result.exp = op1.exp
1183 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001184 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001185 return ans
1186
1187 __radd__ = __add__
1188
1189 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001190 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001191 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001192 if other is NotImplemented:
1193 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001194
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001195 if self._is_special or other._is_special:
1196 ans = self._check_nans(other, context=context)
1197 if ans:
1198 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001199
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001200 # self - other is computed as self + other.copy_negate()
1201 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001202
1203 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001204 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001205 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001206 if other is NotImplemented:
1207 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001208
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001209 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001210
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001211 def __mul__(self, other, context=None):
1212 """Return self * other.
1213
1214 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1215 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001216 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001217 if other is NotImplemented:
1218 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001219
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001220 if context is None:
1221 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001222
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001223 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001224
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001225 if self._is_special or other._is_special:
1226 ans = self._check_nans(other, context)
1227 if ans:
1228 return ans
1229
1230 if self._isinfinity():
1231 if not other:
1232 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001233 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001234
1235 if other._isinfinity():
1236 if not self:
1237 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001238 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001239
1240 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001241
1242 # Special case for multiplying by zero
1243 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001244 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001245 # Fixing in case the exponent is out of bounds
1246 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001247 return ans
1248
1249 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001250 if self._int == '1':
1251 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001252 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001253 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001254 if other._int == '1':
1255 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001256 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001257 return ans
1258
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001259 op1 = _WorkRep(self)
1260 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001261
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001262 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001263 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001264
1265 return ans
1266 __rmul__ = __mul__
1267
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001268 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001269 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001270 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001271 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001272 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001273
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001274 if context is None:
1275 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001276
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001277 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001278
1279 if self._is_special or other._is_special:
1280 ans = self._check_nans(other, context)
1281 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001282 return ans
1283
1284 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001285 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001286
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001287 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001288 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001289
1290 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001291 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001292 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001293
1294 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001295 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001296 if not self:
1297 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001298 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001299
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001300 if not self:
1301 exp = self._exp - other._exp
1302 coeff = 0
1303 else:
1304 # OK, so neither = 0, INF or NaN
1305 shift = len(other._int) - len(self._int) + context.prec + 1
1306 exp = self._exp - other._exp - shift
1307 op1 = _WorkRep(self)
1308 op2 = _WorkRep(other)
1309 if shift >= 0:
1310 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1311 else:
1312 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1313 if remainder:
1314 # result is not exact; adjust to ensure correct rounding
1315 if coeff % 5 == 0:
1316 coeff += 1
1317 else:
1318 # result is exact; get as close to ideal exponent as possible
1319 ideal_exp = self._exp - other._exp
1320 while exp < ideal_exp and coeff % 10 == 0:
1321 coeff //= 10
1322 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001323
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001324 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001325 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001326
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001327 def _divide(self, other, context):
1328 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001329
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001330 Assumes that neither self nor other is a NaN, that self is not
1331 infinite and that other is nonzero.
1332 """
1333 sign = self._sign ^ other._sign
1334 if other._isinfinity():
1335 ideal_exp = self._exp
1336 else:
1337 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001338
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001339 expdiff = self.adjusted() - other.adjusted()
1340 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001341 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001342 self._rescale(ideal_exp, context.rounding))
1343 if expdiff <= context.prec:
1344 op1 = _WorkRep(self)
1345 op2 = _WorkRep(other)
1346 if op1.exp >= op2.exp:
1347 op1.int *= 10**(op1.exp - op2.exp)
1348 else:
1349 op2.int *= 10**(op2.exp - op1.exp)
1350 q, r = divmod(op1.int, op2.int)
1351 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001352 return (_dec_from_triple(sign, str(q), 0),
1353 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001354
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001355 # Here the quotient is too large to be representable
1356 ans = context._raise_error(DivisionImpossible,
1357 'quotient too large in //, % or divmod')
1358 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001359
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001360 def __rtruediv__(self, other, context=None):
1361 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001362 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001363 if other is NotImplemented:
1364 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001365 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001366
1367 def __divmod__(self, other, context=None):
1368 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001369 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001370 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001371 other = _convert_other(other)
1372 if other is NotImplemented:
1373 return other
1374
1375 if context is None:
1376 context = getcontext()
1377
1378 ans = self._check_nans(other, context)
1379 if ans:
1380 return (ans, ans)
1381
1382 sign = self._sign ^ other._sign
1383 if self._isinfinity():
1384 if other._isinfinity():
1385 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1386 return ans, ans
1387 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001388 return (_SignedInfinity[sign],
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001389 context._raise_error(InvalidOperation, 'INF % x'))
1390
1391 if not other:
1392 if not self:
1393 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1394 return ans, ans
1395 else:
1396 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1397 context._raise_error(InvalidOperation, 'x % 0'))
1398
1399 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001400 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001401 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001402
1403 def __rdivmod__(self, other, context=None):
1404 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001405 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001406 if other is NotImplemented:
1407 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001408 return other.__divmod__(self, context=context)
1409
1410 def __mod__(self, other, context=None):
1411 """
1412 self % other
1413 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001414 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001415 if other is NotImplemented:
1416 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001417
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001418 if context is None:
1419 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001420
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001421 ans = self._check_nans(other, context)
1422 if ans:
1423 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001424
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001425 if self._isinfinity():
1426 return context._raise_error(InvalidOperation, 'INF % x')
1427 elif not other:
1428 if self:
1429 return context._raise_error(InvalidOperation, 'x % 0')
1430 else:
1431 return context._raise_error(DivisionUndefined, '0 % 0')
1432
1433 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001434 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001435 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001436
1437 def __rmod__(self, other, context=None):
1438 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001439 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001440 if other is NotImplemented:
1441 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001442 return other.__mod__(self, context=context)
1443
1444 def remainder_near(self, other, context=None):
1445 """
1446 Remainder nearest to 0- abs(remainder-near) <= other/2
1447 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001448 if context is None:
1449 context = getcontext()
1450
1451 other = _convert_other(other, raiseit=True)
1452
1453 ans = self._check_nans(other, context)
1454 if ans:
1455 return ans
1456
1457 # self == +/-infinity -> InvalidOperation
1458 if self._isinfinity():
1459 return context._raise_error(InvalidOperation,
1460 'remainder_near(infinity, x)')
1461
1462 # other == 0 -> either InvalidOperation or DivisionUndefined
1463 if not other:
1464 if self:
1465 return context._raise_error(InvalidOperation,
1466 'remainder_near(x, 0)')
1467 else:
1468 return context._raise_error(DivisionUndefined,
1469 'remainder_near(0, 0)')
1470
1471 # other = +/-infinity -> remainder = self
1472 if other._isinfinity():
1473 ans = Decimal(self)
1474 return ans._fix(context)
1475
1476 # self = 0 -> remainder = self, with ideal exponent
1477 ideal_exponent = min(self._exp, other._exp)
1478 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001479 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001480 return ans._fix(context)
1481
1482 # catch most cases of large or small quotient
1483 expdiff = self.adjusted() - other.adjusted()
1484 if expdiff >= context.prec + 1:
1485 # expdiff >= prec+1 => abs(self/other) > 10**prec
1486 return context._raise_error(DivisionImpossible)
1487 if expdiff <= -2:
1488 # expdiff <= -2 => abs(self/other) < 0.1
1489 ans = self._rescale(ideal_exponent, context.rounding)
1490 return ans._fix(context)
1491
1492 # adjust both arguments to have the same exponent, then divide
1493 op1 = _WorkRep(self)
1494 op2 = _WorkRep(other)
1495 if op1.exp >= op2.exp:
1496 op1.int *= 10**(op1.exp - op2.exp)
1497 else:
1498 op2.int *= 10**(op2.exp - op1.exp)
1499 q, r = divmod(op1.int, op2.int)
1500 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1501 # 10**ideal_exponent. Apply correction to ensure that
1502 # abs(remainder) <= abs(other)/2
1503 if 2*r + (q&1) > op2.int:
1504 r -= op2.int
1505 q += 1
1506
1507 if q >= 10**context.prec:
1508 return context._raise_error(DivisionImpossible)
1509
1510 # result has same sign as self unless r is negative
1511 sign = self._sign
1512 if r < 0:
1513 sign = 1-sign
1514 r = -r
1515
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001516 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001517 return ans._fix(context)
1518
1519 def __floordiv__(self, other, context=None):
1520 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001521 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001522 if other is NotImplemented:
1523 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001524
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001525 if context is None:
1526 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001527
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001528 ans = self._check_nans(other, context)
1529 if ans:
1530 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001531
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001532 if self._isinfinity():
1533 if other._isinfinity():
1534 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001535 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001536 return _SignedInfinity[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001537
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001538 if not other:
1539 if self:
1540 return context._raise_error(DivisionByZero, 'x // 0',
1541 self._sign ^ other._sign)
1542 else:
1543 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001544
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001545 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001546
1547 def __rfloordiv__(self, other, context=None):
1548 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001549 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001550 if other is NotImplemented:
1551 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001552 return other.__floordiv__(self, context=context)
1553
1554 def __float__(self):
1555 """Float representation."""
1556 return float(str(self))
1557
1558 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001559 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001560 if self._is_special:
1561 if self._isnan():
1562 context = getcontext()
1563 return context._raise_error(InvalidContext)
1564 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001565 raise OverflowError("Cannot convert infinity to int")
1566 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001567 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001568 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001569 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001570 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001571
Christian Heimes969fe572008-01-25 11:23:10 +00001572 __trunc__ = __int__
1573
Christian Heimes0bd4e112008-02-12 22:59:25 +00001574 def real(self):
1575 return self
Mark Dickinson315a20a2009-01-04 21:34:18 +00001576 real = property(real)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001577
Christian Heimes0bd4e112008-02-12 22:59:25 +00001578 def imag(self):
1579 return Decimal(0)
Mark Dickinson315a20a2009-01-04 21:34:18 +00001580 imag = property(imag)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001581
1582 def conjugate(self):
1583 return self
1584
1585 def __complex__(self):
1586 return complex(float(self))
1587
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001588 def _fix_nan(self, context):
1589 """Decapitate the payload of a NaN to fit the context"""
1590 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001591
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001592 # maximum length of payload is precision if _clamp=0,
1593 # precision-1 if _clamp=1.
1594 max_payload_len = context.prec - context._clamp
1595 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001596 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1597 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001598 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001599
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001600 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001601 """Round if it is necessary to keep self within prec precision.
1602
1603 Rounds and fixes the exponent. Does not raise on a sNaN.
1604
1605 Arguments:
1606 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001607 context - context used.
1608 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001609
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001610 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001611 if self._isnan():
1612 # decapitate payload if necessary
1613 return self._fix_nan(context)
1614 else:
1615 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001616 return Decimal(self)
1617
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001618 # if self is zero then exponent should be between Etiny and
1619 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1620 Etiny = context.Etiny()
1621 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001622 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001623 exp_max = [context.Emax, Etop][context._clamp]
1624 new_exp = min(max(self._exp, Etiny), exp_max)
1625 if new_exp != self._exp:
1626 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001627 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001628 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001629 return Decimal(self)
1630
1631 # exp_min is the smallest allowable exponent of the result,
1632 # equal to max(self.adjusted()-context.prec+1, Etiny)
1633 exp_min = len(self._int) + self._exp - context.prec
1634 if exp_min > Etop:
1635 # overflow: exp_min > Etop iff self.adjusted() > Emax
1636 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001637 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001638 return context._raise_error(Overflow, 'above Emax', self._sign)
1639 self_is_subnormal = exp_min < Etiny
1640 if self_is_subnormal:
1641 context._raise_error(Subnormal)
1642 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001643
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001644 # round if self has too many digits
1645 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001646 context._raise_error(Rounded)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001647 digits = len(self._int) + self._exp - exp_min
1648 if digits < 0:
1649 self = _dec_from_triple(self._sign, '1', exp_min-1)
1650 digits = 0
1651 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1652 changed = this_function(digits)
1653 coeff = self._int[:digits] or '0'
1654 if changed == 1:
1655 coeff = str(int(coeff)+1)
1656 ans = _dec_from_triple(self._sign, coeff, exp_min)
1657
1658 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001659 context._raise_error(Inexact)
1660 if self_is_subnormal:
1661 context._raise_error(Underflow)
1662 if not ans:
1663 # raise Clamped on underflow to 0
1664 context._raise_error(Clamped)
1665 elif len(ans._int) == context.prec+1:
1666 # we get here only if rescaling rounds the
1667 # cofficient up to exactly 10**context.prec
1668 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001669 ans = _dec_from_triple(ans._sign,
1670 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001671 else:
1672 # Inexact and Rounded have already been raised
1673 ans = context._raise_error(Overflow, 'above Emax',
1674 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001675 return ans
1676
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001677 # fold down if _clamp == 1 and self has too few digits
1678 if context._clamp == 1 and self._exp > Etop:
1679 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001680 self_padded = self._int + '0'*(self._exp - Etop)
1681 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001682
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001683 # here self was representable to begin with; return unchanged
1684 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001685
1686 _pick_rounding_function = {}
1687
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001688 # for each of the rounding functions below:
1689 # self is a finite, nonzero Decimal
1690 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001691 #
1692 # each function returns either -1, 0, or 1, as follows:
1693 # 1 indicates that self should be rounded up (away from zero)
1694 # 0 indicates that self should be truncated, and that all the
1695 # digits to be truncated are zeros (so the value is unchanged)
1696 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001697
1698 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001699 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001700 if _all_zeros(self._int, prec):
1701 return 0
1702 else:
1703 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001704
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001705 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001706 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001707 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001708
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001709 def _round_half_up(self, prec):
1710 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001711 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001712 return 1
1713 elif _all_zeros(self._int, prec):
1714 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001715 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001716 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001717
1718 def _round_half_down(self, prec):
1719 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001720 if _exact_half(self._int, prec):
1721 return -1
1722 else:
1723 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001724
1725 def _round_half_even(self, prec):
1726 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001727 if _exact_half(self._int, prec) and \
1728 (prec == 0 or self._int[prec-1] in '02468'):
1729 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001730 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001731 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001732
1733 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001734 """Rounds up (not away from 0 if negative.)"""
1735 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001736 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001737 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001738 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001739
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001740 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001741 """Rounds down (not towards 0 if negative)"""
1742 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001743 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001744 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001745 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001746
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001747 def _round_05up(self, prec):
1748 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001749 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001750 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001751 else:
1752 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001753
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001754 def __round__(self, n=None):
1755 """Round self to the nearest integer, or to a given precision.
1756
1757 If only one argument is supplied, round a finite Decimal
1758 instance self to the nearest integer. If self is infinite or
1759 a NaN then a Python exception is raised. If self is finite
1760 and lies exactly halfway between two integers then it is
1761 rounded to the integer with even last digit.
1762
1763 >>> round(Decimal('123.456'))
1764 123
1765 >>> round(Decimal('-456.789'))
1766 -457
1767 >>> round(Decimal('-3.0'))
1768 -3
1769 >>> round(Decimal('2.5'))
1770 2
1771 >>> round(Decimal('3.5'))
1772 4
1773 >>> round(Decimal('Inf'))
1774 Traceback (most recent call last):
1775 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001776 OverflowError: cannot round an infinity
1777 >>> round(Decimal('NaN'))
1778 Traceback (most recent call last):
1779 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001780 ValueError: cannot round a NaN
1781
1782 If a second argument n is supplied, self is rounded to n
1783 decimal places using the rounding mode for the current
1784 context.
1785
1786 For an integer n, round(self, -n) is exactly equivalent to
1787 self.quantize(Decimal('1En')).
1788
1789 >>> round(Decimal('123.456'), 0)
1790 Decimal('123')
1791 >>> round(Decimal('123.456'), 2)
1792 Decimal('123.46')
1793 >>> round(Decimal('123.456'), -2)
1794 Decimal('1E+2')
1795 >>> round(Decimal('-Infinity'), 37)
1796 Decimal('NaN')
1797 >>> round(Decimal('sNaN123'), 0)
1798 Decimal('NaN123')
1799
1800 """
1801 if n is not None:
1802 # two-argument form: use the equivalent quantize call
1803 if not isinstance(n, int):
1804 raise TypeError('Second argument to round should be integral')
1805 exp = _dec_from_triple(0, '1', -n)
1806 return self.quantize(exp)
1807
1808 # one-argument form
1809 if self._is_special:
1810 if self.is_nan():
1811 raise ValueError("cannot round a NaN")
1812 else:
1813 raise OverflowError("cannot round an infinity")
1814 return int(self._rescale(0, ROUND_HALF_EVEN))
1815
1816 def __floor__(self):
1817 """Return the floor of self, as an integer.
1818
1819 For a finite Decimal instance self, return the greatest
1820 integer n such that n <= self. If self is infinite or a NaN
1821 then a Python exception is raised.
1822
1823 """
1824 if self._is_special:
1825 if self.is_nan():
1826 raise ValueError("cannot round a NaN")
1827 else:
1828 raise OverflowError("cannot round an infinity")
1829 return int(self._rescale(0, ROUND_FLOOR))
1830
1831 def __ceil__(self):
1832 """Return the ceiling of self, as an integer.
1833
1834 For a finite Decimal instance self, return the least integer n
1835 such that n >= self. If self is infinite or a NaN then a
1836 Python exception is raised.
1837
1838 """
1839 if self._is_special:
1840 if self.is_nan():
1841 raise ValueError("cannot round a NaN")
1842 else:
1843 raise OverflowError("cannot round an infinity")
1844 return int(self._rescale(0, ROUND_CEILING))
1845
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001846 def fma(self, other, third, context=None):
1847 """Fused multiply-add.
1848
1849 Returns self*other+third with no rounding of the intermediate
1850 product self*other.
1851
1852 self and other are multiplied together, with no rounding of
1853 the result. The third operand is then added to the result,
1854 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001855 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001856
1857 other = _convert_other(other, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001858
1859 # compute product; raise InvalidOperation if either operand is
1860 # a signaling NaN or if the product is zero times infinity.
1861 if self._is_special or other._is_special:
1862 if context is None:
1863 context = getcontext()
1864 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001865 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001866 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001867 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001868 if self._exp == 'n':
1869 product = self
1870 elif other._exp == 'n':
1871 product = other
1872 elif self._exp == 'F':
1873 if not other:
1874 return context._raise_error(InvalidOperation,
1875 'INF * 0 in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001876 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001877 elif other._exp == 'F':
1878 if not self:
1879 return context._raise_error(InvalidOperation,
1880 '0 * INF in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001881 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001882 else:
1883 product = _dec_from_triple(self._sign ^ other._sign,
1884 str(int(self._int) * int(other._int)),
1885 self._exp + other._exp)
1886
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001887 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001888 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001889
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001890 def _power_modulo(self, other, modulo, context=None):
1891 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001892
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001893 # if can't convert other and modulo to Decimal, raise
1894 # TypeError; there's no point returning NotImplemented (no
1895 # equivalent of __rpow__ for three argument pow)
1896 other = _convert_other(other, raiseit=True)
1897 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001898
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001899 if context is None:
1900 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001901
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001902 # deal with NaNs: if there are any sNaNs then first one wins,
1903 # (i.e. behaviour for NaNs is identical to that of fma)
1904 self_is_nan = self._isnan()
1905 other_is_nan = other._isnan()
1906 modulo_is_nan = modulo._isnan()
1907 if self_is_nan or other_is_nan or modulo_is_nan:
1908 if self_is_nan == 2:
1909 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001910 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001911 if other_is_nan == 2:
1912 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001913 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001914 if modulo_is_nan == 2:
1915 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001916 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001917 if self_is_nan:
1918 return self._fix_nan(context)
1919 if other_is_nan:
1920 return other._fix_nan(context)
1921 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001922
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001923 # check inputs: we apply same restrictions as Python's pow()
1924 if not (self._isinteger() and
1925 other._isinteger() and
1926 modulo._isinteger()):
1927 return context._raise_error(InvalidOperation,
1928 'pow() 3rd argument not allowed '
1929 'unless all arguments are integers')
1930 if other < 0:
1931 return context._raise_error(InvalidOperation,
1932 'pow() 2nd argument cannot be '
1933 'negative when 3rd argument specified')
1934 if not modulo:
1935 return context._raise_error(InvalidOperation,
1936 'pow() 3rd argument cannot be 0')
1937
1938 # additional restriction for decimal: the modulus must be less
1939 # than 10**prec in absolute value
1940 if modulo.adjusted() >= context.prec:
1941 return context._raise_error(InvalidOperation,
1942 'insufficient precision: pow() 3rd '
1943 'argument must not have more than '
1944 'precision digits')
1945
1946 # define 0**0 == NaN, for consistency with two-argument pow
1947 # (even though it hurts!)
1948 if not other and not self:
1949 return context._raise_error(InvalidOperation,
1950 'at least one of pow() 1st argument '
1951 'and 2nd argument must be nonzero ;'
1952 '0**0 is not defined')
1953
1954 # compute sign of result
1955 if other._iseven():
1956 sign = 0
1957 else:
1958 sign = self._sign
1959
1960 # convert modulo to a Python integer, and self and other to
1961 # Decimal integers (i.e. force their exponents to be >= 0)
1962 modulo = abs(int(modulo))
1963 base = _WorkRep(self.to_integral_value())
1964 exponent = _WorkRep(other.to_integral_value())
1965
1966 # compute result using integer pow()
1967 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1968 for i in range(exponent.exp):
1969 base = pow(base, 10, modulo)
1970 base = pow(base, exponent.int, modulo)
1971
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001972 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001973
1974 def _power_exact(self, other, p):
1975 """Attempt to compute self**other exactly.
1976
1977 Given Decimals self and other and an integer p, attempt to
1978 compute an exact result for the power self**other, with p
1979 digits of precision. Return None if self**other is not
1980 exactly representable in p digits.
1981
1982 Assumes that elimination of special cases has already been
1983 performed: self and other must both be nonspecial; self must
1984 be positive and not numerically equal to 1; other must be
1985 nonzero. For efficiency, other._exp should not be too large,
1986 so that 10**abs(other._exp) is a feasible calculation."""
1987
1988 # In the comments below, we write x for the value of self and
1989 # y for the value of other. Write x = xc*10**xe and y =
1990 # yc*10**ye.
1991
1992 # The main purpose of this method is to identify the *failure*
1993 # of x**y to be exactly representable with as little effort as
1994 # possible. So we look for cheap and easy tests that
1995 # eliminate the possibility of x**y being exact. Only if all
1996 # these tests are passed do we go on to actually compute x**y.
1997
1998 # Here's the main idea. First normalize both x and y. We
1999 # express y as a rational m/n, with m and n relatively prime
2000 # and n>0. Then for x**y to be exactly representable (at
2001 # *any* precision), xc must be the nth power of a positive
2002 # integer and xe must be divisible by n. If m is negative
2003 # then additionally xc must be a power of either 2 or 5, hence
2004 # a power of 2**n or 5**n.
2005 #
2006 # There's a limit to how small |y| can be: if y=m/n as above
2007 # then:
2008 #
2009 # (1) if xc != 1 then for the result to be representable we
2010 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
2011 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
2012 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
2013 # representable.
2014 #
2015 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
2016 # |y| < 1/|xe| then the result is not representable.
2017 #
2018 # Note that since x is not equal to 1, at least one of (1) and
2019 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2020 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2021 #
2022 # There's also a limit to how large y can be, at least if it's
2023 # positive: the normalized result will have coefficient xc**y,
2024 # so if it's representable then xc**y < 10**p, and y <
2025 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
2026 # not exactly representable.
2027
2028 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2029 # so |y| < 1/xe and the result is not representable.
2030 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2031 # < 1/nbits(xc).
2032
2033 x = _WorkRep(self)
2034 xc, xe = x.int, x.exp
2035 while xc % 10 == 0:
2036 xc //= 10
2037 xe += 1
2038
2039 y = _WorkRep(other)
2040 yc, ye = y.int, y.exp
2041 while yc % 10 == 0:
2042 yc //= 10
2043 ye += 1
2044
2045 # case where xc == 1: result is 10**(xe*y), with xe*y
2046 # required to be an integer
2047 if xc == 1:
2048 if ye >= 0:
2049 exponent = xe*yc*10**ye
2050 else:
2051 exponent, remainder = divmod(xe*yc, 10**-ye)
2052 if remainder:
2053 return None
2054 if y.sign == 1:
2055 exponent = -exponent
2056 # if other is a nonnegative integer, use ideal exponent
2057 if other._isinteger() and other._sign == 0:
2058 ideal_exponent = self._exp*int(other)
2059 zeros = min(exponent-ideal_exponent, p-1)
2060 else:
2061 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002062 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002063
2064 # case where y is negative: xc must be either a power
2065 # of 2 or a power of 5.
2066 if y.sign == 1:
2067 last_digit = xc % 10
2068 if last_digit in (2,4,6,8):
2069 # quick test for power of 2
2070 if xc & -xc != xc:
2071 return None
2072 # now xc is a power of 2; e is its exponent
2073 e = _nbits(xc)-1
2074 # find e*y and xe*y; both must be integers
2075 if ye >= 0:
2076 y_as_int = yc*10**ye
2077 e = e*y_as_int
2078 xe = xe*y_as_int
2079 else:
2080 ten_pow = 10**-ye
2081 e, remainder = divmod(e*yc, ten_pow)
2082 if remainder:
2083 return None
2084 xe, remainder = divmod(xe*yc, ten_pow)
2085 if remainder:
2086 return None
2087
2088 if e*65 >= p*93: # 93/65 > log(10)/log(5)
2089 return None
2090 xc = 5**e
2091
2092 elif last_digit == 5:
2093 # e >= log_5(xc) if xc is a power of 5; we have
2094 # equality all the way up to xc=5**2658
2095 e = _nbits(xc)*28//65
2096 xc, remainder = divmod(5**e, xc)
2097 if remainder:
2098 return None
2099 while xc % 5 == 0:
2100 xc //= 5
2101 e -= 1
2102 if ye >= 0:
2103 y_as_integer = yc*10**ye
2104 e = e*y_as_integer
2105 xe = xe*y_as_integer
2106 else:
2107 ten_pow = 10**-ye
2108 e, remainder = divmod(e*yc, ten_pow)
2109 if remainder:
2110 return None
2111 xe, remainder = divmod(xe*yc, ten_pow)
2112 if remainder:
2113 return None
2114 if e*3 >= p*10: # 10/3 > log(10)/log(2)
2115 return None
2116 xc = 2**e
2117 else:
2118 return None
2119
2120 if xc >= 10**p:
2121 return None
2122 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002123 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002124
2125 # now y is positive; find m and n such that y = m/n
2126 if ye >= 0:
2127 m, n = yc*10**ye, 1
2128 else:
2129 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2130 return None
2131 xc_bits = _nbits(xc)
2132 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2133 return None
2134 m, n = yc, 10**(-ye)
2135 while m % 2 == n % 2 == 0:
2136 m //= 2
2137 n //= 2
2138 while m % 5 == n % 5 == 0:
2139 m //= 5
2140 n //= 5
2141
2142 # compute nth root of xc*10**xe
2143 if n > 1:
2144 # if 1 < xc < 2**n then xc isn't an nth power
2145 if xc != 1 and xc_bits <= n:
2146 return None
2147
2148 xe, rem = divmod(xe, n)
2149 if rem != 0:
2150 return None
2151
2152 # compute nth root of xc using Newton's method
2153 a = 1 << -(-_nbits(xc)//n) # initial estimate
2154 while True:
2155 q, r = divmod(xc, a**(n-1))
2156 if a <= q:
2157 break
2158 else:
2159 a = (a*(n-1) + q)//n
2160 if not (a == q and r == 0):
2161 return None
2162 xc = a
2163
2164 # now xc*10**xe is the nth root of the original xc*10**xe
2165 # compute mth power of xc*10**xe
2166
2167 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2168 # 10**p and the result is not representable.
2169 if xc > 1 and m > p*100//_log10_lb(xc):
2170 return None
2171 xc = xc**m
2172 xe *= m
2173 if xc > 10**p:
2174 return None
2175
2176 # by this point the result *is* exactly representable
2177 # adjust the exponent to get as close as possible to the ideal
2178 # exponent, if necessary
2179 str_xc = str(xc)
2180 if other._isinteger() and other._sign == 0:
2181 ideal_exponent = self._exp*int(other)
2182 zeros = min(xe-ideal_exponent, p-len(str_xc))
2183 else:
2184 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002185 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002186
2187 def __pow__(self, other, modulo=None, context=None):
2188 """Return self ** other [ % modulo].
2189
2190 With two arguments, compute self**other.
2191
2192 With three arguments, compute (self**other) % modulo. For the
2193 three argument form, the following restrictions on the
2194 arguments hold:
2195
2196 - all three arguments must be integral
2197 - other must be nonnegative
2198 - either self or other (or both) must be nonzero
2199 - modulo must be nonzero and must have at most p digits,
2200 where p is the context precision.
2201
2202 If any of these restrictions is violated the InvalidOperation
2203 flag is raised.
2204
2205 The result of pow(self, other, modulo) is identical to the
2206 result that would be obtained by computing (self**other) %
2207 modulo with unbounded precision, but is computed more
2208 efficiently. It is always exact.
2209 """
2210
2211 if modulo is not None:
2212 return self._power_modulo(other, modulo, context)
2213
2214 other = _convert_other(other)
2215 if other is NotImplemented:
2216 return other
2217
2218 if context is None:
2219 context = getcontext()
2220
2221 # either argument is a NaN => result is NaN
2222 ans = self._check_nans(other, context)
2223 if ans:
2224 return ans
2225
2226 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2227 if not other:
2228 if not self:
2229 return context._raise_error(InvalidOperation, '0 ** 0')
2230 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002231 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002232
2233 # result has sign 1 iff self._sign is 1 and other is an odd integer
2234 result_sign = 0
2235 if self._sign == 1:
2236 if other._isinteger():
2237 if not other._iseven():
2238 result_sign = 1
2239 else:
2240 # -ve**noninteger = NaN
2241 # (-0)**noninteger = 0**noninteger
2242 if self:
2243 return context._raise_error(InvalidOperation,
2244 'x ** y with x negative and y not an integer')
2245 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002246 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002247
2248 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2249 if not self:
2250 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002251 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002252 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002253 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002254
2255 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002256 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002257 if other._sign == 0:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002258 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002259 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002260 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002261
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002262 # 1**other = 1, but the choice of exponent and the flags
2263 # depend on the exponent of self, and on whether other is a
2264 # positive integer, a negative integer, or neither
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002265 if self == _One:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002266 if other._isinteger():
2267 # exp = max(self._exp*max(int(other), 0),
2268 # 1-context.prec) but evaluating int(other) directly
2269 # is dangerous until we know other is small (other
2270 # could be 1e999999999)
2271 if other._sign == 1:
2272 multiplier = 0
2273 elif other > context.prec:
2274 multiplier = context.prec
2275 else:
2276 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002277
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002278 exp = self._exp * multiplier
2279 if exp < 1-context.prec:
2280 exp = 1-context.prec
2281 context._raise_error(Rounded)
2282 else:
2283 context._raise_error(Inexact)
2284 context._raise_error(Rounded)
2285 exp = 1-context.prec
2286
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002287 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002288
2289 # compute adjusted exponent of self
2290 self_adj = self.adjusted()
2291
2292 # self ** infinity is infinity if self > 1, 0 if self < 1
2293 # self ** -infinity is infinity if self < 1, 0 if self > 1
2294 if other._isinfinity():
2295 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002296 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002297 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002298 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002299
2300 # from here on, the result always goes through the call
2301 # to _fix at the end of this function.
2302 ans = None
2303
2304 # crude test to catch cases of extreme overflow/underflow. If
2305 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2306 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2307 # self**other >= 10**(Emax+1), so overflow occurs. The test
2308 # for underflow is similar.
2309 bound = self._log10_exp_bound() + other.adjusted()
2310 if (self_adj >= 0) == (other._sign == 0):
2311 # self > 1 and other +ve, or self < 1 and other -ve
2312 # possibility of overflow
2313 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002314 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002315 else:
2316 # self > 1 and other -ve, or self < 1 and other +ve
2317 # possibility of underflow to 0
2318 Etiny = context.Etiny()
2319 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002320 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002321
2322 # try for an exact result with precision +1
2323 if ans is None:
2324 ans = self._power_exact(other, context.prec + 1)
2325 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002326 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002327
2328 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2329 if ans is None:
2330 p = context.prec
2331 x = _WorkRep(self)
2332 xc, xe = x.int, x.exp
2333 y = _WorkRep(other)
2334 yc, ye = y.int, y.exp
2335 if y.sign == 1:
2336 yc = -yc
2337
2338 # compute correctly rounded result: start with precision +3,
2339 # then increase precision until result is unambiguously roundable
2340 extra = 3
2341 while True:
2342 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2343 if coeff % (5*10**(len(str(coeff))-p-1)):
2344 break
2345 extra += 3
2346
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002347 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002348
2349 # the specification says that for non-integer other we need to
2350 # raise Inexact, even when the result is actually exact. In
2351 # the same way, we need to raise Underflow here if the result
2352 # is subnormal. (The call to _fix will take care of raising
2353 # Rounded and Subnormal, as usual.)
2354 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002355 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002356 # pad with zeros up to length context.prec+1 if necessary
2357 if len(ans._int) <= context.prec:
2358 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002359 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2360 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002361 if ans.adjusted() < context.Emin:
2362 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002363
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002364 # unlike exp, ln and log10, the power function respects the
2365 # rounding mode; no need to use ROUND_HALF_EVEN here
2366 ans = ans._fix(context)
2367 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002368
2369 def __rpow__(self, other, context=None):
2370 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002371 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002372 if other is NotImplemented:
2373 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002374 return other.__pow__(self, context=context)
2375
2376 def normalize(self, context=None):
2377 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002378
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002379 if context is None:
2380 context = getcontext()
2381
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002382 if self._is_special:
2383 ans = self._check_nans(context=context)
2384 if ans:
2385 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002386
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002387 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002388 if dup._isinfinity():
2389 return dup
2390
2391 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002392 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002393 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002394 end = len(dup._int)
2395 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002396 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002397 exp += 1
2398 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002399 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002400
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002401 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002402 """Quantize self so its exponent is the same as that of exp.
2403
2404 Similar to self._rescale(exp._exp) but with error checking.
2405 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002406 exp = _convert_other(exp, raiseit=True)
2407
2408 if context is None:
2409 context = getcontext()
2410 if rounding is None:
2411 rounding = context.rounding
2412
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002413 if self._is_special or exp._is_special:
2414 ans = self._check_nans(exp, context)
2415 if ans:
2416 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002417
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002418 if exp._isinfinity() or self._isinfinity():
2419 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002420 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002421 return context._raise_error(InvalidOperation,
2422 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002423
2424 # if we're not watching exponents, do a simple rescale
2425 if not watchexp:
2426 ans = self._rescale(exp._exp, rounding)
2427 # raise Inexact and Rounded where appropriate
2428 if ans._exp > self._exp:
2429 context._raise_error(Rounded)
2430 if ans != self:
2431 context._raise_error(Inexact)
2432 return ans
2433
2434 # exp._exp should be between Etiny and Emax
2435 if not (context.Etiny() <= exp._exp <= context.Emax):
2436 return context._raise_error(InvalidOperation,
2437 'target exponent out of bounds in quantize')
2438
2439 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002440 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002441 return ans._fix(context)
2442
2443 self_adjusted = self.adjusted()
2444 if self_adjusted > context.Emax:
2445 return context._raise_error(InvalidOperation,
2446 'exponent of quantize result too large for current context')
2447 if self_adjusted - exp._exp + 1 > context.prec:
2448 return context._raise_error(InvalidOperation,
2449 'quantize result has too many digits for current context')
2450
2451 ans = self._rescale(exp._exp, rounding)
2452 if ans.adjusted() > context.Emax:
2453 return context._raise_error(InvalidOperation,
2454 'exponent of quantize result too large for current context')
2455 if len(ans._int) > context.prec:
2456 return context._raise_error(InvalidOperation,
2457 'quantize result has too many digits for current context')
2458
2459 # raise appropriate flags
2460 if ans._exp > self._exp:
2461 context._raise_error(Rounded)
2462 if ans != self:
2463 context._raise_error(Inexact)
2464 if ans and ans.adjusted() < context.Emin:
2465 context._raise_error(Subnormal)
2466
2467 # call to fix takes care of any necessary folddown
2468 ans = ans._fix(context)
2469 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002470
2471 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002472 """Return True if self and other have the same exponent; otherwise
2473 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002474
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002475 If either operand is a special value, the following rules are used:
2476 * return True if both operands are infinities
2477 * return True if both operands are NaNs
2478 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002479 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002480 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002481 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002482 return (self.is_nan() and other.is_nan() or
2483 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002484 return self._exp == other._exp
2485
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002486 def _rescale(self, exp, rounding):
2487 """Rescale self so that the exponent is exp, either by padding with zeros
2488 or by truncating digits, using the given rounding mode.
2489
2490 Specials are returned without change. This operation is
2491 quiet: it raises no flags, and uses no information from the
2492 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002493
2494 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002495 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002496 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002497 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002498 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002499 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002500 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002501
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002502 if self._exp >= exp:
2503 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002504 return _dec_from_triple(self._sign,
2505 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002506
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002507 # too many digits; round and lose data. If self.adjusted() <
2508 # exp-1, replace self by 10**(exp-1) before rounding
2509 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002510 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002511 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002512 digits = 0
2513 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002514 changed = this_function(digits)
2515 coeff = self._int[:digits] or '0'
2516 if changed == 1:
2517 coeff = str(int(coeff)+1)
2518 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002519
Christian Heimesf16baeb2008-02-29 14:57:44 +00002520 def _round(self, places, rounding):
2521 """Round a nonzero, nonspecial Decimal to a fixed number of
2522 significant figures, using the given rounding mode.
2523
2524 Infinities, NaNs and zeros are returned unaltered.
2525
2526 This operation is quiet: it raises no flags, and uses no
2527 information from the context.
2528
2529 """
2530 if places <= 0:
2531 raise ValueError("argument should be at least 1 in _round")
2532 if self._is_special or not self:
2533 return Decimal(self)
2534 ans = self._rescale(self.adjusted()+1-places, rounding)
2535 # it can happen that the rescale alters the adjusted exponent;
2536 # for example when rounding 99.97 to 3 significant figures.
2537 # When this happens we end up with an extra 0 at the end of
2538 # the number; a second rescale fixes this.
2539 if ans.adjusted() != self.adjusted():
2540 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2541 return ans
2542
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002543 def to_integral_exact(self, rounding=None, context=None):
2544 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002545
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002546 If no rounding mode is specified, take the rounding mode from
2547 the context. This method raises the Rounded and Inexact flags
2548 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002549
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002550 See also: to_integral_value, which does exactly the same as
2551 this method except that it doesn't raise Inexact or Rounded.
2552 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002553 if self._is_special:
2554 ans = self._check_nans(context=context)
2555 if ans:
2556 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002557 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002558 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002559 return Decimal(self)
2560 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002561 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002562 if context is None:
2563 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002564 if rounding is None:
2565 rounding = context.rounding
2566 context._raise_error(Rounded)
2567 ans = self._rescale(0, rounding)
2568 if ans != self:
2569 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002570 return ans
2571
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002572 def to_integral_value(self, rounding=None, context=None):
2573 """Rounds to the nearest integer, without raising inexact, rounded."""
2574 if context is None:
2575 context = getcontext()
2576 if rounding is None:
2577 rounding = context.rounding
2578 if self._is_special:
2579 ans = self._check_nans(context=context)
2580 if ans:
2581 return ans
2582 return Decimal(self)
2583 if self._exp >= 0:
2584 return Decimal(self)
2585 else:
2586 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002587
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002588 # the method name changed, but we provide also the old one, for compatibility
2589 to_integral = to_integral_value
2590
2591 def sqrt(self, context=None):
2592 """Return the square root of self."""
Christian Heimes0348fb62008-03-26 12:55:56 +00002593 if context is None:
2594 context = getcontext()
2595
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002596 if self._is_special:
2597 ans = self._check_nans(context=context)
2598 if ans:
2599 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002600
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002601 if self._isinfinity() and self._sign == 0:
2602 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002603
2604 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002605 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002606 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002607 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002608
2609 if self._sign == 1:
2610 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2611
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002612 # At this point self represents a positive number. Let p be
2613 # the desired precision and express self in the form c*100**e
2614 # with c a positive real number and e an integer, c and e
2615 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2616 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2617 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2618 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2619 # the closest integer to sqrt(c) with the even integer chosen
2620 # in the case of a tie.
2621 #
2622 # To ensure correct rounding in all cases, we use the
2623 # following trick: we compute the square root to an extra
2624 # place (precision p+1 instead of precision p), rounding down.
2625 # Then, if the result is inexact and its last digit is 0 or 5,
2626 # we increase the last digit to 1 or 6 respectively; if it's
2627 # exact we leave the last digit alone. Now the final round to
2628 # p places (or fewer in the case of underflow) will round
2629 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002630
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002631 # use an extra digit of precision
2632 prec = context.prec+1
2633
2634 # write argument in the form c*100**e where e = self._exp//2
2635 # is the 'ideal' exponent, to be used if the square root is
2636 # exactly representable. l is the number of 'digits' of c in
2637 # base 100, so that 100**(l-1) <= c < 100**l.
2638 op = _WorkRep(self)
2639 e = op.exp >> 1
2640 if op.exp & 1:
2641 c = op.int * 10
2642 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002643 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002644 c = op.int
2645 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002646
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002647 # rescale so that c has exactly prec base 100 'digits'
2648 shift = prec-l
2649 if shift >= 0:
2650 c *= 100**shift
2651 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002652 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002653 c, remainder = divmod(c, 100**-shift)
2654 exact = not remainder
2655 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002656
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002657 # find n = floor(sqrt(c)) using Newton's method
2658 n = 10**prec
2659 while True:
2660 q = c//n
2661 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002662 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002663 else:
2664 n = n + q >> 1
2665 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002666
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002667 if exact:
2668 # result is exact; rescale to use ideal exponent e
2669 if shift >= 0:
2670 # assert n % 10**shift == 0
2671 n //= 10**shift
2672 else:
2673 n *= 10**-shift
2674 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002675 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002676 # result is not exact; fix last digit as described above
2677 if n % 5 == 0:
2678 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002679
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002680 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002681
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002682 # round, and fit to current context
2683 context = context._shallow_copy()
2684 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002685 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002686 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002687
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002688 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002689
2690 def max(self, other, context=None):
2691 """Returns the larger value.
2692
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002693 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002694 NaN (and signals if one is sNaN). Also rounds.
2695 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002696 other = _convert_other(other, raiseit=True)
2697
2698 if context is None:
2699 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002700
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002701 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002702 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002703 # number is always returned
2704 sn = self._isnan()
2705 on = other._isnan()
2706 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002707 if on == 1 and sn == 0:
2708 return self._fix(context)
2709 if sn == 1 and on == 0:
2710 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002711 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002712
Christian Heimes77c02eb2008-02-09 02:18:51 +00002713 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002714 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002715 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002716 # then an ordering is applied:
2717 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002718 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002719 # positive sign and min returns the operand with the negative sign
2720 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002721 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002722 # the result. This is exactly the ordering used in compare_total.
2723 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002724
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002725 if c == -1:
2726 ans = other
2727 else:
2728 ans = self
2729
Christian Heimes2c181612007-12-17 20:04:13 +00002730 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002731
2732 def min(self, other, context=None):
2733 """Returns the smaller value.
2734
Guido van Rossumd8faa362007-04-27 19:54:29 +00002735 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002736 NaN (and signals if one is sNaN). Also rounds.
2737 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002738 other = _convert_other(other, raiseit=True)
2739
2740 if context is None:
2741 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002742
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002743 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002744 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002745 # number is always returned
2746 sn = self._isnan()
2747 on = other._isnan()
2748 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002749 if on == 1 and sn == 0:
2750 return self._fix(context)
2751 if sn == 1 and on == 0:
2752 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002753 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002754
Christian Heimes77c02eb2008-02-09 02:18:51 +00002755 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002756 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002757 c = self.compare_total(other)
2758
2759 if c == -1:
2760 ans = self
2761 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002762 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002763
Christian Heimes2c181612007-12-17 20:04:13 +00002764 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002765
2766 def _isinteger(self):
2767 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002768 if self._is_special:
2769 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002770 if self._exp >= 0:
2771 return True
2772 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002773 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002774
2775 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002776 """Returns True if self is even. Assumes self is an integer."""
2777 if not self or self._exp > 0:
2778 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002779 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002780
2781 def adjusted(self):
2782 """Return the adjusted exponent of self"""
2783 try:
2784 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002785 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002786 except TypeError:
2787 return 0
2788
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002789 def canonical(self, context=None):
2790 """Returns the same Decimal object.
2791
2792 As we do not have different encodings for the same number, the
2793 received object already is in its canonical form.
2794 """
2795 return self
2796
2797 def compare_signal(self, other, context=None):
2798 """Compares self to the other operand numerically.
2799
2800 It's pretty much like compare(), but all NaNs signal, with signaling
2801 NaNs taking precedence over quiet NaNs.
2802 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002803 other = _convert_other(other, raiseit = True)
2804 ans = self._compare_check_nans(other, context)
2805 if ans:
2806 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002807 return self.compare(other, context=context)
2808
2809 def compare_total(self, other):
2810 """Compares self to other using the abstract representations.
2811
2812 This is not like the standard compare, which use their numerical
2813 value. Note that a total ordering is defined for all possible abstract
2814 representations.
2815 """
2816 # if one is negative and the other is positive, it's easy
2817 if self._sign and not other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002818 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002819 if not self._sign and other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002820 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002821 sign = self._sign
2822
2823 # let's handle both NaN types
2824 self_nan = self._isnan()
2825 other_nan = other._isnan()
2826 if self_nan or other_nan:
2827 if self_nan == other_nan:
2828 if self._int < other._int:
2829 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002830 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002831 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002832 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002833 if self._int > other._int:
2834 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002835 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002836 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002837 return _One
2838 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002839
2840 if sign:
2841 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002842 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002843 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002844 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002845 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002846 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002847 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002848 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002849 else:
2850 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002851 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002852 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002853 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002854 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002855 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002856 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002857 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002858
2859 if self < other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002860 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002861 if self > other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002862 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002863
2864 if self._exp < other._exp:
2865 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002866 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002867 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002868 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002869 if self._exp > other._exp:
2870 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002871 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002872 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002873 return _One
2874 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002875
2876
2877 def compare_total_mag(self, other):
2878 """Compares self to other using abstract repr., ignoring sign.
2879
2880 Like compare_total, but with operand's sign ignored and assumed to be 0.
2881 """
2882 s = self.copy_abs()
2883 o = other.copy_abs()
2884 return s.compare_total(o)
2885
2886 def copy_abs(self):
2887 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002888 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002889
2890 def copy_negate(self):
2891 """Returns a copy with the sign inverted."""
2892 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002893 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002894 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002895 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002896
2897 def copy_sign(self, other):
2898 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002899 return _dec_from_triple(other._sign, self._int,
2900 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002901
2902 def exp(self, context=None):
2903 """Returns e ** self."""
2904
2905 if context is None:
2906 context = getcontext()
2907
2908 # exp(NaN) = NaN
2909 ans = self._check_nans(context=context)
2910 if ans:
2911 return ans
2912
2913 # exp(-Infinity) = 0
2914 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002915 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002916
2917 # exp(0) = 1
2918 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002919 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002920
2921 # exp(Infinity) = Infinity
2922 if self._isinfinity() == 1:
2923 return Decimal(self)
2924
2925 # the result is now guaranteed to be inexact (the true
2926 # mathematical result is transcendental). There's no need to
2927 # raise Rounded and Inexact here---they'll always be raised as
2928 # a result of the call to _fix.
2929 p = context.prec
2930 adj = self.adjusted()
2931
2932 # we only need to do any computation for quite a small range
2933 # of adjusted exponents---for example, -29 <= adj <= 10 for
2934 # the default context. For smaller exponent the result is
2935 # indistinguishable from 1 at the given precision, while for
2936 # larger exponent the result either overflows or underflows.
2937 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2938 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002939 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002940 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2941 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002942 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002943 elif self._sign == 0 and adj < -p:
2944 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002945 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002946 elif self._sign == 1 and adj < -p-1:
2947 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002948 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002949 # general case
2950 else:
2951 op = _WorkRep(self)
2952 c, e = op.int, op.exp
2953 if op.sign == 1:
2954 c = -c
2955
2956 # compute correctly rounded result: increase precision by
2957 # 3 digits at a time until we get an unambiguously
2958 # roundable result
2959 extra = 3
2960 while True:
2961 coeff, exp = _dexp(c, e, p+extra)
2962 if coeff % (5*10**(len(str(coeff))-p-1)):
2963 break
2964 extra += 3
2965
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002966 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002967
2968 # at this stage, ans should round correctly with *any*
2969 # rounding mode, not just with ROUND_HALF_EVEN
2970 context = context._shallow_copy()
2971 rounding = context._set_rounding(ROUND_HALF_EVEN)
2972 ans = ans._fix(context)
2973 context.rounding = rounding
2974
2975 return ans
2976
2977 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002978 """Return True if self is canonical; otherwise return False.
2979
2980 Currently, the encoding of a Decimal instance is always
2981 canonical, so this method returns True for any Decimal.
2982 """
2983 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002984
2985 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002986 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002987
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002988 A Decimal instance is considered finite if it is neither
2989 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002990 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002991 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002992
2993 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002994 """Return True if self is infinite; otherwise return False."""
2995 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002996
2997 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002998 """Return True if self is a qNaN or sNaN; otherwise return False."""
2999 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003000
3001 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003002 """Return True if self is a normal number; 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 context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003008
3009 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003010 """Return True if self is a quiet NaN; otherwise return False."""
3011 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003012
3013 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003014 """Return True if self is negative; otherwise return False."""
3015 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003016
3017 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003018 """Return True if self is a signaling NaN; otherwise return False."""
3019 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003020
3021 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003022 """Return True if self is subnormal; otherwise return False."""
3023 if self._is_special or not self:
3024 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003025 if context is None:
3026 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003027 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003028
3029 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003030 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003031 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003032
3033 def _ln_exp_bound(self):
3034 """Compute a lower bound for the adjusted exponent of self.ln().
3035 In other words, compute r such that self.ln() >= 10**r. Assumes
3036 that self is finite and positive and that self != 1.
3037 """
3038
3039 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
3040 adj = self._exp + len(self._int) - 1
3041 if adj >= 1:
3042 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
3043 return len(str(adj*23//10)) - 1
3044 if adj <= -2:
3045 # argument <= 0.1
3046 return len(str((-1-adj)*23//10)) - 1
3047 op = _WorkRep(self)
3048 c, e = op.int, op.exp
3049 if adj == 0:
3050 # 1 < self < 10
3051 num = str(c-10**-e)
3052 den = str(c)
3053 return len(num) - len(den) - (num < den)
3054 # adj == -1, 0.1 <= self < 1
3055 return e + len(str(10**-e - c)) - 1
3056
3057
3058 def ln(self, context=None):
3059 """Returns the natural (base e) logarithm of self."""
3060
3061 if context is None:
3062 context = getcontext()
3063
3064 # ln(NaN) = NaN
3065 ans = self._check_nans(context=context)
3066 if ans:
3067 return ans
3068
3069 # ln(0.0) == -Infinity
3070 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003071 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003072
3073 # ln(Infinity) = Infinity
3074 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003075 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003076
3077 # ln(1.0) == 0.0
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003078 if self == _One:
3079 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003080
3081 # ln(negative) raises InvalidOperation
3082 if self._sign == 1:
3083 return context._raise_error(InvalidOperation,
3084 'ln of a negative value')
3085
3086 # result is irrational, so necessarily inexact
3087 op = _WorkRep(self)
3088 c, e = op.int, op.exp
3089 p = context.prec
3090
3091 # correctly rounded result: repeatedly increase precision by 3
3092 # until we get an unambiguously roundable result
3093 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3094 while True:
3095 coeff = _dlog(c, e, places)
3096 # assert len(str(abs(coeff)))-p >= 1
3097 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3098 break
3099 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003100 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003101
3102 context = context._shallow_copy()
3103 rounding = context._set_rounding(ROUND_HALF_EVEN)
3104 ans = ans._fix(context)
3105 context.rounding = rounding
3106 return ans
3107
3108 def _log10_exp_bound(self):
3109 """Compute a lower bound for the adjusted exponent of self.log10().
3110 In other words, find r such that self.log10() >= 10**r.
3111 Assumes that self is finite and positive and that self != 1.
3112 """
3113
3114 # For x >= 10 or x < 0.1 we only need a bound on the integer
3115 # part of log10(self), and this comes directly from the
3116 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3117 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3118 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3119
3120 adj = self._exp + len(self._int) - 1
3121 if adj >= 1:
3122 # self >= 10
3123 return len(str(adj))-1
3124 if adj <= -2:
3125 # self < 0.1
3126 return len(str(-1-adj))-1
3127 op = _WorkRep(self)
3128 c, e = op.int, op.exp
3129 if adj == 0:
3130 # 1 < self < 10
3131 num = str(c-10**-e)
3132 den = str(231*c)
3133 return len(num) - len(den) - (num < den) + 2
3134 # adj == -1, 0.1 <= self < 1
3135 num = str(10**-e-c)
3136 return len(num) + e - (num < "231") - 1
3137
3138 def log10(self, context=None):
3139 """Returns the base 10 logarithm of self."""
3140
3141 if context is None:
3142 context = getcontext()
3143
3144 # log10(NaN) = NaN
3145 ans = self._check_nans(context=context)
3146 if ans:
3147 return ans
3148
3149 # log10(0.0) == -Infinity
3150 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003151 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003152
3153 # log10(Infinity) = Infinity
3154 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003155 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003156
3157 # log10(negative or -Infinity) raises InvalidOperation
3158 if self._sign == 1:
3159 return context._raise_error(InvalidOperation,
3160 'log10 of a negative value')
3161
3162 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003163 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003164 # answer may need rounding
3165 ans = Decimal(self._exp + len(self._int) - 1)
3166 else:
3167 # result is irrational, so necessarily inexact
3168 op = _WorkRep(self)
3169 c, e = op.int, op.exp
3170 p = context.prec
3171
3172 # correctly rounded result: repeatedly increase precision
3173 # until result is unambiguously roundable
3174 places = p-self._log10_exp_bound()+2
3175 while True:
3176 coeff = _dlog10(c, e, places)
3177 # assert len(str(abs(coeff)))-p >= 1
3178 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3179 break
3180 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003181 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003182
3183 context = context._shallow_copy()
3184 rounding = context._set_rounding(ROUND_HALF_EVEN)
3185 ans = ans._fix(context)
3186 context.rounding = rounding
3187 return ans
3188
3189 def logb(self, context=None):
3190 """ Returns the exponent of the magnitude of self's MSD.
3191
3192 The result is the integer which is the exponent of the magnitude
3193 of the most significant digit of self (as though it were truncated
3194 to a single digit while maintaining the value of that digit and
3195 without limiting the resulting exponent).
3196 """
3197 # logb(NaN) = NaN
3198 ans = self._check_nans(context=context)
3199 if ans:
3200 return ans
3201
3202 if context is None:
3203 context = getcontext()
3204
3205 # logb(+/-Inf) = +Inf
3206 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003207 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003208
3209 # logb(0) = -Inf, DivisionByZero
3210 if not self:
3211 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3212
3213 # otherwise, simply return the adjusted exponent of self, as a
3214 # Decimal. Note that no attempt is made to fit the result
3215 # into the current context.
3216 return Decimal(self.adjusted())
3217
3218 def _islogical(self):
3219 """Return True if self is a logical operand.
3220
Christian Heimes679db4a2008-01-18 09:56:22 +00003221 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003222 an exponent of 0, and a coefficient whose digits must all be
3223 either 0 or 1.
3224 """
3225 if self._sign != 0 or self._exp != 0:
3226 return False
3227 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003228 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003229 return False
3230 return True
3231
3232 def _fill_logical(self, context, opa, opb):
3233 dif = context.prec - len(opa)
3234 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003235 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003236 elif dif < 0:
3237 opa = opa[-context.prec:]
3238 dif = context.prec - len(opb)
3239 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003240 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003241 elif dif < 0:
3242 opb = opb[-context.prec:]
3243 return opa, opb
3244
3245 def logical_and(self, other, context=None):
3246 """Applies an 'and' operation between self and other's digits."""
3247 if context is None:
3248 context = getcontext()
3249 if not self._islogical() or not other._islogical():
3250 return context._raise_error(InvalidOperation)
3251
3252 # fill to context.prec
3253 (opa, opb) = self._fill_logical(context, self._int, other._int)
3254
3255 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003256 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3257 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003258
3259 def logical_invert(self, context=None):
3260 """Invert all its digits."""
3261 if context is None:
3262 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003263 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3264 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003265
3266 def logical_or(self, other, context=None):
3267 """Applies an 'or' operation between self and other's digits."""
3268 if context is None:
3269 context = getcontext()
3270 if not self._islogical() or not other._islogical():
3271 return context._raise_error(InvalidOperation)
3272
3273 # fill to context.prec
3274 (opa, opb) = self._fill_logical(context, self._int, other._int)
3275
3276 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003277 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003278 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003279
3280 def logical_xor(self, other, context=None):
3281 """Applies an 'xor' operation between self and other's digits."""
3282 if context is None:
3283 context = getcontext()
3284 if not self._islogical() or not other._islogical():
3285 return context._raise_error(InvalidOperation)
3286
3287 # fill to context.prec
3288 (opa, opb) = self._fill_logical(context, self._int, other._int)
3289
3290 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003291 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003292 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003293
3294 def max_mag(self, other, context=None):
3295 """Compares the values numerically with their sign ignored."""
3296 other = _convert_other(other, raiseit=True)
3297
3298 if context is None:
3299 context = getcontext()
3300
3301 if self._is_special or other._is_special:
3302 # If one operand is a quiet NaN and the other is number, then the
3303 # number is always returned
3304 sn = self._isnan()
3305 on = other._isnan()
3306 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003307 if on == 1 and sn == 0:
3308 return self._fix(context)
3309 if sn == 1 and on == 0:
3310 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003311 return self._check_nans(other, context)
3312
Christian Heimes77c02eb2008-02-09 02:18:51 +00003313 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003314 if c == 0:
3315 c = self.compare_total(other)
3316
3317 if c == -1:
3318 ans = other
3319 else:
3320 ans = self
3321
Christian Heimes2c181612007-12-17 20:04:13 +00003322 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003323
3324 def min_mag(self, other, context=None):
3325 """Compares the values numerically with their sign ignored."""
3326 other = _convert_other(other, raiseit=True)
3327
3328 if context is None:
3329 context = getcontext()
3330
3331 if self._is_special or other._is_special:
3332 # If one operand is a quiet NaN and the other is number, then the
3333 # number is always returned
3334 sn = self._isnan()
3335 on = other._isnan()
3336 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003337 if on == 1 and sn == 0:
3338 return self._fix(context)
3339 if sn == 1 and on == 0:
3340 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003341 return self._check_nans(other, context)
3342
Christian Heimes77c02eb2008-02-09 02:18:51 +00003343 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003344 if c == 0:
3345 c = self.compare_total(other)
3346
3347 if c == -1:
3348 ans = self
3349 else:
3350 ans = other
3351
Christian Heimes2c181612007-12-17 20:04:13 +00003352 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003353
3354 def next_minus(self, context=None):
3355 """Returns the largest representable number smaller than itself."""
3356 if context is None:
3357 context = getcontext()
3358
3359 ans = self._check_nans(context=context)
3360 if ans:
3361 return ans
3362
3363 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003364 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003365 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003366 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003367
3368 context = context.copy()
3369 context._set_rounding(ROUND_FLOOR)
3370 context._ignore_all_flags()
3371 new_self = self._fix(context)
3372 if new_self != self:
3373 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003374 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3375 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003376
3377 def next_plus(self, context=None):
3378 """Returns the smallest representable number larger than itself."""
3379 if context is None:
3380 context = getcontext()
3381
3382 ans = self._check_nans(context=context)
3383 if ans:
3384 return ans
3385
3386 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003387 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003388 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003389 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003390
3391 context = context.copy()
3392 context._set_rounding(ROUND_CEILING)
3393 context._ignore_all_flags()
3394 new_self = self._fix(context)
3395 if new_self != self:
3396 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003397 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3398 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003399
3400 def next_toward(self, other, context=None):
3401 """Returns the number closest to self, in the direction towards other.
3402
3403 The result is the closest representable number to self
3404 (excluding self) that is in the direction towards other,
3405 unless both have the same value. If the two operands are
3406 numerically equal, then the result is a copy of self with the
3407 sign set to be the same as the sign of other.
3408 """
3409 other = _convert_other(other, raiseit=True)
3410
3411 if context is None:
3412 context = getcontext()
3413
3414 ans = self._check_nans(other, context)
3415 if ans:
3416 return ans
3417
Christian Heimes77c02eb2008-02-09 02:18:51 +00003418 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003419 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003420 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003421
3422 if comparison == -1:
3423 ans = self.next_plus(context)
3424 else: # comparison == 1
3425 ans = self.next_minus(context)
3426
3427 # decide which flags to raise using value of ans
3428 if ans._isinfinity():
3429 context._raise_error(Overflow,
3430 'Infinite result from next_toward',
3431 ans._sign)
3432 context._raise_error(Rounded)
3433 context._raise_error(Inexact)
3434 elif ans.adjusted() < context.Emin:
3435 context._raise_error(Underflow)
3436 context._raise_error(Subnormal)
3437 context._raise_error(Rounded)
3438 context._raise_error(Inexact)
3439 # if precision == 1 then we don't raise Clamped for a
3440 # result 0E-Etiny.
3441 if not ans:
3442 context._raise_error(Clamped)
3443
3444 return ans
3445
3446 def number_class(self, context=None):
3447 """Returns an indication of the class of self.
3448
3449 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003450 sNaN
3451 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003452 -Infinity
3453 -Normal
3454 -Subnormal
3455 -Zero
3456 +Zero
3457 +Subnormal
3458 +Normal
3459 +Infinity
3460 """
3461 if self.is_snan():
3462 return "sNaN"
3463 if self.is_qnan():
3464 return "NaN"
3465 inf = self._isinfinity()
3466 if inf == 1:
3467 return "+Infinity"
3468 if inf == -1:
3469 return "-Infinity"
3470 if self.is_zero():
3471 if self._sign:
3472 return "-Zero"
3473 else:
3474 return "+Zero"
3475 if context is None:
3476 context = getcontext()
3477 if self.is_subnormal(context=context):
3478 if self._sign:
3479 return "-Subnormal"
3480 else:
3481 return "+Subnormal"
3482 # just a normal, regular, boring number, :)
3483 if self._sign:
3484 return "-Normal"
3485 else:
3486 return "+Normal"
3487
3488 def radix(self):
3489 """Just returns 10, as this is Decimal, :)"""
3490 return Decimal(10)
3491
3492 def rotate(self, other, context=None):
3493 """Returns a rotated copy of self, value-of-other times."""
3494 if context is None:
3495 context = getcontext()
3496
3497 ans = self._check_nans(other, context)
3498 if ans:
3499 return ans
3500
3501 if other._exp != 0:
3502 return context._raise_error(InvalidOperation)
3503 if not (-context.prec <= int(other) <= context.prec):
3504 return context._raise_error(InvalidOperation)
3505
3506 if self._isinfinity():
3507 return Decimal(self)
3508
3509 # get values, pad if necessary
3510 torot = int(other)
3511 rotdig = self._int
3512 topad = context.prec - len(rotdig)
3513 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003514 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003515
3516 # let's rotate!
3517 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003518 return _dec_from_triple(self._sign,
3519 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003520
3521 def scaleb (self, other, context=None):
3522 """Returns self operand after adding the second value to its exp."""
3523 if context is None:
3524 context = getcontext()
3525
3526 ans = self._check_nans(other, context)
3527 if ans:
3528 return ans
3529
3530 if other._exp != 0:
3531 return context._raise_error(InvalidOperation)
3532 liminf = -2 * (context.Emax + context.prec)
3533 limsup = 2 * (context.Emax + context.prec)
3534 if not (liminf <= int(other) <= limsup):
3535 return context._raise_error(InvalidOperation)
3536
3537 if self._isinfinity():
3538 return Decimal(self)
3539
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003540 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003541 d = d._fix(context)
3542 return d
3543
3544 def shift(self, other, context=None):
3545 """Returns a shifted copy of self, value-of-other times."""
3546 if context is None:
3547 context = getcontext()
3548
3549 ans = self._check_nans(other, context)
3550 if ans:
3551 return ans
3552
3553 if other._exp != 0:
3554 return context._raise_error(InvalidOperation)
3555 if not (-context.prec <= int(other) <= context.prec):
3556 return context._raise_error(InvalidOperation)
3557
3558 if self._isinfinity():
3559 return Decimal(self)
3560
3561 # get values, pad if necessary
3562 torot = int(other)
3563 if not torot:
3564 return Decimal(self)
3565 rotdig = self._int
3566 topad = context.prec - len(rotdig)
3567 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003568 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003569
3570 # let's shift!
3571 if torot < 0:
3572 rotated = rotdig[:torot]
3573 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003574 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003575 rotated = rotated[-context.prec:]
3576
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003577 return _dec_from_triple(self._sign,
3578 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003579
Guido van Rossumd8faa362007-04-27 19:54:29 +00003580 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003581 def __reduce__(self):
3582 return (self.__class__, (str(self),))
3583
3584 def __copy__(self):
3585 if type(self) == Decimal:
3586 return self # I'm immutable; therefore I am my own clone
3587 return self.__class__(str(self))
3588
3589 def __deepcopy__(self, memo):
3590 if type(self) == Decimal:
3591 return self # My components are also immutable
3592 return self.__class__(str(self))
3593
Christian Heimesf16baeb2008-02-29 14:57:44 +00003594 # PEP 3101 support. See also _parse_format_specifier and _format_align
3595 def __format__(self, specifier, context=None):
3596 """Format a Decimal instance according to the given specifier.
3597
3598 The specifier should be a standard format specifier, with the
3599 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3600 'F', 'g', 'G', and '%' are supported. If the formatting type
3601 is omitted it defaults to 'g' or 'G', depending on the value
3602 of context.capitals.
3603
3604 At this time the 'n' format specifier type (which is supposed
3605 to use the current locale) is not supported.
3606 """
3607
3608 # Note: PEP 3101 says that if the type is not present then
3609 # there should be at least one digit after the decimal point.
3610 # We take the liberty of ignoring this requirement for
3611 # Decimal---it's presumably there to make sure that
3612 # format(float, '') behaves similarly to str(float).
3613 if context is None:
3614 context = getcontext()
3615
3616 spec = _parse_format_specifier(specifier)
3617
3618 # special values don't care about the type or precision...
3619 if self._is_special:
3620 return _format_align(str(self), spec)
3621
3622 # a type of None defaults to 'g' or 'G', depending on context
3623 # if type is '%', adjust exponent of self accordingly
3624 if spec['type'] is None:
3625 spec['type'] = ['g', 'G'][context.capitals]
3626 elif spec['type'] == '%':
3627 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3628
3629 # round if necessary, taking rounding mode from the context
3630 rounding = context.rounding
3631 precision = spec['precision']
3632 if precision is not None:
3633 if spec['type'] in 'eE':
3634 self = self._round(precision+1, rounding)
3635 elif spec['type'] in 'gG':
3636 if len(self._int) > precision:
3637 self = self._round(precision, rounding)
3638 elif spec['type'] in 'fF%':
3639 self = self._rescale(-precision, rounding)
3640 # special case: zeros with a positive exponent can't be
3641 # represented in fixed point; rescale them to 0e0.
3642 elif not self and self._exp > 0 and spec['type'] in 'fF%':
3643 self = self._rescale(0, rounding)
3644
3645 # figure out placement of the decimal point
3646 leftdigits = self._exp + len(self._int)
3647 if spec['type'] in 'fF%':
3648 dotplace = leftdigits
3649 elif spec['type'] in 'eE':
3650 if not self and precision is not None:
3651 dotplace = 1 - precision
3652 else:
3653 dotplace = 1
3654 elif spec['type'] in 'gG':
3655 if self._exp <= 0 and leftdigits > -6:
3656 dotplace = leftdigits
3657 else:
3658 dotplace = 1
3659
3660 # figure out main part of numeric string...
3661 if dotplace <= 0:
3662 num = '0.' + '0'*(-dotplace) + self._int
3663 elif dotplace >= len(self._int):
3664 # make sure we're not padding a '0' with extra zeros on the right
3665 assert dotplace==len(self._int) or self._int != '0'
3666 num = self._int + '0'*(dotplace-len(self._int))
3667 else:
3668 num = self._int[:dotplace] + '.' + self._int[dotplace:]
3669
3670 # ...then the trailing exponent, or trailing '%'
3671 if leftdigits != dotplace or spec['type'] in 'eE':
3672 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3673 num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3674 elif spec['type'] == '%':
3675 num = num + '%'
3676
3677 # add sign
3678 if self._sign == 1:
3679 num = '-' + num
3680 return _format_align(num, spec)
3681
3682
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003683def _dec_from_triple(sign, coefficient, exponent, special=False):
3684 """Create a decimal instance directly, without any validation,
3685 normalization (e.g. removal of leading zeros) or argument
3686 conversion.
3687
3688 This function is for *internal use only*.
3689 """
3690
3691 self = object.__new__(Decimal)
3692 self._sign = sign
3693 self._int = coefficient
3694 self._exp = exponent
3695 self._is_special = special
3696
3697 return self
3698
Raymond Hettinger82417ca2009-02-03 03:54:28 +00003699# Register Decimal as a kind of Number (an abstract base class).
3700# However, do not register it as Real (because Decimals are not
3701# interoperable with floats).
3702_numbers.Number.register(Decimal)
3703
3704
Guido van Rossumd8faa362007-04-27 19:54:29 +00003705##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003706
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003707
3708# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003709rounding_functions = [name for name in Decimal.__dict__.keys()
3710 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003711for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003712 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003713 globalname = name[1:].upper()
3714 val = globals()[globalname]
3715 Decimal._pick_rounding_function[val] = name
3716
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003717del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003718
Thomas Wouters89f507f2006-12-13 04:49:30 +00003719class _ContextManager(object):
3720 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003721
Thomas Wouters89f507f2006-12-13 04:49:30 +00003722 Sets a copy of the supplied context in __enter__() and restores
3723 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003724 """
3725 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003726 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003727 def __enter__(self):
3728 self.saved_context = getcontext()
3729 setcontext(self.new_context)
3730 return self.new_context
3731 def __exit__(self, t, v, tb):
3732 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003733
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003734class Context(object):
3735 """Contains the context for a Decimal instance.
3736
3737 Contains:
3738 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003739 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003740 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003741 raised when it is caused. Otherwise, a value is
3742 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003743 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003744 (Whether or not the trap_enabler is set)
3745 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003746 Emin - Minimum exponent
3747 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003748 capitals - If 1, 1*10^1 is printed as 1E+1.
3749 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003750 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003751 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003752
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003753 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003754 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003755 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003756 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003757 _ignored_flags=None):
3758 if flags is None:
3759 flags = []
3760 if _ignored_flags is None:
3761 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003762 if not isinstance(flags, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003763 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003764 if traps is not None and not isinstance(traps, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003765 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003766 for name, val in locals().items():
3767 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003768 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003769 else:
3770 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003771 del self.self
3772
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003773 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003774 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003775 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003776 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3777 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3778 % vars(self))
3779 names = [f.__name__ for f, v in self.flags.items() if v]
3780 s.append('flags=[' + ', '.join(names) + ']')
3781 names = [t.__name__ for t, v in self.traps.items() if v]
3782 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003783 return ', '.join(s) + ')'
3784
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003785 def clear_flags(self):
3786 """Reset all flags to zero"""
3787 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003788 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003789
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003790 def _shallow_copy(self):
3791 """Returns a shallow copy from self."""
Christian Heimes2c181612007-12-17 20:04:13 +00003792 nc = Context(self.prec, self.rounding, self.traps,
3793 self.flags, self.Emin, self.Emax,
3794 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003795 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003796
3797 def copy(self):
3798 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003799 nc = Context(self.prec, self.rounding, self.traps.copy(),
Christian Heimes2c181612007-12-17 20:04:13 +00003800 self.flags.copy(), self.Emin, self.Emax,
3801 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003802 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003803 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003804
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003805 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003806 """Handles an error
3807
3808 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003809 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003810 trap_enabler is set, it reaises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00003811 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003812 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003813 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003814 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003815 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003816 return error().handle(self, *args)
3817
Raymond Hettinger86173da2008-02-01 20:38:12 +00003818 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003819 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003820 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003821 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003822
3823 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003824 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003825 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003826
3827 def _ignore_all_flags(self):
3828 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003829 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003830
3831 def _ignore_flags(self, *flags):
3832 """Ignore the flags, if they are raised"""
3833 # Do not mutate-- This way, copies of a context leave the original
3834 # alone.
3835 self._ignored_flags = (self._ignored_flags + list(flags))
3836 return list(flags)
3837
3838 def _regard_flags(self, *flags):
3839 """Stop ignoring the flags, if they are raised"""
3840 if flags and isinstance(flags[0], (tuple,list)):
3841 flags = flags[0]
3842 for flag in flags:
3843 self._ignored_flags.remove(flag)
3844
Nick Coghland1abd252008-07-15 15:46:38 +00003845 # We inherit object.__hash__, so we must deny this explicitly
3846 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003847
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003848 def Etiny(self):
3849 """Returns Etiny (= Emin - prec + 1)"""
3850 return int(self.Emin - self.prec + 1)
3851
3852 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003853 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003854 return int(self.Emax - self.prec + 1)
3855
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003856 def _set_rounding(self, type):
3857 """Sets the rounding type.
3858
3859 Sets the rounding type, and returns the current (previous)
3860 rounding type. Often used like:
3861
3862 context = context.copy()
3863 # so you don't change the calling context
3864 # if an error occurs in the middle.
3865 rounding = context._set_rounding(ROUND_UP)
3866 val = self.__sub__(other, context=context)
3867 context._set_rounding(rounding)
3868
3869 This will make it round up for that operation.
3870 """
3871 rounding = self.rounding
3872 self.rounding= type
3873 return rounding
3874
Raymond Hettingerfed52962004-07-14 15:41:57 +00003875 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00003876 """Creates a new Decimal instance but using self as context.
3877
3878 This method implements the to-number operation of the
3879 IBM Decimal specification."""
3880
3881 if isinstance(num, str) and num != num.strip():
3882 return self._raise_error(ConversionSyntax,
3883 "no trailing or leading whitespace is "
3884 "permitted.")
3885
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003886 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003887 if d._isnan() and len(d._int) > self.prec - self._clamp:
3888 return self._raise_error(ConversionSyntax,
3889 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003890 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003891
Raymond Hettinger771ed762009-01-03 19:20:32 +00003892 def create_decimal_from_float(self, f):
3893 """Creates a new Decimal instance from a float but rounding using self
3894 as the context.
3895
3896 >>> context = Context(prec=5, rounding=ROUND_DOWN)
3897 >>> context.create_decimal_from_float(3.1415926535897932)
3898 Decimal('3.1415')
3899 >>> context = Context(prec=5, traps=[Inexact])
3900 >>> context.create_decimal_from_float(3.1415926535897932)
3901 Traceback (most recent call last):
3902 ...
3903 decimal.Inexact: None
3904
3905 """
3906 d = Decimal.from_float(f) # An exact conversion
3907 return d._fix(self) # Apply the context rounding
3908
Guido van Rossumd8faa362007-04-27 19:54:29 +00003909 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003910 def abs(self, a):
3911 """Returns the absolute value of the operand.
3912
3913 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003914 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003915 the plus operation on the operand.
3916
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003917 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003918 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003919 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003920 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003921 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003922 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003923 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003924 Decimal('101.5')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003925 """
3926 return a.__abs__(context=self)
3927
3928 def add(self, a, b):
3929 """Return the sum of the two operands.
3930
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003931 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003932 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003933 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003934 Decimal('1.02E+4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003935 """
3936 return a.__add__(b, context=self)
3937
3938 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003939 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003940
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003941 def canonical(self, a):
3942 """Returns the same Decimal object.
3943
3944 As we do not have different encodings for the same number, the
3945 received object already is in its canonical form.
3946
3947 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003948 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003949 """
3950 return a.canonical(context=self)
3951
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003952 def compare(self, a, b):
3953 """Compares values numerically.
3954
3955 If the signs of the operands differ, a value representing each operand
3956 ('-1' if the operand is less than zero, '0' if the operand is zero or
3957 negative zero, or '1' if the operand is greater than zero) is used in
3958 place of that operand for the comparison instead of the actual
3959 operand.
3960
3961 The comparison is then effected by subtracting the second operand from
3962 the first and then returning a value according to the result of the
3963 subtraction: '-1' if the result is less than zero, '0' if the result is
3964 zero or negative zero, or '1' if the result is greater than zero.
3965
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003966 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003967 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003968 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003969 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003970 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003971 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003972 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003973 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003974 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003975 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003976 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003977 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003978 """
3979 return a.compare(b, context=self)
3980
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003981 def compare_signal(self, a, b):
3982 """Compares the values of the two operands numerically.
3983
3984 It's pretty much like compare(), but all NaNs signal, with signaling
3985 NaNs taking precedence over quiet NaNs.
3986
3987 >>> c = ExtendedContext
3988 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003989 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003990 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003991 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003992 >>> c.flags[InvalidOperation] = 0
3993 >>> print(c.flags[InvalidOperation])
3994 0
3995 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003996 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003997 >>> print(c.flags[InvalidOperation])
3998 1
3999 >>> c.flags[InvalidOperation] = 0
4000 >>> print(c.flags[InvalidOperation])
4001 0
4002 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004003 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004004 >>> print(c.flags[InvalidOperation])
4005 1
4006 """
4007 return a.compare_signal(b, context=self)
4008
4009 def compare_total(self, a, b):
4010 """Compares two operands using their abstract representation.
4011
4012 This is not like the standard compare, which use their numerical
4013 value. Note that a total ordering is defined for all possible abstract
4014 representations.
4015
4016 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004017 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004018 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004019 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004020 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004021 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004022 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004023 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004024 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004025 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004026 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004027 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004028 """
4029 return a.compare_total(b)
4030
4031 def compare_total_mag(self, a, b):
4032 """Compares two operands using their abstract representation ignoring sign.
4033
4034 Like compare_total, but with operand's sign ignored and assumed to be 0.
4035 """
4036 return a.compare_total_mag(b)
4037
4038 def copy_abs(self, a):
4039 """Returns a copy of the operand with the sign set to 0.
4040
4041 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004042 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004043 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004044 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004045 """
4046 return a.copy_abs()
4047
4048 def copy_decimal(self, a):
4049 """Returns a copy of the decimal objet.
4050
4051 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004052 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004053 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004054 Decimal('-1.00')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004055 """
4056 return Decimal(a)
4057
4058 def copy_negate(self, a):
4059 """Returns a copy of the operand with the sign inverted.
4060
4061 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004062 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004063 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004064 Decimal('101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004065 """
4066 return a.copy_negate()
4067
4068 def copy_sign(self, a, b):
4069 """Copies the second operand's sign to the first one.
4070
4071 In detail, it returns a copy of the first operand with the sign
4072 equal to the sign of the second operand.
4073
4074 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004075 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004076 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004077 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004078 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004079 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004080 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004081 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004082 """
4083 return a.copy_sign(b)
4084
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004085 def divide(self, a, b):
4086 """Decimal division in a specified context.
4087
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004088 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004089 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004090 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004091 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004092 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004093 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004094 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004095 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004096 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004097 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004098 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004099 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004100 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004101 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004102 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004103 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004104 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004105 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004106 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004107 Decimal('1.20E+6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004108 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00004109 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004110
4111 def divide_int(self, a, b):
4112 """Divides two numbers and returns the integer part of the result.
4113
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004114 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004115 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004116 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004117 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004118 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004119 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004120 """
4121 return a.__floordiv__(b, context=self)
4122
4123 def divmod(self, a, b):
4124 return a.__divmod__(b, context=self)
4125
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004126 def exp(self, a):
4127 """Returns e ** a.
4128
4129 >>> c = ExtendedContext.copy()
4130 >>> c.Emin = -999
4131 >>> c.Emax = 999
4132 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004133 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004134 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004135 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004136 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004137 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004138 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004139 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004140 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004141 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004142 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004143 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004144 """
4145 return a.exp(context=self)
4146
4147 def fma(self, a, b, c):
4148 """Returns a multiplied by b, plus c.
4149
4150 The first two operands are multiplied together, using multiply,
4151 the third operand is then added to the result of that
4152 multiplication, using add, all with only one final rounding.
4153
4154 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004155 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004156 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004157 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004158 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004159 Decimal('1.38435736E+12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004160 """
4161 return a.fma(b, c, context=self)
4162
4163 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004164 """Return True if the operand is canonical; otherwise return False.
4165
4166 Currently, the encoding of a Decimal instance is always
4167 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004168
4169 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004170 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004171 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004172 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004173
4174 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004175 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004176
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004177 A Decimal instance is considered finite if it is neither
4178 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004179
4180 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004181 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004182 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004183 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004184 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004185 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004186 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004187 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004188 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004189 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004190 """
4191 return a.is_finite()
4192
4193 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004194 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004195
4196 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004197 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004198 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004199 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004200 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004201 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004202 """
4203 return a.is_infinite()
4204
4205 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004206 """Return True if the operand is a qNaN or sNaN;
4207 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004208
4209 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004210 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004211 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004212 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004213 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004214 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004215 """
4216 return a.is_nan()
4217
4218 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004219 """Return True if the operand is a normal number;
4220 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004221
4222 >>> c = ExtendedContext.copy()
4223 >>> c.Emin = -999
4224 >>> c.Emax = 999
4225 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004226 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004227 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004228 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004229 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004230 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004231 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004232 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004233 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004234 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004235 """
4236 return a.is_normal(context=self)
4237
4238 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004239 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004240
4241 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004242 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004243 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004244 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004245 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004246 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004247 """
4248 return a.is_qnan()
4249
4250 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004251 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004252
4253 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004254 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004255 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004256 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004257 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004258 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004259 """
4260 return a.is_signed()
4261
4262 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004263 """Return True if the operand is a signaling NaN;
4264 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004265
4266 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004267 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004268 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004269 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004270 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004271 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004272 """
4273 return a.is_snan()
4274
4275 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004276 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004277
4278 >>> c = ExtendedContext.copy()
4279 >>> c.Emin = -999
4280 >>> c.Emax = 999
4281 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004282 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004283 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004284 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004285 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004286 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004287 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004288 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004289 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004290 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004291 """
4292 return a.is_subnormal(context=self)
4293
4294 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004295 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004296
4297 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004298 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004299 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004300 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004301 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004302 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004303 """
4304 return a.is_zero()
4305
4306 def ln(self, a):
4307 """Returns the natural (base e) logarithm of the operand.
4308
4309 >>> c = ExtendedContext.copy()
4310 >>> c.Emin = -999
4311 >>> c.Emax = 999
4312 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004313 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004314 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004315 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004316 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004317 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004318 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004319 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004320 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004321 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004322 """
4323 return a.ln(context=self)
4324
4325 def log10(self, a):
4326 """Returns the base 10 logarithm of the operand.
4327
4328 >>> c = ExtendedContext.copy()
4329 >>> c.Emin = -999
4330 >>> c.Emax = 999
4331 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004332 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004333 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004334 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004335 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004336 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004337 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004338 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004339 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004340 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004341 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004342 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004343 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004344 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004345 """
4346 return a.log10(context=self)
4347
4348 def logb(self, a):
4349 """ Returns the exponent of the magnitude of the operand's MSD.
4350
4351 The result is the integer which is the exponent of the magnitude
4352 of the most significant digit of the operand (as though the
4353 operand were truncated to a single digit while maintaining the
4354 value of that digit and without limiting the resulting exponent).
4355
4356 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004357 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004358 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004359 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004360 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004361 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004362 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004363 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004364 """
4365 return a.logb(context=self)
4366
4367 def logical_and(self, a, b):
4368 """Applies the logical operation 'and' between each operand's digits.
4369
4370 The operands must be both logical numbers.
4371
4372 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004373 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004374 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004375 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004376 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004377 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004378 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004379 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004380 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004381 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004382 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004383 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004384 """
4385 return a.logical_and(b, context=self)
4386
4387 def logical_invert(self, a):
4388 """Invert all the digits in the operand.
4389
4390 The operand must be a logical number.
4391
4392 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004393 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004394 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004395 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004396 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004397 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004398 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004399 Decimal('10101010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004400 """
4401 return a.logical_invert(context=self)
4402
4403 def logical_or(self, a, b):
4404 """Applies the logical operation 'or' between each operand's digits.
4405
4406 The operands must be both logical numbers.
4407
4408 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004409 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004410 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004411 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004412 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004413 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004414 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004415 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004416 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004417 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004418 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004419 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004420 """
4421 return a.logical_or(b, context=self)
4422
4423 def logical_xor(self, a, b):
4424 """Applies the logical operation 'xor' between each operand's digits.
4425
4426 The operands must be both logical numbers.
4427
4428 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004429 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004430 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004431 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004432 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004433 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004434 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004435 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004436 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004437 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004438 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004439 Decimal('1101')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004440 """
4441 return a.logical_xor(b, context=self)
4442
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004443 def max(self, a,b):
4444 """max compares two values numerically and returns the maximum.
4445
4446 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004447 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004448 operation. If they are numerically equal then the left-hand operand
4449 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004450 infinity) of the two operands is chosen as the result.
4451
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004452 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004453 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004454 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004455 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004456 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004457 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004458 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004459 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004460 """
4461 return a.max(b, context=self)
4462
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004463 def max_mag(self, a, b):
4464 """Compares the values numerically with their sign ignored."""
4465 return a.max_mag(b, context=self)
4466
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004467 def min(self, a,b):
4468 """min compares two values numerically and returns the minimum.
4469
4470 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004471 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004472 operation. If they are numerically equal then the left-hand operand
4473 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004474 infinity) of the two operands is chosen as the result.
4475
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004476 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004477 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004478 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004479 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004480 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004481 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004482 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004483 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004484 """
4485 return a.min(b, context=self)
4486
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004487 def min_mag(self, a, b):
4488 """Compares the values numerically with their sign ignored."""
4489 return a.min_mag(b, context=self)
4490
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004491 def minus(self, a):
4492 """Minus corresponds to unary prefix minus in Python.
4493
4494 The operation is evaluated using the same rules as subtract; the
4495 operation minus(a) is calculated as subtract('0', a) where the '0'
4496 has the same exponent as the operand.
4497
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004498 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004499 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004500 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004501 Decimal('1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004502 """
4503 return a.__neg__(context=self)
4504
4505 def multiply(self, a, b):
4506 """multiply multiplies two operands.
4507
4508 If either operand is a special value then the general rules apply.
4509 Otherwise, the operands are multiplied together ('long multiplication'),
4510 resulting in a number which may be as long as the sum of the lengths
4511 of the two operands.
4512
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004513 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004514 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004515 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004516 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004517 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004518 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004519 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004520 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004521 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004522 Decimal('4.28135971E+11')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004523 """
4524 return a.__mul__(b, context=self)
4525
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004526 def next_minus(self, a):
4527 """Returns the largest representable number smaller than a.
4528
4529 >>> c = ExtendedContext.copy()
4530 >>> c.Emin = -999
4531 >>> c.Emax = 999
4532 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004533 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004534 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004535 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004536 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004537 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004538 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004539 Decimal('9.99999999E+999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004540 """
4541 return a.next_minus(context=self)
4542
4543 def next_plus(self, a):
4544 """Returns the smallest representable number larger than a.
4545
4546 >>> c = ExtendedContext.copy()
4547 >>> c.Emin = -999
4548 >>> c.Emax = 999
4549 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004550 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004551 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004552 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004553 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004554 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004555 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004556 Decimal('-9.99999999E+999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004557 """
4558 return a.next_plus(context=self)
4559
4560 def next_toward(self, a, b):
4561 """Returns the number closest to a, in direction towards b.
4562
4563 The result is the closest representable number from the first
4564 operand (but not the first operand) that is in the direction
4565 towards the second operand, unless the operands have the same
4566 value.
4567
4568 >>> c = ExtendedContext.copy()
4569 >>> c.Emin = -999
4570 >>> c.Emax = 999
4571 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004572 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004573 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004574 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004575 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004576 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004577 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004578 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004579 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004580 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004581 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004582 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004583 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004584 Decimal('-0.00')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004585 """
4586 return a.next_toward(b, context=self)
4587
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004588 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004589 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004590
4591 Essentially a plus operation with all trailing zeros removed from the
4592 result.
4593
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004594 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004595 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004596 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004597 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004598 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004599 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004600 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004601 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004602 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004603 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004604 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004605 Decimal('0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004606 """
4607 return a.normalize(context=self)
4608
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004609 def number_class(self, a):
4610 """Returns an indication of the class of the operand.
4611
4612 The class is one of the following strings:
4613 -sNaN
4614 -NaN
4615 -Infinity
4616 -Normal
4617 -Subnormal
4618 -Zero
4619 +Zero
4620 +Subnormal
4621 +Normal
4622 +Infinity
4623
4624 >>> c = Context(ExtendedContext)
4625 >>> c.Emin = -999
4626 >>> c.Emax = 999
4627 >>> c.number_class(Decimal('Infinity'))
4628 '+Infinity'
4629 >>> c.number_class(Decimal('1E-10'))
4630 '+Normal'
4631 >>> c.number_class(Decimal('2.50'))
4632 '+Normal'
4633 >>> c.number_class(Decimal('0.1E-999'))
4634 '+Subnormal'
4635 >>> c.number_class(Decimal('0'))
4636 '+Zero'
4637 >>> c.number_class(Decimal('-0'))
4638 '-Zero'
4639 >>> c.number_class(Decimal('-0.1E-999'))
4640 '-Subnormal'
4641 >>> c.number_class(Decimal('-1E-10'))
4642 '-Normal'
4643 >>> c.number_class(Decimal('-2.50'))
4644 '-Normal'
4645 >>> c.number_class(Decimal('-Infinity'))
4646 '-Infinity'
4647 >>> c.number_class(Decimal('NaN'))
4648 'NaN'
4649 >>> c.number_class(Decimal('-NaN'))
4650 'NaN'
4651 >>> c.number_class(Decimal('sNaN'))
4652 'sNaN'
4653 """
4654 return a.number_class(context=self)
4655
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004656 def plus(self, a):
4657 """Plus corresponds to unary prefix plus in Python.
4658
4659 The operation is evaluated using the same rules as add; the
4660 operation plus(a) is calculated as add('0', a) where the '0'
4661 has the same exponent as the operand.
4662
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004663 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004664 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004665 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004666 Decimal('-1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004667 """
4668 return a.__pos__(context=self)
4669
4670 def power(self, a, b, modulo=None):
4671 """Raises a to the power of b, to modulo if given.
4672
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004673 With two arguments, compute a**b. If a is negative then b
4674 must be integral. The result will be inexact unless b is
4675 integral and the result is finite and can be expressed exactly
4676 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004677
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004678 With three arguments, compute (a**b) % modulo. For the
4679 three argument form, the following restrictions on the
4680 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004681
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004682 - all three arguments must be integral
4683 - b must be nonnegative
4684 - at least one of a or b must be nonzero
4685 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004686
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004687 The result of pow(a, b, modulo) is identical to the result
4688 that would be obtained by computing (a**b) % modulo with
4689 unbounded precision, but is computed more efficiently. It is
4690 always exact.
4691
4692 >>> c = ExtendedContext.copy()
4693 >>> c.Emin = -999
4694 >>> c.Emax = 999
4695 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004696 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004697 >>> c.power(Decimal('-2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004698 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004699 >>> c.power(Decimal('2'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004700 Decimal('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004701 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004702 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004703 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004704 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004705 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004706 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004707 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004708 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004709 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004710 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004711 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004712 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004713 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004714 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004715 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004716 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004717 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004718 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004719 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004720 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004721
4722 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004723 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004724 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004725 Decimal('-11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004726 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004727 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004728 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004729 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004730 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004731 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004732 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004733 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004734 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004735 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004736 """
4737 return a.__pow__(b, modulo, context=self)
4738
4739 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004740 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004741
4742 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004743 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004744 exponent is being increased), multiplied by a positive power of ten (if
4745 the exponent is being decreased), or is unchanged (if the exponent is
4746 already equal to that of the right-hand operand).
4747
4748 Unlike other operations, if the length of the coefficient after the
4749 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004750 operation condition is raised. This guarantees that, unless there is
4751 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004752 equal to that of the right-hand operand.
4753
4754 Also unlike other operations, quantize will never raise Underflow, even
4755 if the result is subnormal and inexact.
4756
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004757 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004758 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004759 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004760 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004761 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004762 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004763 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004764 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004765 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004766 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004767 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004768 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004769 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004770 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004771 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004772 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004773 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004774 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004775 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004776 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004777 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004778 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004779 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004780 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004781 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004782 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004783 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004784 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004785 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004786 Decimal('2E+2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004787 """
4788 return a.quantize(b, context=self)
4789
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004790 def radix(self):
4791 """Just returns 10, as this is Decimal, :)
4792
4793 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004794 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004795 """
4796 return Decimal(10)
4797
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004798 def remainder(self, a, b):
4799 """Returns the remainder from integer division.
4800
4801 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004802 calculating integer division as described for divide-integer, rounded
4803 to precision digits if necessary. The sign of the result, if
4804 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004805
4806 This operation will fail under the same conditions as integer division
4807 (that is, if integer division on the same two operands would fail, the
4808 remainder cannot be calculated).
4809
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004810 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004811 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004812 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004813 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004814 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004815 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004816 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004817 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004818 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004819 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004820 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004821 Decimal('1.0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004822 """
4823 return a.__mod__(b, context=self)
4824
4825 def remainder_near(self, a, b):
4826 """Returns to be "a - b * n", where n is the integer nearest the exact
4827 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004828 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004829 sign of a.
4830
4831 This operation will fail under the same conditions as integer division
4832 (that is, if integer division on the same two operands would fail, the
4833 remainder cannot be calculated).
4834
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004835 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004836 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004837 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004838 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004839 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004840 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004841 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004842 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004843 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004844 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004845 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004846 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004847 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004848 Decimal('-0.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004849 """
4850 return a.remainder_near(b, context=self)
4851
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004852 def rotate(self, a, b):
4853 """Returns a rotated copy of a, b times.
4854
4855 The coefficient of the result is a rotated copy of the digits in
4856 the coefficient of the first operand. The number of places of
4857 rotation is taken from the absolute value of the second operand,
4858 with the rotation being to the left if the second operand is
4859 positive or to the right otherwise.
4860
4861 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004862 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004863 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004864 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004865 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004866 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004867 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004868 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004869 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004870 Decimal('345678912')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004871 """
4872 return a.rotate(b, context=self)
4873
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004874 def same_quantum(self, a, b):
4875 """Returns True if the two operands have the same exponent.
4876
4877 The result is never affected by either the sign or the coefficient of
4878 either operand.
4879
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004880 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004881 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004882 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004883 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004884 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004885 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004886 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004887 True
4888 """
4889 return a.same_quantum(b)
4890
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004891 def scaleb (self, a, b):
4892 """Returns the first operand after adding the second value its exp.
4893
4894 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004895 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004896 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004897 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004898 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004899 Decimal('7.50E+3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004900 """
4901 return a.scaleb (b, context=self)
4902
4903 def shift(self, a, b):
4904 """Returns a shifted copy of a, b times.
4905
4906 The coefficient of the result is a shifted copy of the digits
4907 in the coefficient of the first operand. The number of places
4908 to shift is taken from the absolute value of the second operand,
4909 with the shift being to the left if the second operand is
4910 positive or to the right otherwise. Digits shifted into the
4911 coefficient are zeros.
4912
4913 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004914 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004915 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004916 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004917 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004918 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004919 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004920 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004921 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004922 Decimal('345678900')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004923 """
4924 return a.shift(b, context=self)
4925
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004926 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004927 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004928
4929 If the result must be inexact, it is rounded using the round-half-even
4930 algorithm.
4931
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004932 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004933 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004934 >>> ExtendedContext.sqrt(Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004935 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004936 >>> ExtendedContext.sqrt(Decimal('0.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004937 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004938 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004939 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004940 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004941 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004942 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004943 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004944 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004945 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004946 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004947 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004948 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004949 Decimal('3.16227766')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004950 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004951 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004952 """
4953 return a.sqrt(context=self)
4954
4955 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004956 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004957
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004958 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004959 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004960 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004961 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004962 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004963 Decimal('-0.77')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004964 """
4965 return a.__sub__(b, context=self)
4966
4967 def to_eng_string(self, a):
4968 """Converts a number to a string, using scientific notation.
4969
4970 The operation is not affected by the context.
4971 """
4972 return a.to_eng_string(context=self)
4973
4974 def to_sci_string(self, a):
4975 """Converts a number to a string, using scientific notation.
4976
4977 The operation is not affected by the context.
4978 """
4979 return a.__str__(context=self)
4980
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004981 def to_integral_exact(self, a):
4982 """Rounds to an integer.
4983
4984 When the operand has a negative exponent, the result is the same
4985 as using the quantize() operation using the given operand as the
4986 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4987 of the operand as the precision setting; Inexact and Rounded flags
4988 are allowed in this operation. The rounding mode is taken from the
4989 context.
4990
4991 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004992 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004993 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004994 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004995 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004996 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004997 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004998 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004999 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005000 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005001 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005002 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005003 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005004 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005005 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005006 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005007 """
5008 return a.to_integral_exact(context=self)
5009
5010 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005011 """Rounds to an integer.
5012
5013 When the operand has a negative exponent, the result is the same
5014 as using the quantize() operation using the given operand as the
5015 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5016 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00005017 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005018
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005019 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005020 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005021 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005022 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005023 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005024 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005025 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005026 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005027 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005028 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005029 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005030 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005031 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005032 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005033 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005034 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005035 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005036 return a.to_integral_value(context=self)
5037
5038 # the method name changed, but we provide also the old one, for compatibility
5039 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005040
5041class _WorkRep(object):
5042 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005043 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005044 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005045 # exp: None, int, or string
5046
5047 def __init__(self, value=None):
5048 if value is None:
5049 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005050 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005051 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005052 elif isinstance(value, Decimal):
5053 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005054 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005055 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005056 else:
5057 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005058 self.sign = value[0]
5059 self.int = value[1]
5060 self.exp = value[2]
5061
5062 def __repr__(self):
5063 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5064
5065 __str__ = __repr__
5066
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005067
5068
Christian Heimes2c181612007-12-17 20:04:13 +00005069def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005070 """Normalizes op1, op2 to have the same exp and length of coefficient.
5071
5072 Done during addition.
5073 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005074 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005075 tmp = op2
5076 other = op1
5077 else:
5078 tmp = op1
5079 other = op2
5080
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005081 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5082 # Then adding 10**exp to tmp has the same effect (after rounding)
5083 # as adding any positive quantity smaller than 10**exp; similarly
5084 # for subtraction. So if other is smaller than 10**exp we replace
5085 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00005086 tmp_len = len(str(tmp.int))
5087 other_len = len(str(other.int))
5088 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5089 if other_len + other.exp - 1 < exp:
5090 other.int = 1
5091 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005092
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005093 tmp.int *= 10 ** (tmp.exp - other.exp)
5094 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005095 return op1, op2
5096
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005097##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005098
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005099# This function from Tim Peters was taken from here:
5100# http://mail.python.org/pipermail/python-list/1999-July/007758.html
5101# The correction being in the function definition is for speed, and
5102# the whole function is not resolved with math.log because of avoiding
5103# the use of floats.
5104def _nbits(n, correction = {
5105 '0': 4, '1': 3, '2': 2, '3': 2,
5106 '4': 1, '5': 1, '6': 1, '7': 1,
5107 '8': 0, '9': 0, 'a': 0, 'b': 0,
5108 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
5109 """Number of bits in binary representation of the positive integer n,
5110 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005111 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005112 if n < 0:
5113 raise ValueError("The argument to _nbits should be nonnegative.")
5114 hex_n = "%x" % n
5115 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005116
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005117def _sqrt_nearest(n, a):
5118 """Closest integer to the square root of the positive integer n. a is
5119 an initial approximation to the square root. Any positive integer
5120 will do for a, but the closer a is to the square root of n the
5121 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005122
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005123 """
5124 if n <= 0 or a <= 0:
5125 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5126
5127 b=0
5128 while a != b:
5129 b, a = a, a--n//a>>1
5130 return a
5131
5132def _rshift_nearest(x, shift):
5133 """Given an integer x and a nonnegative integer shift, return closest
5134 integer to x / 2**shift; use round-to-even in case of a tie.
5135
5136 """
5137 b, q = 1 << shift, x >> shift
5138 return q + (2*(x & (b-1)) + (q&1) > b)
5139
5140def _div_nearest(a, b):
5141 """Closest integer to a/b, a and b positive integers; rounds to even
5142 in the case of a tie.
5143
5144 """
5145 q, r = divmod(a, b)
5146 return q + (2*r + (q&1) > b)
5147
5148def _ilog(x, M, L = 8):
5149 """Integer approximation to M*log(x/M), with absolute error boundable
5150 in terms only of x/M.
5151
5152 Given positive integers x and M, return an integer approximation to
5153 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5154 between the approximation and the exact result is at most 22. For
5155 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5156 both cases these are upper bounds on the error; it will usually be
5157 much smaller."""
5158
5159 # The basic algorithm is the following: let log1p be the function
5160 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5161 # the reduction
5162 #
5163 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5164 #
5165 # repeatedly until the argument to log1p is small (< 2**-L in
5166 # absolute value). For small y we can use the Taylor series
5167 # expansion
5168 #
5169 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5170 #
5171 # truncating at T such that y**T is small enough. The whole
5172 # computation is carried out in a form of fixed-point arithmetic,
5173 # with a real number z being represented by an integer
5174 # approximation to z*M. To avoid loss of precision, the y below
5175 # is actually an integer approximation to 2**R*y*M, where R is the
5176 # number of reductions performed so far.
5177
5178 y = x-M
5179 # argument reduction; R = number of reductions performed
5180 R = 0
5181 while (R <= L and abs(y) << L-R >= M or
5182 R > L and abs(y) >> R-L >= M):
5183 y = _div_nearest((M*y) << 1,
5184 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5185 R += 1
5186
5187 # Taylor series with T terms
5188 T = -int(-10*len(str(M))//(3*L))
5189 yshift = _rshift_nearest(y, R)
5190 w = _div_nearest(M, T)
5191 for k in range(T-1, 0, -1):
5192 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5193
5194 return _div_nearest(w*y, M)
5195
5196def _dlog10(c, e, p):
5197 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5198 approximation to 10**p * log10(c*10**e), with an absolute error of
5199 at most 1. Assumes that c*10**e is not exactly 1."""
5200
5201 # increase precision by 2; compensate for this by dividing
5202 # final result by 100
5203 p += 2
5204
5205 # write c*10**e as d*10**f with either:
5206 # f >= 0 and 1 <= d <= 10, or
5207 # f <= 0 and 0.1 <= d <= 1.
5208 # Thus for c*10**e close to 1, f = 0
5209 l = len(str(c))
5210 f = e+l - (e+l >= 1)
5211
5212 if p > 0:
5213 M = 10**p
5214 k = e+p-f
5215 if k >= 0:
5216 c *= 10**k
5217 else:
5218 c = _div_nearest(c, 10**-k)
5219
5220 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005221 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005222 log_d = _div_nearest(log_d*M, log_10)
5223 log_tenpower = f*M # exact
5224 else:
5225 log_d = 0 # error < 2.31
Neal Norwitz2f99b242008-08-24 05:48:10 +00005226 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005227
5228 return _div_nearest(log_tenpower+log_d, 100)
5229
5230def _dlog(c, e, p):
5231 """Given integers c, e and p with c > 0, compute an integer
5232 approximation to 10**p * log(c*10**e), with an absolute error of
5233 at most 1. Assumes that c*10**e is not exactly 1."""
5234
5235 # Increase precision by 2. The precision increase is compensated
5236 # for at the end with a division by 100.
5237 p += 2
5238
5239 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5240 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5241 # as 10**p * log(d) + 10**p*f * log(10).
5242 l = len(str(c))
5243 f = e+l - (e+l >= 1)
5244
5245 # compute approximation to 10**p*log(d), with error < 27
5246 if p > 0:
5247 k = e+p-f
5248 if k >= 0:
5249 c *= 10**k
5250 else:
5251 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5252
5253 # _ilog magnifies existing error in c by a factor of at most 10
5254 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5255 else:
5256 # p <= 0: just approximate the whole thing by 0; error < 2.31
5257 log_d = 0
5258
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005259 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005260 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005261 extra = len(str(abs(f)))-1
5262 if p + extra >= 0:
5263 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5264 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5265 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005266 else:
5267 f_log_ten = 0
5268 else:
5269 f_log_ten = 0
5270
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005271 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005272 return _div_nearest(f_log_ten + log_d, 100)
5273
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005274class _Log10Memoize(object):
5275 """Class to compute, store, and allow retrieval of, digits of the
5276 constant log(10) = 2.302585.... This constant is needed by
5277 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5278 def __init__(self):
5279 self.digits = "23025850929940456840179914546843642076011014886"
5280
5281 def getdigits(self, p):
5282 """Given an integer p >= 0, return floor(10**p)*log(10).
5283
5284 For example, self.getdigits(3) returns 2302.
5285 """
5286 # digits are stored as a string, for quick conversion to
5287 # integer in the case that we've already computed enough
5288 # digits; the stored digits should always be correct
5289 # (truncated, not rounded to nearest).
5290 if p < 0:
5291 raise ValueError("p should be nonnegative")
5292
5293 if p >= len(self.digits):
5294 # compute p+3, p+6, p+9, ... digits; continue until at
5295 # least one of the extra digits is nonzero
5296 extra = 3
5297 while True:
5298 # compute p+extra digits, correct to within 1ulp
5299 M = 10**(p+extra+2)
5300 digits = str(_div_nearest(_ilog(10*M, M), 100))
5301 if digits[-extra:] != '0'*extra:
5302 break
5303 extra += 3
5304 # keep all reliable digits so far; remove trailing zeros
5305 # and next nonzero digit
5306 self.digits = digits.rstrip('0')[:-1]
5307 return int(self.digits[:p+1])
5308
5309_log10_digits = _Log10Memoize().getdigits
5310
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005311def _iexp(x, M, L=8):
5312 """Given integers x and M, M > 0, such that x/M is small in absolute
5313 value, compute an integer approximation to M*exp(x/M). For 0 <=
5314 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5315 is usually much smaller)."""
5316
5317 # Algorithm: to compute exp(z) for a real number z, first divide z
5318 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5319 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5320 # series
5321 #
5322 # expm1(x) = x + x**2/2! + x**3/3! + ...
5323 #
5324 # Now use the identity
5325 #
5326 # expm1(2x) = expm1(x)*(expm1(x)+2)
5327 #
5328 # R times to compute the sequence expm1(z/2**R),
5329 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5330
5331 # Find R such that x/2**R/M <= 2**-L
5332 R = _nbits((x<<L)//M)
5333
5334 # Taylor series. (2**L)**T > M
5335 T = -int(-10*len(str(M))//(3*L))
5336 y = _div_nearest(x, T)
5337 Mshift = M<<R
5338 for i in range(T-1, 0, -1):
5339 y = _div_nearest(x*(Mshift + y), Mshift * i)
5340
5341 # Expansion
5342 for k in range(R-1, -1, -1):
5343 Mshift = M<<(k+2)
5344 y = _div_nearest(y*(y+Mshift), Mshift)
5345
5346 return M+y
5347
5348def _dexp(c, e, p):
5349 """Compute an approximation to exp(c*10**e), with p decimal places of
5350 precision.
5351
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005352 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005353
5354 10**(p-1) <= d <= 10**p, and
5355 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5356
5357 In other words, d*10**f is an approximation to exp(c*10**e) with p
5358 digits of precision, and with an error in d of at most 1. This is
5359 almost, but not quite, the same as the error being < 1ulp: when d
5360 = 10**(p-1) the error could be up to 10 ulp."""
5361
5362 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5363 p += 2
5364
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005365 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005366 extra = max(0, e + len(str(c)) - 1)
5367 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005368
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005369 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005370 # rounding down
5371 shift = e+q
5372 if shift >= 0:
5373 cshift = c*10**shift
5374 else:
5375 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005376 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005377
5378 # reduce remainder back to original precision
5379 rem = _div_nearest(rem, 10**extra)
5380
5381 # error in result of _iexp < 120; error after division < 0.62
5382 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5383
5384def _dpower(xc, xe, yc, ye, p):
5385 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5386 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5387
5388 10**(p-1) <= c <= 10**p, and
5389 (c-1)*10**e < x**y < (c+1)*10**e
5390
5391 in other words, c*10**e is an approximation to x**y with p digits
5392 of precision, and with an error in c of at most 1. (This is
5393 almost, but not quite, the same as the error being < 1ulp: when c
5394 == 10**(p-1) we can only guarantee error < 10ulp.)
5395
5396 We assume that: x is positive and not equal to 1, and y is nonzero.
5397 """
5398
5399 # Find b such that 10**(b-1) <= |y| <= 10**b
5400 b = len(str(abs(yc))) + ye
5401
5402 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5403 lxc = _dlog(xc, xe, p+b+1)
5404
5405 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5406 shift = ye-b
5407 if shift >= 0:
5408 pc = lxc*yc*10**shift
5409 else:
5410 pc = _div_nearest(lxc*yc, 10**-shift)
5411
5412 if pc == 0:
5413 # we prefer a result that isn't exactly 1; this makes it
5414 # easier to compute a correctly rounded result in __pow__
5415 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5416 coeff, exp = 10**(p-1)+1, 1-p
5417 else:
5418 coeff, exp = 10**p-1, -p
5419 else:
5420 coeff, exp = _dexp(pc, -(p+1), p+1)
5421 coeff = _div_nearest(coeff, 10)
5422 exp += 1
5423
5424 return coeff, exp
5425
5426def _log10_lb(c, correction = {
5427 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5428 '6': 23, '7': 16, '8': 10, '9': 5}):
5429 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5430 if c <= 0:
5431 raise ValueError("The argument to _log10_lb should be nonnegative.")
5432 str_c = str(c)
5433 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005434
Guido van Rossumd8faa362007-04-27 19:54:29 +00005435##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005436
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005437def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005438 """Convert other to Decimal.
5439
5440 Verifies that it's ok to use in an implicit construction.
5441 """
5442 if isinstance(other, Decimal):
5443 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005444 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005445 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005446 if raiseit:
5447 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005448 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005449
Guido van Rossumd8faa362007-04-27 19:54:29 +00005450##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005451
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005452# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005453# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005454
5455DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005456 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005457 traps=[DivisionByZero, Overflow, InvalidOperation],
5458 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005459 Emax=999999999,
5460 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005461 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005462)
5463
5464# Pre-made alternate contexts offered by the specification
5465# Don't change these; the user should be able to select these
5466# contexts and be able to reproduce results from other implementations
5467# of the spec.
5468
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005469BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005470 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005471 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5472 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005473)
5474
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005475ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005476 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005477 traps=[],
5478 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005479)
5480
5481
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005482##### crud for parsing strings #############################################
Christian Heimes23daade2008-02-25 12:39:23 +00005483#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005484# Regular expression used for parsing numeric strings. Additional
5485# comments:
5486#
5487# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5488# whitespace. But note that the specification disallows whitespace in
5489# a numeric string.
5490#
5491# 2. For finite numbers (not infinities and NaNs) the body of the
5492# number between the optional sign and the optional exponent must have
5493# at least one decimal digit, possibly after the decimal point. The
Antoine Pitroufd036452008-08-19 17:56:33 +00005494# lookahead expression '(?=[0-9]|\.[0-9])' checks this.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005495#
5496# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5497# other meaning for \d than the numbers [0-9].
5498
5499import re
Benjamin Peterson41181742008-07-02 20:22:54 +00005500_parser = re.compile(r""" # A numeric string consists of:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005501# \s*
Benjamin Peterson41181742008-07-02 20:22:54 +00005502 (?P<sign>[-+])? # an optional sign, followed by either...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005503 (
Benjamin Peterson41181742008-07-02 20:22:54 +00005504 (?=[0-9]|\.[0-9]) # ...a number (with at least one digit)
5505 (?P<int>[0-9]*) # having a (possibly empty) integer part
5506 (\.(?P<frac>[0-9]*))? # followed by an optional fractional part
5507 (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005508 |
Benjamin Peterson41181742008-07-02 20:22:54 +00005509 Inf(inity)? # ...an infinity, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005510 |
Benjamin Peterson41181742008-07-02 20:22:54 +00005511 (?P<signal>s)? # ...an (optionally signaling)
5512 NaN # NaN
5513 (?P<diag>[0-9]*) # with (possibly empty) diagnostic info.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005514 )
5515# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00005516 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005517""", re.VERBOSE | re.IGNORECASE).match
5518
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005519_all_zeros = re.compile('0*$').match
5520_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00005521
5522##### PEP3101 support functions ##############################################
5523# The functions parse_format_specifier and format_align have little to do
5524# with the Decimal class, and could potentially be reused for other pure
5525# Python numeric classes that want to implement __format__
5526#
5527# A format specifier for Decimal looks like:
5528#
5529# [[fill]align][sign][0][minimumwidth][.precision][type]
5530#
5531
5532_parse_format_specifier_regex = re.compile(r"""\A
5533(?:
5534 (?P<fill>.)?
5535 (?P<align>[<>=^])
5536)?
5537(?P<sign>[-+ ])?
5538(?P<zeropad>0)?
5539(?P<minimumwidth>(?!0)\d+)?
5540(?:\.(?P<precision>0|(?!0)\d+))?
5541(?P<type>[eEfFgG%])?
5542\Z
5543""", re.VERBOSE)
5544
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005545del re
5546
Christian Heimesf16baeb2008-02-29 14:57:44 +00005547def _parse_format_specifier(format_spec):
5548 """Parse and validate a format specifier.
5549
5550 Turns a standard numeric format specifier into a dict, with the
5551 following entries:
5552
5553 fill: fill character to pad field to minimum width
5554 align: alignment type, either '<', '>', '=' or '^'
5555 sign: either '+', '-' or ' '
5556 minimumwidth: nonnegative integer giving minimum width
5557 precision: nonnegative integer giving precision, or None
5558 type: one of the characters 'eEfFgG%', or None
5559 unicode: either True or False (always True for Python 3.x)
5560
5561 """
5562 m = _parse_format_specifier_regex.match(format_spec)
5563 if m is None:
5564 raise ValueError("Invalid format specifier: " + format_spec)
5565
5566 # get the dictionary
5567 format_dict = m.groupdict()
5568
5569 # defaults for fill and alignment
5570 fill = format_dict['fill']
5571 align = format_dict['align']
5572 if format_dict.pop('zeropad') is not None:
5573 # in the face of conflict, refuse the temptation to guess
5574 if fill is not None and fill != '0':
5575 raise ValueError("Fill character conflicts with '0'"
5576 " in format specifier: " + format_spec)
5577 if align is not None and align != '=':
5578 raise ValueError("Alignment conflicts with '0' in "
5579 "format specifier: " + format_spec)
5580 fill = '0'
5581 align = '='
5582 format_dict['fill'] = fill or ' '
5583 format_dict['align'] = align or '<'
5584
5585 if format_dict['sign'] is None:
5586 format_dict['sign'] = '-'
5587
5588 # turn minimumwidth and precision entries into integers.
5589 # minimumwidth defaults to 0; precision remains None if not given
5590 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5591 if format_dict['precision'] is not None:
5592 format_dict['precision'] = int(format_dict['precision'])
5593
5594 # if format type is 'g' or 'G' then a precision of 0 makes little
5595 # sense; convert it to 1. Same if format type is unspecified.
5596 if format_dict['precision'] == 0:
5597 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5598 format_dict['precision'] = 1
5599
5600 # record whether return type should be str or unicode
Christian Heimes295f4fa2008-02-29 15:03:39 +00005601 format_dict['unicode'] = True
Christian Heimesf16baeb2008-02-29 14:57:44 +00005602
5603 return format_dict
5604
5605def _format_align(body, spec_dict):
5606 """Given an unpadded, non-aligned numeric string, add padding and
5607 aligment to conform with the given format specifier dictionary (as
5608 output from parse_format_specifier).
5609
5610 It's assumed that if body is negative then it starts with '-'.
5611 Any leading sign ('-' or '+') is stripped from the body before
5612 applying the alignment and padding rules, and replaced in the
5613 appropriate position.
5614
5615 """
5616 # figure out the sign; we only examine the first character, so if
5617 # body has leading whitespace the results may be surprising.
5618 if len(body) > 0 and body[0] in '-+':
5619 sign = body[0]
5620 body = body[1:]
5621 else:
5622 sign = ''
5623
5624 if sign != '-':
5625 if spec_dict['sign'] in ' +':
5626 sign = spec_dict['sign']
5627 else:
5628 sign = ''
5629
5630 # how much extra space do we have to play with?
5631 minimumwidth = spec_dict['minimumwidth']
5632 fill = spec_dict['fill']
5633 padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5634
5635 align = spec_dict['align']
5636 if align == '<':
5637 result = padding + sign + body
5638 elif align == '>':
5639 result = sign + body + padding
5640 elif align == '=':
5641 result = sign + padding + body
5642 else: #align == '^'
5643 half = len(padding)//2
5644 result = padding[:half] + sign + body + padding[half:]
5645
Christian Heimesf16baeb2008-02-29 14:57:44 +00005646 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005647
Guido van Rossumd8faa362007-04-27 19:54:29 +00005648##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005649
Guido van Rossumd8faa362007-04-27 19:54:29 +00005650# Reusable defaults
Mark Dickinson627cf6a2009-01-03 12:11:47 +00005651_Infinity = Decimal('Inf')
5652_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonf9236412009-01-02 23:23:21 +00005653_NaN = Decimal('NaN')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00005654_Zero = Decimal(0)
5655_One = Decimal(1)
5656_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005657
Mark Dickinson627cf6a2009-01-03 12:11:47 +00005658# _SignedInfinity[sign] is infinity w/ that sign
5659_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005660
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005661
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005662
5663if __name__ == '__main__':
5664 import doctest, sys
5665 doctest.testmod(sys.modules[__name__])