blob: b486d36f9ac5505007f7ffbcb57536a6030299a1 [file] [log] [blame]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001# Copyright (c) 2004 Python Software Foundation.
2# All rights reserved.
3
4# Written by Eric Price <eprice at tjhsst.edu>
5# and Facundo Batista <facundo at taniquetil.com.ar>
6# and Raymond Hettinger <python at rcn.com>
Fred Drake1f34eb12004-07-01 14:28:36 +00007# and Aahz <aahz at pobox.com>
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00008# and Tim Peters
9
Raymond Hettinger27dbcf22004-08-19 22:39:55 +000010# This module is currently Py2.3 compatible and should be kept that way
11# unless a major compelling advantage arises. IOW, 2.3 compatibility is
12# strongly preferred, but not guaranteed.
13
14# Also, this module should be kept in sync with the latest updates of
15# the IBM specification as it evolves. Those updates will be treated
16# as bug fixes (deviation from the spec is a compatibility, usability
17# bug) and will be backported. At this point the spec is stabilizing
18# and the updates are becoming fewer, smaller, and less significant.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000019
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000020"""
21This is a Py2.3 implementation of decimal floating point arithmetic based on
22the General Decimal Arithmetic Specification:
23
24 www2.hursley.ibm.com/decimal/decarith.html
25
Raymond Hettinger0ea241e2004-07-04 13:53:24 +000026and IEEE standard 854-1987:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000027
28 www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
29
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000030Decimal floating point has finite precision with arbitrarily large bounds.
31
Guido van Rossumd8faa362007-04-27 19:54:29 +000032The purpose of this module is to support arithmetic using familiar
33"schoolhouse" rules and to avoid some of the tricky representation
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000034issues associated with binary floating point. The package is especially
35useful for financial applications or for contexts where users have
36expectations that are at odds with binary floating point (for instance,
37in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
Christian Heimes68f5fbe2008-02-14 08:27:37 +000038of the expected Decimal('0.00') returned by decimal floating point).
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000039
40Here are some examples of using the decimal module:
41
42>>> from decimal import *
Raymond Hettingerbd7f76d2004-07-08 00:49:18 +000043>>> setcontext(ExtendedContext)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000044>>> Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000045Decimal('0')
46>>> Decimal('1')
47Decimal('1')
48>>> Decimal('-.0123')
49Decimal('-0.0123')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000050>>> Decimal(123456)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000051Decimal('123456')
52>>> Decimal('123.45e12345678901234567890')
53Decimal('1.2345E+12345678901234567892')
54>>> Decimal('1.33') + Decimal('1.27')
55Decimal('2.60')
56>>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
57Decimal('-2.20')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000058>>> dig = Decimal(1)
Guido van Rossum7131f842007-02-09 20:13:25 +000059>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000600.333333333
61>>> getcontext().prec = 18
Guido van Rossum7131f842007-02-09 20:13:25 +000062>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000630.333333333333333333
Guido van Rossum7131f842007-02-09 20:13:25 +000064>>> print(dig.sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000651
Guido van Rossum7131f842007-02-09 20:13:25 +000066>>> print(Decimal(3).sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000671.73205080756887729
Guido van Rossum7131f842007-02-09 20:13:25 +000068>>> print(Decimal(3) ** 123)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000694.85192780976896427E+58
70>>> inf = Decimal(1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000071>>> print(inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000072Infinity
73>>> neginf = Decimal(-1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000074>>> print(neginf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000075-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000076>>> print(neginf + inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000077NaN
Guido van Rossum7131f842007-02-09 20:13:25 +000078>>> print(neginf * inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000079-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000080>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000081Infinity
Raymond Hettingerbf440692004-07-10 14:14:37 +000082>>> getcontext().traps[DivisionByZero] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000083>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000084Traceback (most recent call last):
85 ...
86 ...
87 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +000088decimal.DivisionByZero: x / 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000089>>> c = Context()
Raymond Hettingerbf440692004-07-10 14:14:37 +000090>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000091>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000920
93>>> c.divide(Decimal(0), Decimal(0))
Christian Heimes68f5fbe2008-02-14 08:27:37 +000094Decimal('NaN')
Raymond Hettingerbf440692004-07-10 14:14:37 +000095>>> c.traps[InvalidOperation] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000096>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000098>>> c.flags[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000099>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000
Guido van Rossum7131f842007-02-09 20:13:25 +0000101>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000102Traceback (most recent call last):
103 ...
104 ...
105 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +0000106decimal.InvalidOperation: 0 / 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000107>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000109>>> c.flags[InvalidOperation] = 0
Raymond Hettingerbf440692004-07-10 14:14:37 +0000110>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000111>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000112NaN
Guido van Rossum7131f842007-02-09 20:13:25 +0000113>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141
115>>>
116"""
117
118__all__ = [
119 # Two major classes
120 'Decimal', 'Context',
121
122 # Contexts
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +0000123 'DefaultContext', 'BasicContext', 'ExtendedContext',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000124
125 # Exceptions
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +0000126 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
127 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000128
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000129 # Constants for use in setting up contexts
130 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000131 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000132
133 # Functions for manipulating contexts
Thomas Wouters89f507f2006-12-13 04:49:30 +0000134 'setcontext', 'getcontext', 'localcontext'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000135]
136
Guido van Rossuma13f4a12007-12-10 20:04:04 +0000137import numbers as _numbers
Raymond Hettingereb260842005-06-07 18:52:34 +0000138import copy as _copy
Raymond Hettinger771ed762009-01-03 19:20:32 +0000139import math as _math
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000140
Christian Heimes25bb7832008-01-11 16:17:00 +0000141try:
142 from collections import namedtuple as _namedtuple
143 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
144except ImportError:
145 DecimalTuple = lambda *args: args
146
Guido van Rossumd8faa362007-04-27 19:54:29 +0000147# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000148ROUND_DOWN = 'ROUND_DOWN'
149ROUND_HALF_UP = 'ROUND_HALF_UP'
150ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
151ROUND_CEILING = 'ROUND_CEILING'
152ROUND_FLOOR = 'ROUND_FLOOR'
153ROUND_UP = 'ROUND_UP'
154ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000155ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000156
Guido van Rossumd8faa362007-04-27 19:54:29 +0000157# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000158
159class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000160 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000161
162 Used exceptions derive from this.
163 If an exception derives from another exception besides this (such as
164 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
165 called if the others are present. This isn't actually used for
166 anything, though.
167
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000168 handle -- Called when context._raise_error is called and the
169 trap_enabler is set. First argument is self, second is the
170 context. More arguments can be given, those being after
171 the explanation in _raise_error (For example,
172 context._raise_error(NewError, '(-x)!', self._sign) would
173 call NewError().handle(context, self._sign).)
174
175 To define a new exception, it should be sufficient to have it derive
176 from DecimalException.
177 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000178 def handle(self, context, *args):
179 pass
180
181
182class Clamped(DecimalException):
183 """Exponent of a 0 changed to fit bounds.
184
185 This occurs and signals clamped if the exponent of a result has been
186 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000187 representation. This may occur when the exponent of a zero result would
188 be outside the bounds of a representation, or when a large normal
189 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000190 this latter case, the exponent is reduced to fit and the corresponding
191 number of zero digits are appended to the coefficient ("fold-down").
192 """
193
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000194class InvalidOperation(DecimalException):
195 """An invalid operation was performed.
196
197 Various bad things cause this:
198
199 Something creates a signaling NaN
200 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000201 0 * (+-)INF
202 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000203 x % 0
204 (+-)INF % x
205 x._rescale( non-integer )
206 sqrt(-x) , x > 0
207 0 ** 0
208 x ** (non-integer)
209 x ** (+-)INF
210 An operand is invalid
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000211
212 The result of the operation after these is a quiet positive NaN,
213 except when the cause is a signaling NaN, in which case the result is
214 also a quiet NaN, but with the original sign, and an optional
215 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000216 """
217 def handle(self, context, *args):
218 if args:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000219 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
220 return ans._fix_nan(context)
Mark Dickinsonf9236412009-01-02 23:23:21 +0000221 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000222
223class ConversionSyntax(InvalidOperation):
224 """Trying to convert badly formed string.
225
226 This occurs and signals invalid-operation if an string is being
227 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000228 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000229 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000230 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000231 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000232
233class DivisionByZero(DecimalException, ZeroDivisionError):
234 """Division by 0.
235
236 This occurs and signals division-by-zero if division of a finite number
237 by zero was attempted (during a divide-integer or divide operation, or a
238 power operation with negative right-hand operand), and the dividend was
239 not zero.
240
241 The result of the operation is [sign,inf], where sign is the exclusive
242 or of the signs of the operands for divide, or is 1 for an odd power of
243 -0, for power.
244 """
245
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000246 def handle(self, context, sign, *args):
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000247 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000248
249class DivisionImpossible(InvalidOperation):
250 """Cannot perform the division adequately.
251
252 This occurs and signals invalid-operation if the integer result of a
253 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000254 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000255 """
256
257 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000258 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000259
260class DivisionUndefined(InvalidOperation, ZeroDivisionError):
261 """Undefined result of division.
262
263 This occurs and signals invalid-operation if division by zero was
264 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000265 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000266 """
267
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000268 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000269 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000270
271class Inexact(DecimalException):
272 """Had to round, losing information.
273
274 This occurs and signals inexact whenever the result of an operation is
275 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000276 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000277 result in all cases is unchanged.
278
279 The inexact signal may be tested (or trapped) to determine if a given
280 operation (or sequence of operations) was inexact.
281 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000282
283class InvalidContext(InvalidOperation):
284 """Invalid context. Unknown rounding, for example.
285
286 This occurs and signals invalid-operation if an invalid context was
Guido van Rossumd8faa362007-04-27 19:54:29 +0000287 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000288 on creation and either the precision exceeds the capability of the
289 underlying concrete representation or an unknown or unsupported rounding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000290 was specified. These aspects of the context need only be checked when
291 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000292 """
293
294 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000295 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000296
297class Rounded(DecimalException):
298 """Number got rounded (not necessarily changed during rounding).
299
300 This occurs and signals rounded whenever the result of an operation is
301 rounded (that is, some zero or non-zero digits were discarded from the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000302 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000303 result in all cases is unchanged.
304
305 The rounded signal may be tested (or trapped) to determine if a given
306 operation (or sequence of operations) caused a loss of precision.
307 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000308
309class Subnormal(DecimalException):
310 """Exponent < Emin before rounding.
311
312 This occurs and signals subnormal whenever the result of a conversion or
313 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000314 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000315
316 The subnormal signal may be tested (or trapped) to determine if a given
317 or operation (or sequence of operations) yielded a subnormal result.
318 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000319
320class Overflow(Inexact, Rounded):
321 """Numerical overflow.
322
323 This occurs and signals overflow if the adjusted exponent of a result
324 (from a conversion or from an operation that is not an attempt to divide
325 by zero), after rounding, would be greater than the largest value that
326 can be handled by the implementation (the value Emax).
327
328 The result depends on the rounding mode:
329
330 For round-half-up and round-half-even (and for round-half-down and
331 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000332 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000333 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000334 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000335 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000336 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000338 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000339 will also be raised.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000340 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000341
342 def handle(self, context, sign, *args):
343 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000344 ROUND_HALF_DOWN, ROUND_UP):
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000345 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000346 if sign == 0:
347 if context.rounding == ROUND_CEILING:
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000348 return _SignedInfinity[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000349 return _dec_from_triple(sign, '9'*context.prec,
350 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000351 if sign == 1:
352 if context.rounding == ROUND_FLOOR:
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000353 return _SignedInfinity[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000354 return _dec_from_triple(sign, '9'*context.prec,
355 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000356
357
358class Underflow(Inexact, Rounded, Subnormal):
359 """Numerical underflow with result rounded to 0.
360
361 This occurs and signals underflow if a result is inexact and the
362 adjusted exponent of the result would be smaller (more negative) than
363 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000364 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000365
366 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000367 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000368 in 0 with the sign of the intermediate result and an exponent of Etiny.
369
370 In all cases, Inexact, Rounded, and Subnormal will also be raised.
371 """
372
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000373# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000374_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000375 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000376
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000377# Map conditions (per the spec) to signals
378_condition_map = {ConversionSyntax:InvalidOperation,
379 DivisionImpossible:InvalidOperation,
380 DivisionUndefined:InvalidOperation,
381 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000382
Guido van Rossumd8faa362007-04-27 19:54:29 +0000383##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000384
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000385# The getcontext() and setcontext() function manage access to a thread-local
386# current context. Py2.4 offers direct support for thread locals. If that
Georg Brandlf9926402008-06-13 06:32:25 +0000387# is not available, use threading.current_thread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000388# work for older Pythons. If threads are not part of the build, create a
389# mock threading object with threading.local() returning the module namespace.
390
391try:
392 import threading
393except ImportError:
394 # Python was compiled without threads; create a mock object instead
395 import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +0000396 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000397 def local(self, sys=sys):
398 return sys.modules[__name__]
399 threading = MockThreading()
400 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000401
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000402try:
403 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000404
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000405except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000406
Guido van Rossumd8faa362007-04-27 19:54:29 +0000407 # To fix reloading, force it to create a new context
408 # Old contexts have different exceptions in their dicts, making problems.
Georg Brandlf9926402008-06-13 06:32:25 +0000409 if hasattr(threading.current_thread(), '__decimal_context__'):
410 del threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000411
412 def setcontext(context):
413 """Set this thread's context to context."""
414 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000415 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000416 context.clear_flags()
Georg Brandlf9926402008-06-13 06:32:25 +0000417 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000418
419 def getcontext():
420 """Returns this thread's context.
421
422 If this thread does not yet have a context, returns
423 a new context and sets this thread's context.
424 New contexts are copies of DefaultContext.
425 """
426 try:
Georg Brandlf9926402008-06-13 06:32:25 +0000427 return threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000428 except AttributeError:
429 context = Context()
Georg Brandlf9926402008-06-13 06:32:25 +0000430 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000431 return context
432
433else:
434
435 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000436 if hasattr(local, '__decimal_context__'):
437 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000438
439 def getcontext(_local=local):
440 """Returns this thread's context.
441
442 If this thread does not yet have a context, returns
443 a new context and sets this thread's context.
444 New contexts are copies of DefaultContext.
445 """
446 try:
447 return _local.__decimal_context__
448 except AttributeError:
449 context = Context()
450 _local.__decimal_context__ = context
451 return context
452
453 def setcontext(context, _local=local):
454 """Set this thread's context to context."""
455 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000456 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000457 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000458 _local.__decimal_context__ = context
459
460 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000461
Thomas Wouters89f507f2006-12-13 04:49:30 +0000462def localcontext(ctx=None):
463 """Return a context manager for a copy of the supplied context
464
465 Uses a copy of the current context if no context is specified
466 The returned context manager creates a local decimal context
467 in a with statement:
468 def sin(x):
469 with localcontext() as ctx:
470 ctx.prec += 2
471 # Rest of sin calculation algorithm
472 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000473 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000474
475 def sin(x):
476 with localcontext(ExtendedContext):
477 # Rest of sin calculation algorithm
478 # uses the Extended Context from the
479 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000480 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000481
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000482 >>> setcontext(DefaultContext)
Guido van Rossum7131f842007-02-09 20:13:25 +0000483 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000484 28
485 >>> with localcontext():
486 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000487 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000488 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000489 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000490 30
491 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000492 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000493 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000494 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000495 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000496 28
497 """
498 if ctx is None: ctx = getcontext()
499 return _ContextManager(ctx)
500
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000501
Guido van Rossumd8faa362007-04-27 19:54:29 +0000502##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000503
Christian Heimes08976cb2008-03-16 00:32:36 +0000504class Decimal(_numbers.Real):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000505 """Floating point class for decimal arithmetic."""
506
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000507 __slots__ = ('_exp','_int','_sign', '_is_special')
508 # Generally, the value of the Decimal instance is given by
509 # (-1)**_sign * _int * 10**_exp
510 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000511
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000512 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000513 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000514 """Create a decimal point instance.
515
516 >>> Decimal('3.14') # string input
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000517 Decimal('3.14')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000518 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000519 Decimal('3.14')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000520 >>> Decimal(314) # int
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000521 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000522 >>> Decimal(Decimal(314)) # another decimal instance
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000523 Decimal('314')
Christian Heimesa62da1d2008-01-12 19:39:10 +0000524 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000525 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000526 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000527
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000528 # Note that the coefficient, self._int, is actually stored as
529 # a string rather than as a tuple of digits. This speeds up
530 # the "digits to integer" and "integer to digits" conversions
531 # that are used in almost every arithmetic operation on
532 # Decimals. This is an internal detail: the as_tuple function
533 # and the Decimal constructor still deal with tuples of
534 # digits.
535
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000536 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000537
Christian Heimesd59c64c2007-11-30 19:27:20 +0000538 # From a string
539 # REs insist on real strings, so we can too.
540 if isinstance(value, str):
Christian Heimesa62da1d2008-01-12 19:39:10 +0000541 m = _parser(value.strip())
Christian Heimesd59c64c2007-11-30 19:27:20 +0000542 if m is None:
543 if context is None:
544 context = getcontext()
545 return context._raise_error(ConversionSyntax,
546 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000547
Christian Heimesd59c64c2007-11-30 19:27:20 +0000548 if m.group('sign') == "-":
549 self._sign = 1
550 else:
551 self._sign = 0
552 intpart = m.group('int')
553 if intpart is not None:
554 # finite number
555 fracpart = m.group('frac')
556 exp = int(m.group('exp') or '0')
557 if fracpart is not None:
558 self._int = (intpart+fracpart).lstrip('0') or '0'
559 self._exp = exp - len(fracpart)
560 else:
561 self._int = intpart.lstrip('0') or '0'
562 self._exp = exp
563 self._is_special = False
564 else:
565 diag = m.group('diag')
566 if diag is not None:
567 # NaN
568 self._int = diag.lstrip('0')
569 if m.group('signal'):
570 self._exp = 'N'
571 else:
572 self._exp = 'n'
573 else:
574 # infinity
575 self._int = '0'
576 self._exp = 'F'
577 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000578 return self
579
580 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000581 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000582 if value >= 0:
583 self._sign = 0
584 else:
585 self._sign = 1
586 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000587 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000588 self._is_special = False
589 return self
590
591 # From another decimal
592 if isinstance(value, Decimal):
593 self._exp = value._exp
594 self._sign = value._sign
595 self._int = value._int
596 self._is_special = value._is_special
597 return self
598
599 # From an internal working value
600 if isinstance(value, _WorkRep):
601 self._sign = value.sign
602 self._int = str(value.int)
603 self._exp = int(value.exp)
604 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000605 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000606
607 # tuple/list conversion (possibly from as_tuple())
608 if isinstance(value, (list,tuple)):
609 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000610 raise ValueError('Invalid tuple size in creation of Decimal '
611 'from list or tuple. The list or tuple '
612 'should have exactly three elements.')
613 # process sign. The isinstance test rejects floats
614 if not (isinstance(value[0], int) and value[0] in (0,1)):
615 raise ValueError("Invalid sign. The first value in the tuple "
616 "should be an integer; either 0 for a "
617 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000618 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000619 if value[2] == 'F':
620 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000621 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000622 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000623 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000624 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000625 # process and validate the digits in value[1]
626 digits = []
627 for digit in value[1]:
628 if isinstance(digit, int) and 0 <= digit <= 9:
629 # skip leading zeros
630 if digits or digit != 0:
631 digits.append(digit)
632 else:
633 raise ValueError("The second value in the tuple must "
634 "be composed of integers in the range "
635 "0 through 9.")
636 if value[2] in ('n', 'N'):
637 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000638 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000639 self._exp = value[2]
640 self._is_special = True
641 elif isinstance(value[2], int):
642 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000643 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000644 self._exp = value[2]
645 self._is_special = False
646 else:
647 raise ValueError("The third value in the tuple must "
648 "be an integer, or one of the "
649 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000650 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000651
Raymond Hettingerbf440692004-07-10 14:14:37 +0000652 if isinstance(value, float):
653 raise TypeError("Cannot convert float to Decimal. " +
654 "First convert the float to a string")
655
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000656 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000657
Mark Dickinsonba298e42009-01-04 21:17:43 +0000658 # @classmethod, but @decorator is not valid Python 2.3 syntax, so
659 # don't use it (see notes on Py2.3 compatibility at top of file)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000660 def from_float(cls, f):
661 """Converts a float to a decimal number, exactly.
662
663 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
664 Since 0.1 is not exactly representable in binary floating point, the
665 value is stored as the nearest representable value which is
666 0x1.999999999999ap-4. The exact equivalent of the value in decimal
667 is 0.1000000000000000055511151231257827021181583404541015625.
668
669 >>> Decimal.from_float(0.1)
670 Decimal('0.1000000000000000055511151231257827021181583404541015625')
671 >>> Decimal.from_float(float('nan'))
672 Decimal('NaN')
673 >>> Decimal.from_float(float('inf'))
674 Decimal('Infinity')
675 >>> Decimal.from_float(-float('inf'))
676 Decimal('-Infinity')
677 >>> Decimal.from_float(-0.0)
678 Decimal('-0')
679
680 """
681 if isinstance(f, int): # handle integer inputs
682 return cls(f)
683 if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float
684 return cls(repr(f))
Mark Dickinsonba298e42009-01-04 21:17:43 +0000685 if _math.copysign(1.0, f) == 1.0:
686 sign = 0
687 else:
688 sign = 1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000689 n, d = abs(f).as_integer_ratio()
690 k = d.bit_length() - 1
691 result = _dec_from_triple(sign, str(n*5**k), -k)
Mark Dickinsonba298e42009-01-04 21:17:43 +0000692 if cls is Decimal:
693 return result
694 else:
695 return cls(result)
696 from_float = classmethod(from_float)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000697
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000698 def _isnan(self):
699 """Returns whether the number is not actually one.
700
701 0 if a number
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000702 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000703 2 if sNaN
704 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000705 if self._is_special:
706 exp = self._exp
707 if exp == 'n':
708 return 1
709 elif exp == 'N':
710 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000711 return 0
712
713 def _isinfinity(self):
714 """Returns whether the number is infinite
715
716 0 if finite or not a number
717 1 if +INF
718 -1 if -INF
719 """
720 if self._exp == 'F':
721 if self._sign:
722 return -1
723 return 1
724 return 0
725
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000726 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000727 """Returns whether the number is not actually one.
728
729 if self, other are sNaN, signal
730 if self, other are NaN return nan
731 return 0
732
733 Done before operations.
734 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000735
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000736 self_is_nan = self._isnan()
737 if other is None:
738 other_is_nan = False
739 else:
740 other_is_nan = other._isnan()
741
742 if self_is_nan or other_is_nan:
743 if context is None:
744 context = getcontext()
745
746 if self_is_nan == 2:
747 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000748 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000749 if other_is_nan == 2:
750 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000751 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000752 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000753 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000754
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000755 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000756 return 0
757
Christian Heimes77c02eb2008-02-09 02:18:51 +0000758 def _compare_check_nans(self, other, context):
759 """Version of _check_nans used for the signaling comparisons
760 compare_signal, __le__, __lt__, __ge__, __gt__.
761
762 Signal InvalidOperation if either self or other is a (quiet
763 or signaling) NaN. Signaling NaNs take precedence over quiet
764 NaNs.
765
766 Return 0 if neither operand is a NaN.
767
768 """
769 if context is None:
770 context = getcontext()
771
772 if self._is_special or other._is_special:
773 if self.is_snan():
774 return context._raise_error(InvalidOperation,
775 'comparison involving sNaN',
776 self)
777 elif other.is_snan():
778 return context._raise_error(InvalidOperation,
779 'comparison involving sNaN',
780 other)
781 elif self.is_qnan():
782 return context._raise_error(InvalidOperation,
783 'comparison involving NaN',
784 self)
785 elif other.is_qnan():
786 return context._raise_error(InvalidOperation,
787 'comparison involving NaN',
788 other)
789 return 0
790
Jack Diederich4dafcc42006-11-28 19:15:13 +0000791 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000792 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000793
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000794 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000795 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000796 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000797
Christian Heimes77c02eb2008-02-09 02:18:51 +0000798 def _cmp(self, other):
799 """Compare the two non-NaN decimal instances self and other.
800
801 Returns -1 if self < other, 0 if self == other and 1
802 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000803
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000804 if self._is_special or other._is_special:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000805 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000806
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000807 # check for zeros; note that cmp(0, -0) should return 0
808 if not self:
809 if not other:
810 return 0
811 else:
812 return -((-1)**other._sign)
813 if not other:
814 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000815
Guido van Rossumd8faa362007-04-27 19:54:29 +0000816 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000817 if other._sign < self._sign:
818 return -1
819 if self._sign < other._sign:
820 return 1
821
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000822 self_adjusted = self.adjusted()
823 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000824 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000825 self_padded = self._int + '0'*(self._exp - other._exp)
826 other_padded = other._int + '0'*(other._exp - self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000827 return cmp(self_padded, other_padded) * (-1)**self._sign
828 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000829 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000830 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000831 return -((-1)**self._sign)
832
Christian Heimes77c02eb2008-02-09 02:18:51 +0000833 # Note: The Decimal standard doesn't cover rich comparisons for
834 # Decimals. In particular, the specification is silent on the
835 # subject of what should happen for a comparison involving a NaN.
836 # We take the following approach:
837 #
838 # == comparisons involving a NaN always return False
839 # != comparisons involving a NaN always return True
840 # <, >, <= and >= comparisons involving a (quiet or signaling)
841 # NaN signal InvalidOperation, and return False if the
Christian Heimes3feef612008-02-11 06:19:17 +0000842 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000843 #
844 # This behavior is designed to conform as closely as possible to
845 # that specified by IEEE 754.
846
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000847 def __eq__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000848 other = _convert_other(other)
849 if other is NotImplemented:
850 return other
851 if self.is_nan() or other.is_nan():
852 return False
853 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000854
855 def __ne__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000856 other = _convert_other(other)
857 if other is NotImplemented:
858 return other
859 if self.is_nan() or other.is_nan():
860 return True
861 return self._cmp(other) != 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000862
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000863
Christian Heimes77c02eb2008-02-09 02:18:51 +0000864 def __lt__(self, other, context=None):
865 other = _convert_other(other)
866 if other is NotImplemented:
867 return other
868 ans = self._compare_check_nans(other, context)
869 if ans:
870 return False
871 return self._cmp(other) < 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000872
Christian Heimes77c02eb2008-02-09 02:18:51 +0000873 def __le__(self, other, context=None):
874 other = _convert_other(other)
875 if other is NotImplemented:
876 return other
877 ans = self._compare_check_nans(other, context)
878 if ans:
879 return False
880 return self._cmp(other) <= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000881
Christian Heimes77c02eb2008-02-09 02:18:51 +0000882 def __gt__(self, other, context=None):
883 other = _convert_other(other)
884 if other is NotImplemented:
885 return other
886 ans = self._compare_check_nans(other, context)
887 if ans:
888 return False
889 return self._cmp(other) > 0
890
891 def __ge__(self, other, context=None):
892 other = _convert_other(other)
893 if other is NotImplemented:
894 return other
895 ans = self._compare_check_nans(other, context)
896 if ans:
897 return False
898 return self._cmp(other) >= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000899
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000900 def compare(self, other, context=None):
901 """Compares one to another.
902
903 -1 => a < b
904 0 => a = b
905 1 => a > b
906 NaN => one is NaN
907 Like __cmp__, but returns Decimal instances.
908 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000909 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000910
Guido van Rossumd8faa362007-04-27 19:54:29 +0000911 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000912 if (self._is_special or other and other._is_special):
913 ans = self._check_nans(other, context)
914 if ans:
915 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000916
Christian Heimes77c02eb2008-02-09 02:18:51 +0000917 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000918
919 def __hash__(self):
920 """x.__hash__() <==> hash(x)"""
921 # Decimal integers must hash the same as the ints
Christian Heimes2380ac72008-01-09 00:17:24 +0000922 #
923 # The hash of a nonspecial noninteger Decimal must depend only
924 # on the value of that Decimal, and not on its representation.
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000925 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000926 if self._is_special:
927 if self._isnan():
928 raise TypeError('Cannot hash a NaN value.')
929 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000930 if not self:
931 return 0
932 if self._isinteger():
933 op = _WorkRep(self.to_integral_value())
934 # to make computation feasible for Decimals with large
935 # exponent, we use the fact that hash(n) == hash(m) for
936 # any two nonzero integers n and m such that (i) n and m
937 # have the same sign, and (ii) n is congruent to m modulo
938 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
939 # hash((-1)**s*c*pow(10, e, 2**64-1).
940 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Christian Heimes2380ac72008-01-09 00:17:24 +0000941 # The value of a nonzero nonspecial Decimal instance is
942 # faithfully represented by the triple consisting of its sign,
943 # its adjusted exponent, and its coefficient with trailing
944 # zeros removed.
945 return hash((self._sign,
946 self._exp+len(self._int),
947 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000948
949 def as_tuple(self):
950 """Represents the number as a triple tuple.
951
952 To show the internals exactly as they are.
953 """
Christian Heimes25bb7832008-01-11 16:17:00 +0000954 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000955
956 def __repr__(self):
957 """Represents the number as an instance of Decimal."""
958 # Invariant: eval(repr(d)) == d
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000959 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000960
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000961 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000962 """Return string representation of the number in scientific notation.
963
964 Captures all of the information in the underlying representation.
965 """
966
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000967 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000968 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000969 if self._exp == 'F':
970 return sign + 'Infinity'
971 elif self._exp == 'n':
972 return sign + 'NaN' + self._int
973 else: # self._exp == 'N'
974 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000975
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000976 # number of digits of self._int to left of decimal point
977 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000978
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000979 # dotplace is number of digits of self._int to the left of the
980 # decimal point in the mantissa of the output string (that is,
981 # after adjusting the exponent)
982 if self._exp <= 0 and leftdigits > -6:
983 # no exponent required
984 dotplace = leftdigits
985 elif not eng:
986 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000987 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000988 elif self._int == '0':
989 # engineering notation, zero
990 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000991 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000992 # engineering notation, nonzero
993 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000994
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000995 if dotplace <= 0:
996 intpart = '0'
997 fracpart = '.' + '0'*(-dotplace) + self._int
998 elif dotplace >= len(self._int):
999 intpart = self._int+'0'*(dotplace-len(self._int))
1000 fracpart = ''
1001 else:
1002 intpart = self._int[:dotplace]
1003 fracpart = '.' + self._int[dotplace:]
1004 if leftdigits == dotplace:
1005 exp = ''
1006 else:
1007 if context is None:
1008 context = getcontext()
1009 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1010
1011 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001012
1013 def to_eng_string(self, context=None):
1014 """Convert to engineering-type string.
1015
1016 Engineering notation has an exponent which is a multiple of 3, so there
1017 are up to 3 digits left of the decimal place.
1018
1019 Same rules for when in exponential and when as a value as in __str__.
1020 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001021 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001022
1023 def __neg__(self, context=None):
1024 """Returns a copy with the sign switched.
1025
1026 Rounds, if it has reason.
1027 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001028 if self._is_special:
1029 ans = self._check_nans(context=context)
1030 if ans:
1031 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001032
1033 if not self:
1034 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001035 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001036 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001037 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001038
1039 if context is None:
1040 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001041 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001042
1043 def __pos__(self, context=None):
1044 """Returns a copy, unless it is a sNaN.
1045
1046 Rounds the number (if more then precision digits)
1047 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001048 if self._is_special:
1049 ans = self._check_nans(context=context)
1050 if ans:
1051 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001052
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001053 if not self:
1054 # + (-0) = 0
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001055 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001056 else:
1057 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001058
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001059 if context is None:
1060 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001061 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001062
Christian Heimes2c181612007-12-17 20:04:13 +00001063 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001064 """Returns the absolute value of self.
1065
Christian Heimes2c181612007-12-17 20:04:13 +00001066 If the keyword argument 'round' is false, do not round. The
1067 expression self.__abs__(round=False) is equivalent to
1068 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001069 """
Christian Heimes2c181612007-12-17 20:04:13 +00001070 if not round:
1071 return self.copy_abs()
1072
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001073 if self._is_special:
1074 ans = self._check_nans(context=context)
1075 if ans:
1076 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001077
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001078 if self._sign:
1079 ans = self.__neg__(context=context)
1080 else:
1081 ans = self.__pos__(context=context)
1082
1083 return ans
1084
1085 def __add__(self, other, context=None):
1086 """Returns self + other.
1087
1088 -INF + INF (or the reverse) cause InvalidOperation errors.
1089 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001090 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001091 if other is NotImplemented:
1092 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001093
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001094 if context is None:
1095 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001096
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001097 if self._is_special or other._is_special:
1098 ans = self._check_nans(other, context)
1099 if ans:
1100 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001101
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001102 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001103 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001104 if self._sign != other._sign and other._isinfinity():
1105 return context._raise_error(InvalidOperation, '-INF + INF')
1106 return Decimal(self)
1107 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001108 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001109
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001110 exp = min(self._exp, other._exp)
1111 negativezero = 0
1112 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001113 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001114 negativezero = 1
1115
1116 if not self and not other:
1117 sign = min(self._sign, other._sign)
1118 if negativezero:
1119 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001120 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001121 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001122 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001123 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001124 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001125 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001126 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001127 return ans
1128 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001129 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001130 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001131 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001132 return ans
1133
1134 op1 = _WorkRep(self)
1135 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001136 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001137
1138 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001139 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001140 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001141 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001142 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001143 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001144 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001145 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001146 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001147 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001148 if op1.sign == 1:
1149 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001150 op1.sign, op2.sign = op2.sign, op1.sign
1151 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001152 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001153 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001154 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001155 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001156 op1.sign, op2.sign = (0, 0)
1157 else:
1158 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001159 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001160
Raymond Hettinger17931de2004-10-27 06:21:46 +00001161 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001162 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001163 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001164 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001165
1166 result.exp = op1.exp
1167 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001168 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001169 return ans
1170
1171 __radd__ = __add__
1172
1173 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001174 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001175 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001176 if other is NotImplemented:
1177 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001178
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001179 if self._is_special or other._is_special:
1180 ans = self._check_nans(other, context=context)
1181 if ans:
1182 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001183
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001184 # self - other is computed as self + other.copy_negate()
1185 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001186
1187 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001188 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001189 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001190 if other is NotImplemented:
1191 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001192
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001193 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001194
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001195 def __mul__(self, other, context=None):
1196 """Return self * other.
1197
1198 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1199 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001200 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001201 if other is NotImplemented:
1202 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001203
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001204 if context is None:
1205 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001206
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001207 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001208
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001209 if self._is_special or other._is_special:
1210 ans = self._check_nans(other, context)
1211 if ans:
1212 return ans
1213
1214 if self._isinfinity():
1215 if not other:
1216 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001217 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001218
1219 if other._isinfinity():
1220 if not self:
1221 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001222 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001223
1224 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001225
1226 # Special case for multiplying by zero
1227 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001228 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001229 # Fixing in case the exponent is out of bounds
1230 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001231 return ans
1232
1233 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001234 if self._int == '1':
1235 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001236 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001237 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001238 if other._int == '1':
1239 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001240 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001241 return ans
1242
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001243 op1 = _WorkRep(self)
1244 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001245
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001246 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001247 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001248
1249 return ans
1250 __rmul__ = __mul__
1251
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001252 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001253 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001254 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001255 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001256 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001257
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001258 if context is None:
1259 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001260
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001261 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001262
1263 if self._is_special or other._is_special:
1264 ans = self._check_nans(other, context)
1265 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001266 return ans
1267
1268 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001269 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001270
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001271 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001272 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001273
1274 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001275 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001276 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001277
1278 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001279 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001280 if not self:
1281 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001282 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001283
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001284 if not self:
1285 exp = self._exp - other._exp
1286 coeff = 0
1287 else:
1288 # OK, so neither = 0, INF or NaN
1289 shift = len(other._int) - len(self._int) + context.prec + 1
1290 exp = self._exp - other._exp - shift
1291 op1 = _WorkRep(self)
1292 op2 = _WorkRep(other)
1293 if shift >= 0:
1294 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1295 else:
1296 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1297 if remainder:
1298 # result is not exact; adjust to ensure correct rounding
1299 if coeff % 5 == 0:
1300 coeff += 1
1301 else:
1302 # result is exact; get as close to ideal exponent as possible
1303 ideal_exp = self._exp - other._exp
1304 while exp < ideal_exp and coeff % 10 == 0:
1305 coeff //= 10
1306 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001307
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001308 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001309 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001310
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001311 def _divide(self, other, context):
1312 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001313
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001314 Assumes that neither self nor other is a NaN, that self is not
1315 infinite and that other is nonzero.
1316 """
1317 sign = self._sign ^ other._sign
1318 if other._isinfinity():
1319 ideal_exp = self._exp
1320 else:
1321 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001322
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001323 expdiff = self.adjusted() - other.adjusted()
1324 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001325 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001326 self._rescale(ideal_exp, context.rounding))
1327 if expdiff <= context.prec:
1328 op1 = _WorkRep(self)
1329 op2 = _WorkRep(other)
1330 if op1.exp >= op2.exp:
1331 op1.int *= 10**(op1.exp - op2.exp)
1332 else:
1333 op2.int *= 10**(op2.exp - op1.exp)
1334 q, r = divmod(op1.int, op2.int)
1335 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001336 return (_dec_from_triple(sign, str(q), 0),
1337 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001338
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001339 # Here the quotient is too large to be representable
1340 ans = context._raise_error(DivisionImpossible,
1341 'quotient too large in //, % or divmod')
1342 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001343
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001344 def __rtruediv__(self, other, context=None):
1345 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001346 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001347 if other is NotImplemented:
1348 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001349 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001350
1351 def __divmod__(self, other, context=None):
1352 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001353 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001354 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001355 other = _convert_other(other)
1356 if other is NotImplemented:
1357 return other
1358
1359 if context is None:
1360 context = getcontext()
1361
1362 ans = self._check_nans(other, context)
1363 if ans:
1364 return (ans, ans)
1365
1366 sign = self._sign ^ other._sign
1367 if self._isinfinity():
1368 if other._isinfinity():
1369 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1370 return ans, ans
1371 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001372 return (_SignedInfinity[sign],
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001373 context._raise_error(InvalidOperation, 'INF % x'))
1374
1375 if not other:
1376 if not self:
1377 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1378 return ans, ans
1379 else:
1380 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1381 context._raise_error(InvalidOperation, 'x % 0'))
1382
1383 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001384 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001385 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001386
1387 def __rdivmod__(self, other, context=None):
1388 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001389 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001390 if other is NotImplemented:
1391 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001392 return other.__divmod__(self, context=context)
1393
1394 def __mod__(self, other, context=None):
1395 """
1396 self % other
1397 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001398 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001399 if other is NotImplemented:
1400 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001401
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001402 if context is None:
1403 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001404
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001405 ans = self._check_nans(other, context)
1406 if ans:
1407 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001408
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001409 if self._isinfinity():
1410 return context._raise_error(InvalidOperation, 'INF % x')
1411 elif not other:
1412 if self:
1413 return context._raise_error(InvalidOperation, 'x % 0')
1414 else:
1415 return context._raise_error(DivisionUndefined, '0 % 0')
1416
1417 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001418 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001419 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001420
1421 def __rmod__(self, other, context=None):
1422 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001423 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001424 if other is NotImplemented:
1425 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001426 return other.__mod__(self, context=context)
1427
1428 def remainder_near(self, other, context=None):
1429 """
1430 Remainder nearest to 0- abs(remainder-near) <= other/2
1431 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001432 if context is None:
1433 context = getcontext()
1434
1435 other = _convert_other(other, raiseit=True)
1436
1437 ans = self._check_nans(other, context)
1438 if ans:
1439 return ans
1440
1441 # self == +/-infinity -> InvalidOperation
1442 if self._isinfinity():
1443 return context._raise_error(InvalidOperation,
1444 'remainder_near(infinity, x)')
1445
1446 # other == 0 -> either InvalidOperation or DivisionUndefined
1447 if not other:
1448 if self:
1449 return context._raise_error(InvalidOperation,
1450 'remainder_near(x, 0)')
1451 else:
1452 return context._raise_error(DivisionUndefined,
1453 'remainder_near(0, 0)')
1454
1455 # other = +/-infinity -> remainder = self
1456 if other._isinfinity():
1457 ans = Decimal(self)
1458 return ans._fix(context)
1459
1460 # self = 0 -> remainder = self, with ideal exponent
1461 ideal_exponent = min(self._exp, other._exp)
1462 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001463 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001464 return ans._fix(context)
1465
1466 # catch most cases of large or small quotient
1467 expdiff = self.adjusted() - other.adjusted()
1468 if expdiff >= context.prec + 1:
1469 # expdiff >= prec+1 => abs(self/other) > 10**prec
1470 return context._raise_error(DivisionImpossible)
1471 if expdiff <= -2:
1472 # expdiff <= -2 => abs(self/other) < 0.1
1473 ans = self._rescale(ideal_exponent, context.rounding)
1474 return ans._fix(context)
1475
1476 # adjust both arguments to have the same exponent, then divide
1477 op1 = _WorkRep(self)
1478 op2 = _WorkRep(other)
1479 if op1.exp >= op2.exp:
1480 op1.int *= 10**(op1.exp - op2.exp)
1481 else:
1482 op2.int *= 10**(op2.exp - op1.exp)
1483 q, r = divmod(op1.int, op2.int)
1484 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1485 # 10**ideal_exponent. Apply correction to ensure that
1486 # abs(remainder) <= abs(other)/2
1487 if 2*r + (q&1) > op2.int:
1488 r -= op2.int
1489 q += 1
1490
1491 if q >= 10**context.prec:
1492 return context._raise_error(DivisionImpossible)
1493
1494 # result has same sign as self unless r is negative
1495 sign = self._sign
1496 if r < 0:
1497 sign = 1-sign
1498 r = -r
1499
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001500 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001501 return ans._fix(context)
1502
1503 def __floordiv__(self, other, context=None):
1504 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001505 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001506 if other is NotImplemented:
1507 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001508
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001509 if context is None:
1510 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001511
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001512 ans = self._check_nans(other, context)
1513 if ans:
1514 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001515
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001516 if self._isinfinity():
1517 if other._isinfinity():
1518 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001519 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001520 return _SignedInfinity[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001521
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001522 if not other:
1523 if self:
1524 return context._raise_error(DivisionByZero, 'x // 0',
1525 self._sign ^ other._sign)
1526 else:
1527 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001528
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001529 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001530
1531 def __rfloordiv__(self, other, context=None):
1532 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001533 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001534 if other is NotImplemented:
1535 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001536 return other.__floordiv__(self, context=context)
1537
1538 def __float__(self):
1539 """Float representation."""
1540 return float(str(self))
1541
1542 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001543 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001544 if self._is_special:
1545 if self._isnan():
1546 context = getcontext()
1547 return context._raise_error(InvalidContext)
1548 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001549 raise OverflowError("Cannot convert infinity to int")
1550 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001551 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001552 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001553 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001554 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001555
Christian Heimes969fe572008-01-25 11:23:10 +00001556 __trunc__ = __int__
1557
Christian Heimes0bd4e112008-02-12 22:59:25 +00001558 def real(self):
1559 return self
Mark Dickinson315a20a2009-01-04 21:34:18 +00001560 real = property(real)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001561
Christian Heimes0bd4e112008-02-12 22:59:25 +00001562 def imag(self):
1563 return Decimal(0)
Mark Dickinson315a20a2009-01-04 21:34:18 +00001564 imag = property(imag)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001565
1566 def conjugate(self):
1567 return self
1568
1569 def __complex__(self):
1570 return complex(float(self))
1571
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001572 def _fix_nan(self, context):
1573 """Decapitate the payload of a NaN to fit the context"""
1574 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001575
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001576 # maximum length of payload is precision if _clamp=0,
1577 # precision-1 if _clamp=1.
1578 max_payload_len = context.prec - context._clamp
1579 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001580 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1581 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001582 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001583
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001584 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001585 """Round if it is necessary to keep self within prec precision.
1586
1587 Rounds and fixes the exponent. Does not raise on a sNaN.
1588
1589 Arguments:
1590 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001591 context - context used.
1592 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001593
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001594 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001595 if self._isnan():
1596 # decapitate payload if necessary
1597 return self._fix_nan(context)
1598 else:
1599 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001600 return Decimal(self)
1601
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001602 # if self is zero then exponent should be between Etiny and
1603 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1604 Etiny = context.Etiny()
1605 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001606 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001607 exp_max = [context.Emax, Etop][context._clamp]
1608 new_exp = min(max(self._exp, Etiny), exp_max)
1609 if new_exp != self._exp:
1610 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001611 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001612 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001613 return Decimal(self)
1614
1615 # exp_min is the smallest allowable exponent of the result,
1616 # equal to max(self.adjusted()-context.prec+1, Etiny)
1617 exp_min = len(self._int) + self._exp - context.prec
1618 if exp_min > Etop:
1619 # overflow: exp_min > Etop iff self.adjusted() > Emax
1620 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001621 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001622 return context._raise_error(Overflow, 'above Emax', self._sign)
1623 self_is_subnormal = exp_min < Etiny
1624 if self_is_subnormal:
1625 context._raise_error(Subnormal)
1626 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001627
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001628 # round if self has too many digits
1629 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001630 context._raise_error(Rounded)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001631 digits = len(self._int) + self._exp - exp_min
1632 if digits < 0:
1633 self = _dec_from_triple(self._sign, '1', exp_min-1)
1634 digits = 0
1635 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1636 changed = this_function(digits)
1637 coeff = self._int[:digits] or '0'
1638 if changed == 1:
1639 coeff = str(int(coeff)+1)
1640 ans = _dec_from_triple(self._sign, coeff, exp_min)
1641
1642 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001643 context._raise_error(Inexact)
1644 if self_is_subnormal:
1645 context._raise_error(Underflow)
1646 if not ans:
1647 # raise Clamped on underflow to 0
1648 context._raise_error(Clamped)
1649 elif len(ans._int) == context.prec+1:
1650 # we get here only if rescaling rounds the
1651 # cofficient up to exactly 10**context.prec
1652 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001653 ans = _dec_from_triple(ans._sign,
1654 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001655 else:
1656 # Inexact and Rounded have already been raised
1657 ans = context._raise_error(Overflow, 'above Emax',
1658 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001659 return ans
1660
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001661 # fold down if _clamp == 1 and self has too few digits
1662 if context._clamp == 1 and self._exp > Etop:
1663 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001664 self_padded = self._int + '0'*(self._exp - Etop)
1665 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001666
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001667 # here self was representable to begin with; return unchanged
1668 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001669
1670 _pick_rounding_function = {}
1671
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001672 # for each of the rounding functions below:
1673 # self is a finite, nonzero Decimal
1674 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001675 #
1676 # each function returns either -1, 0, or 1, as follows:
1677 # 1 indicates that self should be rounded up (away from zero)
1678 # 0 indicates that self should be truncated, and that all the
1679 # digits to be truncated are zeros (so the value is unchanged)
1680 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001681
1682 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001683 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001684 if _all_zeros(self._int, prec):
1685 return 0
1686 else:
1687 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001688
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001689 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001690 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001691 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001692
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001693 def _round_half_up(self, prec):
1694 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001695 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001696 return 1
1697 elif _all_zeros(self._int, prec):
1698 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001699 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001700 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001701
1702 def _round_half_down(self, prec):
1703 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001704 if _exact_half(self._int, prec):
1705 return -1
1706 else:
1707 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001708
1709 def _round_half_even(self, prec):
1710 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001711 if _exact_half(self._int, prec) and \
1712 (prec == 0 or self._int[prec-1] in '02468'):
1713 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001714 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001715 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001716
1717 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001718 """Rounds up (not away from 0 if negative.)"""
1719 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001720 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001721 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001722 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001723
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001724 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001725 """Rounds down (not towards 0 if negative)"""
1726 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001727 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001728 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001729 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001730
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001731 def _round_05up(self, prec):
1732 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001733 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001734 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001735 else:
1736 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001737
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001738 def __round__(self, n=None):
1739 """Round self to the nearest integer, or to a given precision.
1740
1741 If only one argument is supplied, round a finite Decimal
1742 instance self to the nearest integer. If self is infinite or
1743 a NaN then a Python exception is raised. If self is finite
1744 and lies exactly halfway between two integers then it is
1745 rounded to the integer with even last digit.
1746
1747 >>> round(Decimal('123.456'))
1748 123
1749 >>> round(Decimal('-456.789'))
1750 -457
1751 >>> round(Decimal('-3.0'))
1752 -3
1753 >>> round(Decimal('2.5'))
1754 2
1755 >>> round(Decimal('3.5'))
1756 4
1757 >>> round(Decimal('Inf'))
1758 Traceback (most recent call last):
1759 ...
1760 ...
1761 ...
1762 OverflowError: cannot round an infinity
1763 >>> round(Decimal('NaN'))
1764 Traceback (most recent call last):
1765 ...
1766 ...
1767 ...
1768 ValueError: cannot round a NaN
1769
1770 If a second argument n is supplied, self is rounded to n
1771 decimal places using the rounding mode for the current
1772 context.
1773
1774 For an integer n, round(self, -n) is exactly equivalent to
1775 self.quantize(Decimal('1En')).
1776
1777 >>> round(Decimal('123.456'), 0)
1778 Decimal('123')
1779 >>> round(Decimal('123.456'), 2)
1780 Decimal('123.46')
1781 >>> round(Decimal('123.456'), -2)
1782 Decimal('1E+2')
1783 >>> round(Decimal('-Infinity'), 37)
1784 Decimal('NaN')
1785 >>> round(Decimal('sNaN123'), 0)
1786 Decimal('NaN123')
1787
1788 """
1789 if n is not None:
1790 # two-argument form: use the equivalent quantize call
1791 if not isinstance(n, int):
1792 raise TypeError('Second argument to round should be integral')
1793 exp = _dec_from_triple(0, '1', -n)
1794 return self.quantize(exp)
1795
1796 # one-argument form
1797 if self._is_special:
1798 if self.is_nan():
1799 raise ValueError("cannot round a NaN")
1800 else:
1801 raise OverflowError("cannot round an infinity")
1802 return int(self._rescale(0, ROUND_HALF_EVEN))
1803
1804 def __floor__(self):
1805 """Return the floor of self, as an integer.
1806
1807 For a finite Decimal instance self, return the greatest
1808 integer n such that n <= self. If self is infinite or a NaN
1809 then a Python exception is raised.
1810
1811 """
1812 if self._is_special:
1813 if self.is_nan():
1814 raise ValueError("cannot round a NaN")
1815 else:
1816 raise OverflowError("cannot round an infinity")
1817 return int(self._rescale(0, ROUND_FLOOR))
1818
1819 def __ceil__(self):
1820 """Return the ceiling of self, as an integer.
1821
1822 For a finite Decimal instance self, return the least integer n
1823 such that n >= self. If self is infinite or a NaN then a
1824 Python exception is raised.
1825
1826 """
1827 if self._is_special:
1828 if self.is_nan():
1829 raise ValueError("cannot round a NaN")
1830 else:
1831 raise OverflowError("cannot round an infinity")
1832 return int(self._rescale(0, ROUND_CEILING))
1833
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001834 def fma(self, other, third, context=None):
1835 """Fused multiply-add.
1836
1837 Returns self*other+third with no rounding of the intermediate
1838 product self*other.
1839
1840 self and other are multiplied together, with no rounding of
1841 the result. The third operand is then added to the result,
1842 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001843 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001844
1845 other = _convert_other(other, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001846
1847 # compute product; raise InvalidOperation if either operand is
1848 # a signaling NaN or if the product is zero times infinity.
1849 if self._is_special or other._is_special:
1850 if context is None:
1851 context = getcontext()
1852 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001853 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001854 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001855 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001856 if self._exp == 'n':
1857 product = self
1858 elif other._exp == 'n':
1859 product = other
1860 elif self._exp == 'F':
1861 if not other:
1862 return context._raise_error(InvalidOperation,
1863 'INF * 0 in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001864 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001865 elif other._exp == 'F':
1866 if not self:
1867 return context._raise_error(InvalidOperation,
1868 '0 * INF in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001869 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001870 else:
1871 product = _dec_from_triple(self._sign ^ other._sign,
1872 str(int(self._int) * int(other._int)),
1873 self._exp + other._exp)
1874
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001875 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001876 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001877
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001878 def _power_modulo(self, other, modulo, context=None):
1879 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001880
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001881 # if can't convert other and modulo to Decimal, raise
1882 # TypeError; there's no point returning NotImplemented (no
1883 # equivalent of __rpow__ for three argument pow)
1884 other = _convert_other(other, raiseit=True)
1885 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001886
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001887 if context is None:
1888 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001889
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001890 # deal with NaNs: if there are any sNaNs then first one wins,
1891 # (i.e. behaviour for NaNs is identical to that of fma)
1892 self_is_nan = self._isnan()
1893 other_is_nan = other._isnan()
1894 modulo_is_nan = modulo._isnan()
1895 if self_is_nan or other_is_nan or modulo_is_nan:
1896 if self_is_nan == 2:
1897 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001898 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001899 if other_is_nan == 2:
1900 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001901 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001902 if modulo_is_nan == 2:
1903 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001904 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001905 if self_is_nan:
1906 return self._fix_nan(context)
1907 if other_is_nan:
1908 return other._fix_nan(context)
1909 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001910
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001911 # check inputs: we apply same restrictions as Python's pow()
1912 if not (self._isinteger() and
1913 other._isinteger() and
1914 modulo._isinteger()):
1915 return context._raise_error(InvalidOperation,
1916 'pow() 3rd argument not allowed '
1917 'unless all arguments are integers')
1918 if other < 0:
1919 return context._raise_error(InvalidOperation,
1920 'pow() 2nd argument cannot be '
1921 'negative when 3rd argument specified')
1922 if not modulo:
1923 return context._raise_error(InvalidOperation,
1924 'pow() 3rd argument cannot be 0')
1925
1926 # additional restriction for decimal: the modulus must be less
1927 # than 10**prec in absolute value
1928 if modulo.adjusted() >= context.prec:
1929 return context._raise_error(InvalidOperation,
1930 'insufficient precision: pow() 3rd '
1931 'argument must not have more than '
1932 'precision digits')
1933
1934 # define 0**0 == NaN, for consistency with two-argument pow
1935 # (even though it hurts!)
1936 if not other and not self:
1937 return context._raise_error(InvalidOperation,
1938 'at least one of pow() 1st argument '
1939 'and 2nd argument must be nonzero ;'
1940 '0**0 is not defined')
1941
1942 # compute sign of result
1943 if other._iseven():
1944 sign = 0
1945 else:
1946 sign = self._sign
1947
1948 # convert modulo to a Python integer, and self and other to
1949 # Decimal integers (i.e. force their exponents to be >= 0)
1950 modulo = abs(int(modulo))
1951 base = _WorkRep(self.to_integral_value())
1952 exponent = _WorkRep(other.to_integral_value())
1953
1954 # compute result using integer pow()
1955 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1956 for i in range(exponent.exp):
1957 base = pow(base, 10, modulo)
1958 base = pow(base, exponent.int, modulo)
1959
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001960 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001961
1962 def _power_exact(self, other, p):
1963 """Attempt to compute self**other exactly.
1964
1965 Given Decimals self and other and an integer p, attempt to
1966 compute an exact result for the power self**other, with p
1967 digits of precision. Return None if self**other is not
1968 exactly representable in p digits.
1969
1970 Assumes that elimination of special cases has already been
1971 performed: self and other must both be nonspecial; self must
1972 be positive and not numerically equal to 1; other must be
1973 nonzero. For efficiency, other._exp should not be too large,
1974 so that 10**abs(other._exp) is a feasible calculation."""
1975
1976 # In the comments below, we write x for the value of self and
1977 # y for the value of other. Write x = xc*10**xe and y =
1978 # yc*10**ye.
1979
1980 # The main purpose of this method is to identify the *failure*
1981 # of x**y to be exactly representable with as little effort as
1982 # possible. So we look for cheap and easy tests that
1983 # eliminate the possibility of x**y being exact. Only if all
1984 # these tests are passed do we go on to actually compute x**y.
1985
1986 # Here's the main idea. First normalize both x and y. We
1987 # express y as a rational m/n, with m and n relatively prime
1988 # and n>0. Then for x**y to be exactly representable (at
1989 # *any* precision), xc must be the nth power of a positive
1990 # integer and xe must be divisible by n. If m is negative
1991 # then additionally xc must be a power of either 2 or 5, hence
1992 # a power of 2**n or 5**n.
1993 #
1994 # There's a limit to how small |y| can be: if y=m/n as above
1995 # then:
1996 #
1997 # (1) if xc != 1 then for the result to be representable we
1998 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1999 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
2000 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
2001 # representable.
2002 #
2003 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
2004 # |y| < 1/|xe| then the result is not representable.
2005 #
2006 # Note that since x is not equal to 1, at least one of (1) and
2007 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2008 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2009 #
2010 # There's also a limit to how large y can be, at least if it's
2011 # positive: the normalized result will have coefficient xc**y,
2012 # so if it's representable then xc**y < 10**p, and y <
2013 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
2014 # not exactly representable.
2015
2016 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2017 # so |y| < 1/xe and the result is not representable.
2018 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2019 # < 1/nbits(xc).
2020
2021 x = _WorkRep(self)
2022 xc, xe = x.int, x.exp
2023 while xc % 10 == 0:
2024 xc //= 10
2025 xe += 1
2026
2027 y = _WorkRep(other)
2028 yc, ye = y.int, y.exp
2029 while yc % 10 == 0:
2030 yc //= 10
2031 ye += 1
2032
2033 # case where xc == 1: result is 10**(xe*y), with xe*y
2034 # required to be an integer
2035 if xc == 1:
2036 if ye >= 0:
2037 exponent = xe*yc*10**ye
2038 else:
2039 exponent, remainder = divmod(xe*yc, 10**-ye)
2040 if remainder:
2041 return None
2042 if y.sign == 1:
2043 exponent = -exponent
2044 # if other is a nonnegative integer, use ideal exponent
2045 if other._isinteger() and other._sign == 0:
2046 ideal_exponent = self._exp*int(other)
2047 zeros = min(exponent-ideal_exponent, p-1)
2048 else:
2049 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002050 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002051
2052 # case where y is negative: xc must be either a power
2053 # of 2 or a power of 5.
2054 if y.sign == 1:
2055 last_digit = xc % 10
2056 if last_digit in (2,4,6,8):
2057 # quick test for power of 2
2058 if xc & -xc != xc:
2059 return None
2060 # now xc is a power of 2; e is its exponent
2061 e = _nbits(xc)-1
2062 # find e*y and xe*y; both must be integers
2063 if ye >= 0:
2064 y_as_int = yc*10**ye
2065 e = e*y_as_int
2066 xe = xe*y_as_int
2067 else:
2068 ten_pow = 10**-ye
2069 e, remainder = divmod(e*yc, ten_pow)
2070 if remainder:
2071 return None
2072 xe, remainder = divmod(xe*yc, ten_pow)
2073 if remainder:
2074 return None
2075
2076 if e*65 >= p*93: # 93/65 > log(10)/log(5)
2077 return None
2078 xc = 5**e
2079
2080 elif last_digit == 5:
2081 # e >= log_5(xc) if xc is a power of 5; we have
2082 # equality all the way up to xc=5**2658
2083 e = _nbits(xc)*28//65
2084 xc, remainder = divmod(5**e, xc)
2085 if remainder:
2086 return None
2087 while xc % 5 == 0:
2088 xc //= 5
2089 e -= 1
2090 if ye >= 0:
2091 y_as_integer = yc*10**ye
2092 e = e*y_as_integer
2093 xe = xe*y_as_integer
2094 else:
2095 ten_pow = 10**-ye
2096 e, remainder = divmod(e*yc, ten_pow)
2097 if remainder:
2098 return None
2099 xe, remainder = divmod(xe*yc, ten_pow)
2100 if remainder:
2101 return None
2102 if e*3 >= p*10: # 10/3 > log(10)/log(2)
2103 return None
2104 xc = 2**e
2105 else:
2106 return None
2107
2108 if xc >= 10**p:
2109 return None
2110 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002111 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002112
2113 # now y is positive; find m and n such that y = m/n
2114 if ye >= 0:
2115 m, n = yc*10**ye, 1
2116 else:
2117 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2118 return None
2119 xc_bits = _nbits(xc)
2120 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2121 return None
2122 m, n = yc, 10**(-ye)
2123 while m % 2 == n % 2 == 0:
2124 m //= 2
2125 n //= 2
2126 while m % 5 == n % 5 == 0:
2127 m //= 5
2128 n //= 5
2129
2130 # compute nth root of xc*10**xe
2131 if n > 1:
2132 # if 1 < xc < 2**n then xc isn't an nth power
2133 if xc != 1 and xc_bits <= n:
2134 return None
2135
2136 xe, rem = divmod(xe, n)
2137 if rem != 0:
2138 return None
2139
2140 # compute nth root of xc using Newton's method
2141 a = 1 << -(-_nbits(xc)//n) # initial estimate
2142 while True:
2143 q, r = divmod(xc, a**(n-1))
2144 if a <= q:
2145 break
2146 else:
2147 a = (a*(n-1) + q)//n
2148 if not (a == q and r == 0):
2149 return None
2150 xc = a
2151
2152 # now xc*10**xe is the nth root of the original xc*10**xe
2153 # compute mth power of xc*10**xe
2154
2155 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2156 # 10**p and the result is not representable.
2157 if xc > 1 and m > p*100//_log10_lb(xc):
2158 return None
2159 xc = xc**m
2160 xe *= m
2161 if xc > 10**p:
2162 return None
2163
2164 # by this point the result *is* exactly representable
2165 # adjust the exponent to get as close as possible to the ideal
2166 # exponent, if necessary
2167 str_xc = str(xc)
2168 if other._isinteger() and other._sign == 0:
2169 ideal_exponent = self._exp*int(other)
2170 zeros = min(xe-ideal_exponent, p-len(str_xc))
2171 else:
2172 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002173 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002174
2175 def __pow__(self, other, modulo=None, context=None):
2176 """Return self ** other [ % modulo].
2177
2178 With two arguments, compute self**other.
2179
2180 With three arguments, compute (self**other) % modulo. For the
2181 three argument form, the following restrictions on the
2182 arguments hold:
2183
2184 - all three arguments must be integral
2185 - other must be nonnegative
2186 - either self or other (or both) must be nonzero
2187 - modulo must be nonzero and must have at most p digits,
2188 where p is the context precision.
2189
2190 If any of these restrictions is violated the InvalidOperation
2191 flag is raised.
2192
2193 The result of pow(self, other, modulo) is identical to the
2194 result that would be obtained by computing (self**other) %
2195 modulo with unbounded precision, but is computed more
2196 efficiently. It is always exact.
2197 """
2198
2199 if modulo is not None:
2200 return self._power_modulo(other, modulo, context)
2201
2202 other = _convert_other(other)
2203 if other is NotImplemented:
2204 return other
2205
2206 if context is None:
2207 context = getcontext()
2208
2209 # either argument is a NaN => result is NaN
2210 ans = self._check_nans(other, context)
2211 if ans:
2212 return ans
2213
2214 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2215 if not other:
2216 if not self:
2217 return context._raise_error(InvalidOperation, '0 ** 0')
2218 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002219 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002220
2221 # result has sign 1 iff self._sign is 1 and other is an odd integer
2222 result_sign = 0
2223 if self._sign == 1:
2224 if other._isinteger():
2225 if not other._iseven():
2226 result_sign = 1
2227 else:
2228 # -ve**noninteger = NaN
2229 # (-0)**noninteger = 0**noninteger
2230 if self:
2231 return context._raise_error(InvalidOperation,
2232 'x ** y with x negative and y not an integer')
2233 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002234 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002235
2236 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2237 if not self:
2238 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002239 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002240 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002241 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002242
2243 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002244 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002245 if other._sign == 0:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002246 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002247 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002248 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002249
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002250 # 1**other = 1, but the choice of exponent and the flags
2251 # depend on the exponent of self, and on whether other is a
2252 # positive integer, a negative integer, or neither
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002253 if self == _One:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002254 if other._isinteger():
2255 # exp = max(self._exp*max(int(other), 0),
2256 # 1-context.prec) but evaluating int(other) directly
2257 # is dangerous until we know other is small (other
2258 # could be 1e999999999)
2259 if other._sign == 1:
2260 multiplier = 0
2261 elif other > context.prec:
2262 multiplier = context.prec
2263 else:
2264 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002265
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002266 exp = self._exp * multiplier
2267 if exp < 1-context.prec:
2268 exp = 1-context.prec
2269 context._raise_error(Rounded)
2270 else:
2271 context._raise_error(Inexact)
2272 context._raise_error(Rounded)
2273 exp = 1-context.prec
2274
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002275 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002276
2277 # compute adjusted exponent of self
2278 self_adj = self.adjusted()
2279
2280 # self ** infinity is infinity if self > 1, 0 if self < 1
2281 # self ** -infinity is infinity if self < 1, 0 if self > 1
2282 if other._isinfinity():
2283 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002284 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002285 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002286 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002287
2288 # from here on, the result always goes through the call
2289 # to _fix at the end of this function.
2290 ans = None
2291
2292 # crude test to catch cases of extreme overflow/underflow. If
2293 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2294 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2295 # self**other >= 10**(Emax+1), so overflow occurs. The test
2296 # for underflow is similar.
2297 bound = self._log10_exp_bound() + other.adjusted()
2298 if (self_adj >= 0) == (other._sign == 0):
2299 # self > 1 and other +ve, or self < 1 and other -ve
2300 # possibility of overflow
2301 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002302 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002303 else:
2304 # self > 1 and other -ve, or self < 1 and other +ve
2305 # possibility of underflow to 0
2306 Etiny = context.Etiny()
2307 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002308 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002309
2310 # try for an exact result with precision +1
2311 if ans is None:
2312 ans = self._power_exact(other, context.prec + 1)
2313 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002314 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002315
2316 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2317 if ans is None:
2318 p = context.prec
2319 x = _WorkRep(self)
2320 xc, xe = x.int, x.exp
2321 y = _WorkRep(other)
2322 yc, ye = y.int, y.exp
2323 if y.sign == 1:
2324 yc = -yc
2325
2326 # compute correctly rounded result: start with precision +3,
2327 # then increase precision until result is unambiguously roundable
2328 extra = 3
2329 while True:
2330 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2331 if coeff % (5*10**(len(str(coeff))-p-1)):
2332 break
2333 extra += 3
2334
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002335 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002336
2337 # the specification says that for non-integer other we need to
2338 # raise Inexact, even when the result is actually exact. In
2339 # the same way, we need to raise Underflow here if the result
2340 # is subnormal. (The call to _fix will take care of raising
2341 # Rounded and Subnormal, as usual.)
2342 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002343 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002344 # pad with zeros up to length context.prec+1 if necessary
2345 if len(ans._int) <= context.prec:
2346 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002347 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2348 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002349 if ans.adjusted() < context.Emin:
2350 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002351
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002352 # unlike exp, ln and log10, the power function respects the
2353 # rounding mode; no need to use ROUND_HALF_EVEN here
2354 ans = ans._fix(context)
2355 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002356
2357 def __rpow__(self, other, context=None):
2358 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002359 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002360 if other is NotImplemented:
2361 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002362 return other.__pow__(self, context=context)
2363
2364 def normalize(self, context=None):
2365 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002366
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002367 if context is None:
2368 context = getcontext()
2369
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002370 if self._is_special:
2371 ans = self._check_nans(context=context)
2372 if ans:
2373 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002374
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002375 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002376 if dup._isinfinity():
2377 return dup
2378
2379 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002380 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002381 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002382 end = len(dup._int)
2383 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002384 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002385 exp += 1
2386 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002387 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002388
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002389 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002390 """Quantize self so its exponent is the same as that of exp.
2391
2392 Similar to self._rescale(exp._exp) but with error checking.
2393 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002394 exp = _convert_other(exp, raiseit=True)
2395
2396 if context is None:
2397 context = getcontext()
2398 if rounding is None:
2399 rounding = context.rounding
2400
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002401 if self._is_special or exp._is_special:
2402 ans = self._check_nans(exp, context)
2403 if ans:
2404 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002405
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002406 if exp._isinfinity() or self._isinfinity():
2407 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002408 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002409 return context._raise_error(InvalidOperation,
2410 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002411
2412 # if we're not watching exponents, do a simple rescale
2413 if not watchexp:
2414 ans = self._rescale(exp._exp, rounding)
2415 # raise Inexact and Rounded where appropriate
2416 if ans._exp > self._exp:
2417 context._raise_error(Rounded)
2418 if ans != self:
2419 context._raise_error(Inexact)
2420 return ans
2421
2422 # exp._exp should be between Etiny and Emax
2423 if not (context.Etiny() <= exp._exp <= context.Emax):
2424 return context._raise_error(InvalidOperation,
2425 'target exponent out of bounds in quantize')
2426
2427 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002428 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002429 return ans._fix(context)
2430
2431 self_adjusted = self.adjusted()
2432 if self_adjusted > context.Emax:
2433 return context._raise_error(InvalidOperation,
2434 'exponent of quantize result too large for current context')
2435 if self_adjusted - exp._exp + 1 > context.prec:
2436 return context._raise_error(InvalidOperation,
2437 'quantize result has too many digits for current context')
2438
2439 ans = self._rescale(exp._exp, rounding)
2440 if ans.adjusted() > context.Emax:
2441 return context._raise_error(InvalidOperation,
2442 'exponent of quantize result too large for current context')
2443 if len(ans._int) > context.prec:
2444 return context._raise_error(InvalidOperation,
2445 'quantize result has too many digits for current context')
2446
2447 # raise appropriate flags
2448 if ans._exp > self._exp:
2449 context._raise_error(Rounded)
2450 if ans != self:
2451 context._raise_error(Inexact)
2452 if ans and ans.adjusted() < context.Emin:
2453 context._raise_error(Subnormal)
2454
2455 # call to fix takes care of any necessary folddown
2456 ans = ans._fix(context)
2457 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002458
2459 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002460 """Return True if self and other have the same exponent; otherwise
2461 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002462
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002463 If either operand is a special value, the following rules are used:
2464 * return True if both operands are infinities
2465 * return True if both operands are NaNs
2466 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002467 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002468 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002469 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002470 return (self.is_nan() and other.is_nan() or
2471 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002472 return self._exp == other._exp
2473
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002474 def _rescale(self, exp, rounding):
2475 """Rescale self so that the exponent is exp, either by padding with zeros
2476 or by truncating digits, using the given rounding mode.
2477
2478 Specials are returned without change. This operation is
2479 quiet: it raises no flags, and uses no information from the
2480 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002481
2482 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002483 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002484 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002485 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002486 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002487 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002488 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002489
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002490 if self._exp >= exp:
2491 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002492 return _dec_from_triple(self._sign,
2493 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002494
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002495 # too many digits; round and lose data. If self.adjusted() <
2496 # exp-1, replace self by 10**(exp-1) before rounding
2497 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002498 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002499 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002500 digits = 0
2501 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002502 changed = this_function(digits)
2503 coeff = self._int[:digits] or '0'
2504 if changed == 1:
2505 coeff = str(int(coeff)+1)
2506 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002507
Christian Heimesf16baeb2008-02-29 14:57:44 +00002508 def _round(self, places, rounding):
2509 """Round a nonzero, nonspecial Decimal to a fixed number of
2510 significant figures, using the given rounding mode.
2511
2512 Infinities, NaNs and zeros are returned unaltered.
2513
2514 This operation is quiet: it raises no flags, and uses no
2515 information from the context.
2516
2517 """
2518 if places <= 0:
2519 raise ValueError("argument should be at least 1 in _round")
2520 if self._is_special or not self:
2521 return Decimal(self)
2522 ans = self._rescale(self.adjusted()+1-places, rounding)
2523 # it can happen that the rescale alters the adjusted exponent;
2524 # for example when rounding 99.97 to 3 significant figures.
2525 # When this happens we end up with an extra 0 at the end of
2526 # the number; a second rescale fixes this.
2527 if ans.adjusted() != self.adjusted():
2528 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2529 return ans
2530
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002531 def to_integral_exact(self, rounding=None, context=None):
2532 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002533
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002534 If no rounding mode is specified, take the rounding mode from
2535 the context. This method raises the Rounded and Inexact flags
2536 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002537
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002538 See also: to_integral_value, which does exactly the same as
2539 this method except that it doesn't raise Inexact or Rounded.
2540 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002541 if self._is_special:
2542 ans = self._check_nans(context=context)
2543 if ans:
2544 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002545 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002546 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002547 return Decimal(self)
2548 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002549 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002550 if context is None:
2551 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002552 if rounding is None:
2553 rounding = context.rounding
2554 context._raise_error(Rounded)
2555 ans = self._rescale(0, rounding)
2556 if ans != self:
2557 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002558 return ans
2559
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002560 def to_integral_value(self, rounding=None, context=None):
2561 """Rounds to the nearest integer, without raising inexact, rounded."""
2562 if context is None:
2563 context = getcontext()
2564 if rounding is None:
2565 rounding = context.rounding
2566 if self._is_special:
2567 ans = self._check_nans(context=context)
2568 if ans:
2569 return ans
2570 return Decimal(self)
2571 if self._exp >= 0:
2572 return Decimal(self)
2573 else:
2574 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002575
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002576 # the method name changed, but we provide also the old one, for compatibility
2577 to_integral = to_integral_value
2578
2579 def sqrt(self, context=None):
2580 """Return the square root of self."""
Christian Heimes0348fb62008-03-26 12:55:56 +00002581 if context is None:
2582 context = getcontext()
2583
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002584 if self._is_special:
2585 ans = self._check_nans(context=context)
2586 if ans:
2587 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002588
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002589 if self._isinfinity() and self._sign == 0:
2590 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002591
2592 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002593 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002594 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002595 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002596
2597 if self._sign == 1:
2598 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2599
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002600 # At this point self represents a positive number. Let p be
2601 # the desired precision and express self in the form c*100**e
2602 # with c a positive real number and e an integer, c and e
2603 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2604 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2605 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2606 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2607 # the closest integer to sqrt(c) with the even integer chosen
2608 # in the case of a tie.
2609 #
2610 # To ensure correct rounding in all cases, we use the
2611 # following trick: we compute the square root to an extra
2612 # place (precision p+1 instead of precision p), rounding down.
2613 # Then, if the result is inexact and its last digit is 0 or 5,
2614 # we increase the last digit to 1 or 6 respectively; if it's
2615 # exact we leave the last digit alone. Now the final round to
2616 # p places (or fewer in the case of underflow) will round
2617 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002618
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002619 # use an extra digit of precision
2620 prec = context.prec+1
2621
2622 # write argument in the form c*100**e where e = self._exp//2
2623 # is the 'ideal' exponent, to be used if the square root is
2624 # exactly representable. l is the number of 'digits' of c in
2625 # base 100, so that 100**(l-1) <= c < 100**l.
2626 op = _WorkRep(self)
2627 e = op.exp >> 1
2628 if op.exp & 1:
2629 c = op.int * 10
2630 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002631 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002632 c = op.int
2633 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002634
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002635 # rescale so that c has exactly prec base 100 'digits'
2636 shift = prec-l
2637 if shift >= 0:
2638 c *= 100**shift
2639 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002640 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002641 c, remainder = divmod(c, 100**-shift)
2642 exact = not remainder
2643 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002644
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002645 # find n = floor(sqrt(c)) using Newton's method
2646 n = 10**prec
2647 while True:
2648 q = c//n
2649 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002650 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002651 else:
2652 n = n + q >> 1
2653 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002654
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002655 if exact:
2656 # result is exact; rescale to use ideal exponent e
2657 if shift >= 0:
2658 # assert n % 10**shift == 0
2659 n //= 10**shift
2660 else:
2661 n *= 10**-shift
2662 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002663 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002664 # result is not exact; fix last digit as described above
2665 if n % 5 == 0:
2666 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002667
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002668 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002669
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002670 # round, and fit to current context
2671 context = context._shallow_copy()
2672 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002673 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002674 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002675
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002676 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002677
2678 def max(self, other, context=None):
2679 """Returns the larger value.
2680
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002681 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002682 NaN (and signals if one is sNaN). Also rounds.
2683 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002684 other = _convert_other(other, raiseit=True)
2685
2686 if context is None:
2687 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002688
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002689 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002690 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002691 # number is always returned
2692 sn = self._isnan()
2693 on = other._isnan()
2694 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002695 if on == 1 and sn == 0:
2696 return self._fix(context)
2697 if sn == 1 and on == 0:
2698 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002699 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002700
Christian Heimes77c02eb2008-02-09 02:18:51 +00002701 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002702 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002703 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002704 # then an ordering is applied:
2705 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002706 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002707 # positive sign and min returns the operand with the negative sign
2708 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002709 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002710 # the result. This is exactly the ordering used in compare_total.
2711 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002712
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002713 if c == -1:
2714 ans = other
2715 else:
2716 ans = self
2717
Christian Heimes2c181612007-12-17 20:04:13 +00002718 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002719
2720 def min(self, other, context=None):
2721 """Returns the smaller value.
2722
Guido van Rossumd8faa362007-04-27 19:54:29 +00002723 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002724 NaN (and signals if one is sNaN). Also rounds.
2725 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002726 other = _convert_other(other, raiseit=True)
2727
2728 if context is None:
2729 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002730
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002731 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002732 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002733 # number is always returned
2734 sn = self._isnan()
2735 on = other._isnan()
2736 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002737 if on == 1 and sn == 0:
2738 return self._fix(context)
2739 if sn == 1 and on == 0:
2740 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002741 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002742
Christian Heimes77c02eb2008-02-09 02:18:51 +00002743 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002744 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002745 c = self.compare_total(other)
2746
2747 if c == -1:
2748 ans = self
2749 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002750 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002751
Christian Heimes2c181612007-12-17 20:04:13 +00002752 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002753
2754 def _isinteger(self):
2755 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002756 if self._is_special:
2757 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002758 if self._exp >= 0:
2759 return True
2760 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002761 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002762
2763 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002764 """Returns True if self is even. Assumes self is an integer."""
2765 if not self or self._exp > 0:
2766 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002767 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002768
2769 def adjusted(self):
2770 """Return the adjusted exponent of self"""
2771 try:
2772 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002773 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002774 except TypeError:
2775 return 0
2776
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002777 def canonical(self, context=None):
2778 """Returns the same Decimal object.
2779
2780 As we do not have different encodings for the same number, the
2781 received object already is in its canonical form.
2782 """
2783 return self
2784
2785 def compare_signal(self, other, context=None):
2786 """Compares self to the other operand numerically.
2787
2788 It's pretty much like compare(), but all NaNs signal, with signaling
2789 NaNs taking precedence over quiet NaNs.
2790 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002791 other = _convert_other(other, raiseit = True)
2792 ans = self._compare_check_nans(other, context)
2793 if ans:
2794 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002795 return self.compare(other, context=context)
2796
2797 def compare_total(self, other):
2798 """Compares self to other using the abstract representations.
2799
2800 This is not like the standard compare, which use their numerical
2801 value. Note that a total ordering is defined for all possible abstract
2802 representations.
2803 """
2804 # if one is negative and the other is positive, it's easy
2805 if self._sign and not other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002806 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002807 if not self._sign and other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002808 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002809 sign = self._sign
2810
2811 # let's handle both NaN types
2812 self_nan = self._isnan()
2813 other_nan = other._isnan()
2814 if self_nan or other_nan:
2815 if self_nan == other_nan:
2816 if self._int < other._int:
2817 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002818 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002819 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002820 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002821 if self._int > other._int:
2822 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002823 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002824 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002825 return _One
2826 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002827
2828 if sign:
2829 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002830 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002831 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002832 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002833 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002834 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002835 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002836 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002837 else:
2838 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002839 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002840 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002841 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002842 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002843 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002844 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002845 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002846
2847 if self < other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002848 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002849 if self > other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002850 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002851
2852 if self._exp < other._exp:
2853 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002854 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002855 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002856 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002857 if self._exp > other._exp:
2858 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002859 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002860 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002861 return _One
2862 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002863
2864
2865 def compare_total_mag(self, other):
2866 """Compares self to other using abstract repr., ignoring sign.
2867
2868 Like compare_total, but with operand's sign ignored and assumed to be 0.
2869 """
2870 s = self.copy_abs()
2871 o = other.copy_abs()
2872 return s.compare_total(o)
2873
2874 def copy_abs(self):
2875 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002876 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002877
2878 def copy_negate(self):
2879 """Returns a copy with the sign inverted."""
2880 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002881 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002882 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002883 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002884
2885 def copy_sign(self, other):
2886 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002887 return _dec_from_triple(other._sign, self._int,
2888 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002889
2890 def exp(self, context=None):
2891 """Returns e ** self."""
2892
2893 if context is None:
2894 context = getcontext()
2895
2896 # exp(NaN) = NaN
2897 ans = self._check_nans(context=context)
2898 if ans:
2899 return ans
2900
2901 # exp(-Infinity) = 0
2902 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002903 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002904
2905 # exp(0) = 1
2906 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002907 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002908
2909 # exp(Infinity) = Infinity
2910 if self._isinfinity() == 1:
2911 return Decimal(self)
2912
2913 # the result is now guaranteed to be inexact (the true
2914 # mathematical result is transcendental). There's no need to
2915 # raise Rounded and Inexact here---they'll always be raised as
2916 # a result of the call to _fix.
2917 p = context.prec
2918 adj = self.adjusted()
2919
2920 # we only need to do any computation for quite a small range
2921 # of adjusted exponents---for example, -29 <= adj <= 10 for
2922 # the default context. For smaller exponent the result is
2923 # indistinguishable from 1 at the given precision, while for
2924 # larger exponent the result either overflows or underflows.
2925 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2926 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002927 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002928 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2929 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002930 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002931 elif self._sign == 0 and adj < -p:
2932 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002933 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002934 elif self._sign == 1 and adj < -p-1:
2935 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002936 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002937 # general case
2938 else:
2939 op = _WorkRep(self)
2940 c, e = op.int, op.exp
2941 if op.sign == 1:
2942 c = -c
2943
2944 # compute correctly rounded result: increase precision by
2945 # 3 digits at a time until we get an unambiguously
2946 # roundable result
2947 extra = 3
2948 while True:
2949 coeff, exp = _dexp(c, e, p+extra)
2950 if coeff % (5*10**(len(str(coeff))-p-1)):
2951 break
2952 extra += 3
2953
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002954 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002955
2956 # at this stage, ans should round correctly with *any*
2957 # rounding mode, not just with ROUND_HALF_EVEN
2958 context = context._shallow_copy()
2959 rounding = context._set_rounding(ROUND_HALF_EVEN)
2960 ans = ans._fix(context)
2961 context.rounding = rounding
2962
2963 return ans
2964
2965 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002966 """Return True if self is canonical; otherwise return False.
2967
2968 Currently, the encoding of a Decimal instance is always
2969 canonical, so this method returns True for any Decimal.
2970 """
2971 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002972
2973 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002974 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002975
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002976 A Decimal instance is considered finite if it is neither
2977 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002978 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002979 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002980
2981 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002982 """Return True if self is infinite; otherwise return False."""
2983 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002984
2985 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002986 """Return True if self is a qNaN or sNaN; otherwise return False."""
2987 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002988
2989 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002990 """Return True if self is a normal number; otherwise return False."""
2991 if self._is_special or not self:
2992 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002993 if context is None:
2994 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002995 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002996
2997 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002998 """Return True if self is a quiet NaN; otherwise return False."""
2999 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003000
3001 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003002 """Return True if self is negative; otherwise return False."""
3003 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003004
3005 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003006 """Return True if self is a signaling NaN; otherwise return False."""
3007 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003008
3009 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003010 """Return True if self is subnormal; otherwise return False."""
3011 if self._is_special or not self:
3012 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003013 if context is None:
3014 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003015 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003016
3017 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003018 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003019 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003020
3021 def _ln_exp_bound(self):
3022 """Compute a lower bound for the adjusted exponent of self.ln().
3023 In other words, compute r such that self.ln() >= 10**r. Assumes
3024 that self is finite and positive and that self != 1.
3025 """
3026
3027 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
3028 adj = self._exp + len(self._int) - 1
3029 if adj >= 1:
3030 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
3031 return len(str(adj*23//10)) - 1
3032 if adj <= -2:
3033 # argument <= 0.1
3034 return len(str((-1-adj)*23//10)) - 1
3035 op = _WorkRep(self)
3036 c, e = op.int, op.exp
3037 if adj == 0:
3038 # 1 < self < 10
3039 num = str(c-10**-e)
3040 den = str(c)
3041 return len(num) - len(den) - (num < den)
3042 # adj == -1, 0.1 <= self < 1
3043 return e + len(str(10**-e - c)) - 1
3044
3045
3046 def ln(self, context=None):
3047 """Returns the natural (base e) logarithm of self."""
3048
3049 if context is None:
3050 context = getcontext()
3051
3052 # ln(NaN) = NaN
3053 ans = self._check_nans(context=context)
3054 if ans:
3055 return ans
3056
3057 # ln(0.0) == -Infinity
3058 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003059 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003060
3061 # ln(Infinity) = Infinity
3062 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003063 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003064
3065 # ln(1.0) == 0.0
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003066 if self == _One:
3067 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003068
3069 # ln(negative) raises InvalidOperation
3070 if self._sign == 1:
3071 return context._raise_error(InvalidOperation,
3072 'ln of a negative value')
3073
3074 # result is irrational, so necessarily inexact
3075 op = _WorkRep(self)
3076 c, e = op.int, op.exp
3077 p = context.prec
3078
3079 # correctly rounded result: repeatedly increase precision by 3
3080 # until we get an unambiguously roundable result
3081 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3082 while True:
3083 coeff = _dlog(c, e, places)
3084 # assert len(str(abs(coeff)))-p >= 1
3085 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3086 break
3087 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003088 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003089
3090 context = context._shallow_copy()
3091 rounding = context._set_rounding(ROUND_HALF_EVEN)
3092 ans = ans._fix(context)
3093 context.rounding = rounding
3094 return ans
3095
3096 def _log10_exp_bound(self):
3097 """Compute a lower bound for the adjusted exponent of self.log10().
3098 In other words, find r such that self.log10() >= 10**r.
3099 Assumes that self is finite and positive and that self != 1.
3100 """
3101
3102 # For x >= 10 or x < 0.1 we only need a bound on the integer
3103 # part of log10(self), and this comes directly from the
3104 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3105 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3106 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3107
3108 adj = self._exp + len(self._int) - 1
3109 if adj >= 1:
3110 # self >= 10
3111 return len(str(adj))-1
3112 if adj <= -2:
3113 # self < 0.1
3114 return len(str(-1-adj))-1
3115 op = _WorkRep(self)
3116 c, e = op.int, op.exp
3117 if adj == 0:
3118 # 1 < self < 10
3119 num = str(c-10**-e)
3120 den = str(231*c)
3121 return len(num) - len(den) - (num < den) + 2
3122 # adj == -1, 0.1 <= self < 1
3123 num = str(10**-e-c)
3124 return len(num) + e - (num < "231") - 1
3125
3126 def log10(self, context=None):
3127 """Returns the base 10 logarithm of self."""
3128
3129 if context is None:
3130 context = getcontext()
3131
3132 # log10(NaN) = NaN
3133 ans = self._check_nans(context=context)
3134 if ans:
3135 return ans
3136
3137 # log10(0.0) == -Infinity
3138 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003139 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003140
3141 # log10(Infinity) = Infinity
3142 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003143 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003144
3145 # log10(negative or -Infinity) raises InvalidOperation
3146 if self._sign == 1:
3147 return context._raise_error(InvalidOperation,
3148 'log10 of a negative value')
3149
3150 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003151 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003152 # answer may need rounding
3153 ans = Decimal(self._exp + len(self._int) - 1)
3154 else:
3155 # result is irrational, so necessarily inexact
3156 op = _WorkRep(self)
3157 c, e = op.int, op.exp
3158 p = context.prec
3159
3160 # correctly rounded result: repeatedly increase precision
3161 # until result is unambiguously roundable
3162 places = p-self._log10_exp_bound()+2
3163 while True:
3164 coeff = _dlog10(c, e, places)
3165 # assert len(str(abs(coeff)))-p >= 1
3166 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3167 break
3168 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003169 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003170
3171 context = context._shallow_copy()
3172 rounding = context._set_rounding(ROUND_HALF_EVEN)
3173 ans = ans._fix(context)
3174 context.rounding = rounding
3175 return ans
3176
3177 def logb(self, context=None):
3178 """ Returns the exponent of the magnitude of self's MSD.
3179
3180 The result is the integer which is the exponent of the magnitude
3181 of the most significant digit of self (as though it were truncated
3182 to a single digit while maintaining the value of that digit and
3183 without limiting the resulting exponent).
3184 """
3185 # logb(NaN) = NaN
3186 ans = self._check_nans(context=context)
3187 if ans:
3188 return ans
3189
3190 if context is None:
3191 context = getcontext()
3192
3193 # logb(+/-Inf) = +Inf
3194 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003195 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003196
3197 # logb(0) = -Inf, DivisionByZero
3198 if not self:
3199 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3200
3201 # otherwise, simply return the adjusted exponent of self, as a
3202 # Decimal. Note that no attempt is made to fit the result
3203 # into the current context.
3204 return Decimal(self.adjusted())
3205
3206 def _islogical(self):
3207 """Return True if self is a logical operand.
3208
Christian Heimes679db4a2008-01-18 09:56:22 +00003209 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003210 an exponent of 0, and a coefficient whose digits must all be
3211 either 0 or 1.
3212 """
3213 if self._sign != 0 or self._exp != 0:
3214 return False
3215 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003216 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003217 return False
3218 return True
3219
3220 def _fill_logical(self, context, opa, opb):
3221 dif = context.prec - len(opa)
3222 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003223 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003224 elif dif < 0:
3225 opa = opa[-context.prec:]
3226 dif = context.prec - len(opb)
3227 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003228 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003229 elif dif < 0:
3230 opb = opb[-context.prec:]
3231 return opa, opb
3232
3233 def logical_and(self, other, context=None):
3234 """Applies an 'and' operation between self and other's digits."""
3235 if context is None:
3236 context = getcontext()
3237 if not self._islogical() or not other._islogical():
3238 return context._raise_error(InvalidOperation)
3239
3240 # fill to context.prec
3241 (opa, opb) = self._fill_logical(context, self._int, other._int)
3242
3243 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003244 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3245 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003246
3247 def logical_invert(self, context=None):
3248 """Invert all its digits."""
3249 if context is None:
3250 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003251 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3252 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003253
3254 def logical_or(self, other, context=None):
3255 """Applies an 'or' operation between self and other's digits."""
3256 if context is None:
3257 context = getcontext()
3258 if not self._islogical() or not other._islogical():
3259 return context._raise_error(InvalidOperation)
3260
3261 # fill to context.prec
3262 (opa, opb) = self._fill_logical(context, self._int, other._int)
3263
3264 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003265 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003266 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003267
3268 def logical_xor(self, other, context=None):
3269 """Applies an 'xor' operation between self and other's digits."""
3270 if context is None:
3271 context = getcontext()
3272 if not self._islogical() or not other._islogical():
3273 return context._raise_error(InvalidOperation)
3274
3275 # fill to context.prec
3276 (opa, opb) = self._fill_logical(context, self._int, other._int)
3277
3278 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003279 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003280 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003281
3282 def max_mag(self, other, context=None):
3283 """Compares the values numerically with their sign ignored."""
3284 other = _convert_other(other, raiseit=True)
3285
3286 if context is None:
3287 context = getcontext()
3288
3289 if self._is_special or other._is_special:
3290 # If one operand is a quiet NaN and the other is number, then the
3291 # number is always returned
3292 sn = self._isnan()
3293 on = other._isnan()
3294 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003295 if on == 1 and sn == 0:
3296 return self._fix(context)
3297 if sn == 1 and on == 0:
3298 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003299 return self._check_nans(other, context)
3300
Christian Heimes77c02eb2008-02-09 02:18:51 +00003301 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003302 if c == 0:
3303 c = self.compare_total(other)
3304
3305 if c == -1:
3306 ans = other
3307 else:
3308 ans = self
3309
Christian Heimes2c181612007-12-17 20:04:13 +00003310 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003311
3312 def min_mag(self, other, context=None):
3313 """Compares the values numerically with their sign ignored."""
3314 other = _convert_other(other, raiseit=True)
3315
3316 if context is None:
3317 context = getcontext()
3318
3319 if self._is_special or other._is_special:
3320 # If one operand is a quiet NaN and the other is number, then the
3321 # number is always returned
3322 sn = self._isnan()
3323 on = other._isnan()
3324 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003325 if on == 1 and sn == 0:
3326 return self._fix(context)
3327 if sn == 1 and on == 0:
3328 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003329 return self._check_nans(other, context)
3330
Christian Heimes77c02eb2008-02-09 02:18:51 +00003331 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003332 if c == 0:
3333 c = self.compare_total(other)
3334
3335 if c == -1:
3336 ans = self
3337 else:
3338 ans = other
3339
Christian Heimes2c181612007-12-17 20:04:13 +00003340 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003341
3342 def next_minus(self, context=None):
3343 """Returns the largest representable number smaller than itself."""
3344 if context is None:
3345 context = getcontext()
3346
3347 ans = self._check_nans(context=context)
3348 if ans:
3349 return ans
3350
3351 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003352 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003353 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003354 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003355
3356 context = context.copy()
3357 context._set_rounding(ROUND_FLOOR)
3358 context._ignore_all_flags()
3359 new_self = self._fix(context)
3360 if new_self != self:
3361 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003362 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3363 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003364
3365 def next_plus(self, context=None):
3366 """Returns the smallest representable number larger than itself."""
3367 if context is None:
3368 context = getcontext()
3369
3370 ans = self._check_nans(context=context)
3371 if ans:
3372 return ans
3373
3374 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003375 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003376 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003377 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003378
3379 context = context.copy()
3380 context._set_rounding(ROUND_CEILING)
3381 context._ignore_all_flags()
3382 new_self = self._fix(context)
3383 if new_self != self:
3384 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003385 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3386 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003387
3388 def next_toward(self, other, context=None):
3389 """Returns the number closest to self, in the direction towards other.
3390
3391 The result is the closest representable number to self
3392 (excluding self) that is in the direction towards other,
3393 unless both have the same value. If the two operands are
3394 numerically equal, then the result is a copy of self with the
3395 sign set to be the same as the sign of other.
3396 """
3397 other = _convert_other(other, raiseit=True)
3398
3399 if context is None:
3400 context = getcontext()
3401
3402 ans = self._check_nans(other, context)
3403 if ans:
3404 return ans
3405
Christian Heimes77c02eb2008-02-09 02:18:51 +00003406 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003407 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003408 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003409
3410 if comparison == -1:
3411 ans = self.next_plus(context)
3412 else: # comparison == 1
3413 ans = self.next_minus(context)
3414
3415 # decide which flags to raise using value of ans
3416 if ans._isinfinity():
3417 context._raise_error(Overflow,
3418 'Infinite result from next_toward',
3419 ans._sign)
3420 context._raise_error(Rounded)
3421 context._raise_error(Inexact)
3422 elif ans.adjusted() < context.Emin:
3423 context._raise_error(Underflow)
3424 context._raise_error(Subnormal)
3425 context._raise_error(Rounded)
3426 context._raise_error(Inexact)
3427 # if precision == 1 then we don't raise Clamped for a
3428 # result 0E-Etiny.
3429 if not ans:
3430 context._raise_error(Clamped)
3431
3432 return ans
3433
3434 def number_class(self, context=None):
3435 """Returns an indication of the class of self.
3436
3437 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003438 sNaN
3439 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003440 -Infinity
3441 -Normal
3442 -Subnormal
3443 -Zero
3444 +Zero
3445 +Subnormal
3446 +Normal
3447 +Infinity
3448 """
3449 if self.is_snan():
3450 return "sNaN"
3451 if self.is_qnan():
3452 return "NaN"
3453 inf = self._isinfinity()
3454 if inf == 1:
3455 return "+Infinity"
3456 if inf == -1:
3457 return "-Infinity"
3458 if self.is_zero():
3459 if self._sign:
3460 return "-Zero"
3461 else:
3462 return "+Zero"
3463 if context is None:
3464 context = getcontext()
3465 if self.is_subnormal(context=context):
3466 if self._sign:
3467 return "-Subnormal"
3468 else:
3469 return "+Subnormal"
3470 # just a normal, regular, boring number, :)
3471 if self._sign:
3472 return "-Normal"
3473 else:
3474 return "+Normal"
3475
3476 def radix(self):
3477 """Just returns 10, as this is Decimal, :)"""
3478 return Decimal(10)
3479
3480 def rotate(self, other, context=None):
3481 """Returns a rotated copy of self, value-of-other times."""
3482 if context is None:
3483 context = getcontext()
3484
3485 ans = self._check_nans(other, context)
3486 if ans:
3487 return ans
3488
3489 if other._exp != 0:
3490 return context._raise_error(InvalidOperation)
3491 if not (-context.prec <= int(other) <= context.prec):
3492 return context._raise_error(InvalidOperation)
3493
3494 if self._isinfinity():
3495 return Decimal(self)
3496
3497 # get values, pad if necessary
3498 torot = int(other)
3499 rotdig = self._int
3500 topad = context.prec - len(rotdig)
3501 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003502 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003503
3504 # let's rotate!
3505 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003506 return _dec_from_triple(self._sign,
3507 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003508
3509 def scaleb (self, other, context=None):
3510 """Returns self operand after adding the second value to its exp."""
3511 if context is None:
3512 context = getcontext()
3513
3514 ans = self._check_nans(other, context)
3515 if ans:
3516 return ans
3517
3518 if other._exp != 0:
3519 return context._raise_error(InvalidOperation)
3520 liminf = -2 * (context.Emax + context.prec)
3521 limsup = 2 * (context.Emax + context.prec)
3522 if not (liminf <= int(other) <= limsup):
3523 return context._raise_error(InvalidOperation)
3524
3525 if self._isinfinity():
3526 return Decimal(self)
3527
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003528 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003529 d = d._fix(context)
3530 return d
3531
3532 def shift(self, other, context=None):
3533 """Returns a shifted copy of self, value-of-other times."""
3534 if context is None:
3535 context = getcontext()
3536
3537 ans = self._check_nans(other, context)
3538 if ans:
3539 return ans
3540
3541 if other._exp != 0:
3542 return context._raise_error(InvalidOperation)
3543 if not (-context.prec <= int(other) <= context.prec):
3544 return context._raise_error(InvalidOperation)
3545
3546 if self._isinfinity():
3547 return Decimal(self)
3548
3549 # get values, pad if necessary
3550 torot = int(other)
3551 if not torot:
3552 return Decimal(self)
3553 rotdig = self._int
3554 topad = context.prec - len(rotdig)
3555 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003556 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003557
3558 # let's shift!
3559 if torot < 0:
3560 rotated = rotdig[:torot]
3561 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003562 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003563 rotated = rotated[-context.prec:]
3564
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003565 return _dec_from_triple(self._sign,
3566 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003567
Guido van Rossumd8faa362007-04-27 19:54:29 +00003568 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003569 def __reduce__(self):
3570 return (self.__class__, (str(self),))
3571
3572 def __copy__(self):
3573 if type(self) == Decimal:
3574 return self # I'm immutable; therefore I am my own clone
3575 return self.__class__(str(self))
3576
3577 def __deepcopy__(self, memo):
3578 if type(self) == Decimal:
3579 return self # My components are also immutable
3580 return self.__class__(str(self))
3581
Christian Heimesf16baeb2008-02-29 14:57:44 +00003582 # PEP 3101 support. See also _parse_format_specifier and _format_align
3583 def __format__(self, specifier, context=None):
3584 """Format a Decimal instance according to the given specifier.
3585
3586 The specifier should be a standard format specifier, with the
3587 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3588 'F', 'g', 'G', and '%' are supported. If the formatting type
3589 is omitted it defaults to 'g' or 'G', depending on the value
3590 of context.capitals.
3591
3592 At this time the 'n' format specifier type (which is supposed
3593 to use the current locale) is not supported.
3594 """
3595
3596 # Note: PEP 3101 says that if the type is not present then
3597 # there should be at least one digit after the decimal point.
3598 # We take the liberty of ignoring this requirement for
3599 # Decimal---it's presumably there to make sure that
3600 # format(float, '') behaves similarly to str(float).
3601 if context is None:
3602 context = getcontext()
3603
3604 spec = _parse_format_specifier(specifier)
3605
3606 # special values don't care about the type or precision...
3607 if self._is_special:
3608 return _format_align(str(self), spec)
3609
3610 # a type of None defaults to 'g' or 'G', depending on context
3611 # if type is '%', adjust exponent of self accordingly
3612 if spec['type'] is None:
3613 spec['type'] = ['g', 'G'][context.capitals]
3614 elif spec['type'] == '%':
3615 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3616
3617 # round if necessary, taking rounding mode from the context
3618 rounding = context.rounding
3619 precision = spec['precision']
3620 if precision is not None:
3621 if spec['type'] in 'eE':
3622 self = self._round(precision+1, rounding)
3623 elif spec['type'] in 'gG':
3624 if len(self._int) > precision:
3625 self = self._round(precision, rounding)
3626 elif spec['type'] in 'fF%':
3627 self = self._rescale(-precision, rounding)
3628 # special case: zeros with a positive exponent can't be
3629 # represented in fixed point; rescale them to 0e0.
3630 elif not self and self._exp > 0 and spec['type'] in 'fF%':
3631 self = self._rescale(0, rounding)
3632
3633 # figure out placement of the decimal point
3634 leftdigits = self._exp + len(self._int)
3635 if spec['type'] in 'fF%':
3636 dotplace = leftdigits
3637 elif spec['type'] in 'eE':
3638 if not self and precision is not None:
3639 dotplace = 1 - precision
3640 else:
3641 dotplace = 1
3642 elif spec['type'] in 'gG':
3643 if self._exp <= 0 and leftdigits > -6:
3644 dotplace = leftdigits
3645 else:
3646 dotplace = 1
3647
3648 # figure out main part of numeric string...
3649 if dotplace <= 0:
3650 num = '0.' + '0'*(-dotplace) + self._int
3651 elif dotplace >= len(self._int):
3652 # make sure we're not padding a '0' with extra zeros on the right
3653 assert dotplace==len(self._int) or self._int != '0'
3654 num = self._int + '0'*(dotplace-len(self._int))
3655 else:
3656 num = self._int[:dotplace] + '.' + self._int[dotplace:]
3657
3658 # ...then the trailing exponent, or trailing '%'
3659 if leftdigits != dotplace or spec['type'] in 'eE':
3660 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3661 num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3662 elif spec['type'] == '%':
3663 num = num + '%'
3664
3665 # add sign
3666 if self._sign == 1:
3667 num = '-' + num
3668 return _format_align(num, spec)
3669
3670
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003671def _dec_from_triple(sign, coefficient, exponent, special=False):
3672 """Create a decimal instance directly, without any validation,
3673 normalization (e.g. removal of leading zeros) or argument
3674 conversion.
3675
3676 This function is for *internal use only*.
3677 """
3678
3679 self = object.__new__(Decimal)
3680 self._sign = sign
3681 self._int = coefficient
3682 self._exp = exponent
3683 self._is_special = special
3684
3685 return self
3686
Guido van Rossumd8faa362007-04-27 19:54:29 +00003687##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003688
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003689
3690# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003691rounding_functions = [name for name in Decimal.__dict__.keys()
3692 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003693for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003694 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003695 globalname = name[1:].upper()
3696 val = globals()[globalname]
3697 Decimal._pick_rounding_function[val] = name
3698
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003699del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003700
Thomas Wouters89f507f2006-12-13 04:49:30 +00003701class _ContextManager(object):
3702 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003703
Thomas Wouters89f507f2006-12-13 04:49:30 +00003704 Sets a copy of the supplied context in __enter__() and restores
3705 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003706 """
3707 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003708 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003709 def __enter__(self):
3710 self.saved_context = getcontext()
3711 setcontext(self.new_context)
3712 return self.new_context
3713 def __exit__(self, t, v, tb):
3714 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003715
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003716class Context(object):
3717 """Contains the context for a Decimal instance.
3718
3719 Contains:
3720 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003721 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003722 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003723 raised when it is caused. Otherwise, a value is
3724 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003725 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003726 (Whether or not the trap_enabler is set)
3727 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003728 Emin - Minimum exponent
3729 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003730 capitals - If 1, 1*10^1 is printed as 1E+1.
3731 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003732 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003733 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003734
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003735 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003736 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003737 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003738 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003739 _ignored_flags=None):
3740 if flags is None:
3741 flags = []
3742 if _ignored_flags is None:
3743 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003744 if not isinstance(flags, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003745 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003746 if traps is not None and not isinstance(traps, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003747 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003748 for name, val in locals().items():
3749 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003750 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003751 else:
3752 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003753 del self.self
3754
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003755 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003756 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003757 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003758 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3759 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3760 % vars(self))
3761 names = [f.__name__ for f, v in self.flags.items() if v]
3762 s.append('flags=[' + ', '.join(names) + ']')
3763 names = [t.__name__ for t, v in self.traps.items() if v]
3764 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003765 return ', '.join(s) + ')'
3766
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003767 def clear_flags(self):
3768 """Reset all flags to zero"""
3769 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003770 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003771
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003772 def _shallow_copy(self):
3773 """Returns a shallow copy from self."""
Christian Heimes2c181612007-12-17 20:04:13 +00003774 nc = Context(self.prec, self.rounding, self.traps,
3775 self.flags, self.Emin, self.Emax,
3776 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003777 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003778
3779 def copy(self):
3780 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003781 nc = Context(self.prec, self.rounding, self.traps.copy(),
Christian Heimes2c181612007-12-17 20:04:13 +00003782 self.flags.copy(), self.Emin, self.Emax,
3783 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003784 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003785 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003786
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003787 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003788 """Handles an error
3789
3790 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003791 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003792 trap_enabler is set, it reaises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00003793 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003794 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003795 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003796 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003797 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003798 return error().handle(self, *args)
3799
Raymond Hettinger86173da2008-02-01 20:38:12 +00003800 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003801 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003802 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003803 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003804
3805 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003806 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003807 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003808
3809 def _ignore_all_flags(self):
3810 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003811 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003812
3813 def _ignore_flags(self, *flags):
3814 """Ignore the flags, if they are raised"""
3815 # Do not mutate-- This way, copies of a context leave the original
3816 # alone.
3817 self._ignored_flags = (self._ignored_flags + list(flags))
3818 return list(flags)
3819
3820 def _regard_flags(self, *flags):
3821 """Stop ignoring the flags, if they are raised"""
3822 if flags and isinstance(flags[0], (tuple,list)):
3823 flags = flags[0]
3824 for flag in flags:
3825 self._ignored_flags.remove(flag)
3826
Nick Coghland1abd252008-07-15 15:46:38 +00003827 # We inherit object.__hash__, so we must deny this explicitly
3828 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003829
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003830 def Etiny(self):
3831 """Returns Etiny (= Emin - prec + 1)"""
3832 return int(self.Emin - self.prec + 1)
3833
3834 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003835 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003836 return int(self.Emax - self.prec + 1)
3837
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003838 def _set_rounding(self, type):
3839 """Sets the rounding type.
3840
3841 Sets the rounding type, and returns the current (previous)
3842 rounding type. Often used like:
3843
3844 context = context.copy()
3845 # so you don't change the calling context
3846 # if an error occurs in the middle.
3847 rounding = context._set_rounding(ROUND_UP)
3848 val = self.__sub__(other, context=context)
3849 context._set_rounding(rounding)
3850
3851 This will make it round up for that operation.
3852 """
3853 rounding = self.rounding
3854 self.rounding= type
3855 return rounding
3856
Raymond Hettingerfed52962004-07-14 15:41:57 +00003857 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00003858 """Creates a new Decimal instance but using self as context.
3859
3860 This method implements the to-number operation of the
3861 IBM Decimal specification."""
3862
3863 if isinstance(num, str) and num != num.strip():
3864 return self._raise_error(ConversionSyntax,
3865 "no trailing or leading whitespace is "
3866 "permitted.")
3867
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003868 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003869 if d._isnan() and len(d._int) > self.prec - self._clamp:
3870 return self._raise_error(ConversionSyntax,
3871 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003872 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003873
Raymond Hettinger771ed762009-01-03 19:20:32 +00003874 def create_decimal_from_float(self, f):
3875 """Creates a new Decimal instance from a float but rounding using self
3876 as the context.
3877
3878 >>> context = Context(prec=5, rounding=ROUND_DOWN)
3879 >>> context.create_decimal_from_float(3.1415926535897932)
3880 Decimal('3.1415')
3881 >>> context = Context(prec=5, traps=[Inexact])
3882 >>> context.create_decimal_from_float(3.1415926535897932)
3883 Traceback (most recent call last):
3884 ...
3885 decimal.Inexact: None
3886
3887 """
3888 d = Decimal.from_float(f) # An exact conversion
3889 return d._fix(self) # Apply the context rounding
3890
Guido van Rossumd8faa362007-04-27 19:54:29 +00003891 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003892 def abs(self, a):
3893 """Returns the absolute value of the operand.
3894
3895 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003896 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003897 the plus operation on the operand.
3898
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003899 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003900 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003901 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003902 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003903 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003904 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003905 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003906 Decimal('101.5')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003907 """
3908 return a.__abs__(context=self)
3909
3910 def add(self, a, b):
3911 """Return the sum of the two operands.
3912
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003913 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003914 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003915 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003916 Decimal('1.02E+4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003917 """
3918 return a.__add__(b, context=self)
3919
3920 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003921 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003922
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003923 def canonical(self, a):
3924 """Returns the same Decimal object.
3925
3926 As we do not have different encodings for the same number, the
3927 received object already is in its canonical form.
3928
3929 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003930 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003931 """
3932 return a.canonical(context=self)
3933
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003934 def compare(self, a, b):
3935 """Compares values numerically.
3936
3937 If the signs of the operands differ, a value representing each operand
3938 ('-1' if the operand is less than zero, '0' if the operand is zero or
3939 negative zero, or '1' if the operand is greater than zero) is used in
3940 place of that operand for the comparison instead of the actual
3941 operand.
3942
3943 The comparison is then effected by subtracting the second operand from
3944 the first and then returning a value according to the result of the
3945 subtraction: '-1' if the result is less than zero, '0' if the result is
3946 zero or negative zero, or '1' if the result is greater than zero.
3947
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003948 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003949 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003950 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003951 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003952 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003953 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003954 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003955 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003956 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003957 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003958 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003959 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003960 """
3961 return a.compare(b, context=self)
3962
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003963 def compare_signal(self, a, b):
3964 """Compares the values of the two operands numerically.
3965
3966 It's pretty much like compare(), but all NaNs signal, with signaling
3967 NaNs taking precedence over quiet NaNs.
3968
3969 >>> c = ExtendedContext
3970 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003971 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003972 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003973 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003974 >>> c.flags[InvalidOperation] = 0
3975 >>> print(c.flags[InvalidOperation])
3976 0
3977 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003978 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003979 >>> print(c.flags[InvalidOperation])
3980 1
3981 >>> c.flags[InvalidOperation] = 0
3982 >>> print(c.flags[InvalidOperation])
3983 0
3984 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003985 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003986 >>> print(c.flags[InvalidOperation])
3987 1
3988 """
3989 return a.compare_signal(b, context=self)
3990
3991 def compare_total(self, a, b):
3992 """Compares two operands using their abstract representation.
3993
3994 This is not like the standard compare, which use their numerical
3995 value. Note that a total ordering is defined for all possible abstract
3996 representations.
3997
3998 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003999 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004000 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004001 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004002 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004003 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004004 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004005 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004006 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004007 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004008 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004009 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004010 """
4011 return a.compare_total(b)
4012
4013 def compare_total_mag(self, a, b):
4014 """Compares two operands using their abstract representation ignoring sign.
4015
4016 Like compare_total, but with operand's sign ignored and assumed to be 0.
4017 """
4018 return a.compare_total_mag(b)
4019
4020 def copy_abs(self, a):
4021 """Returns a copy of the operand with the sign set to 0.
4022
4023 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004024 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004025 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004026 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004027 """
4028 return a.copy_abs()
4029
4030 def copy_decimal(self, a):
4031 """Returns a copy of the decimal objet.
4032
4033 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004034 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004035 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004036 Decimal('-1.00')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004037 """
4038 return Decimal(a)
4039
4040 def copy_negate(self, a):
4041 """Returns a copy of the operand with the sign inverted.
4042
4043 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004044 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004045 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004046 Decimal('101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004047 """
4048 return a.copy_negate()
4049
4050 def copy_sign(self, a, b):
4051 """Copies the second operand's sign to the first one.
4052
4053 In detail, it returns a copy of the first operand with the sign
4054 equal to the sign of the second operand.
4055
4056 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004057 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004058 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004059 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004060 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004061 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004062 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004063 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004064 """
4065 return a.copy_sign(b)
4066
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004067 def divide(self, a, b):
4068 """Decimal division in a specified context.
4069
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004070 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004071 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004072 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004073 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004074 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004075 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004076 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004077 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004078 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004079 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004080 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004081 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004082 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004083 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004084 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004085 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004086 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004087 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004088 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004089 Decimal('1.20E+6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004090 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00004091 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004092
4093 def divide_int(self, a, b):
4094 """Divides two numbers and returns the integer part of the result.
4095
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004096 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004097 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004098 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004099 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004100 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004101 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004102 """
4103 return a.__floordiv__(b, context=self)
4104
4105 def divmod(self, a, b):
4106 return a.__divmod__(b, context=self)
4107
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004108 def exp(self, a):
4109 """Returns e ** a.
4110
4111 >>> c = ExtendedContext.copy()
4112 >>> c.Emin = -999
4113 >>> c.Emax = 999
4114 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004115 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004116 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004117 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004118 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004119 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004120 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004121 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004122 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004123 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004124 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004125 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004126 """
4127 return a.exp(context=self)
4128
4129 def fma(self, a, b, c):
4130 """Returns a multiplied by b, plus c.
4131
4132 The first two operands are multiplied together, using multiply,
4133 the third operand is then added to the result of that
4134 multiplication, using add, all with only one final rounding.
4135
4136 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004137 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004138 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004139 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004140 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004141 Decimal('1.38435736E+12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004142 """
4143 return a.fma(b, c, context=self)
4144
4145 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004146 """Return True if the operand is canonical; otherwise return False.
4147
4148 Currently, the encoding of a Decimal instance is always
4149 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004150
4151 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004152 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004153 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004154 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004155
4156 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004157 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004158
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004159 A Decimal instance is considered finite if it is neither
4160 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004161
4162 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004163 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004164 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004165 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004166 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004167 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004168 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004169 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004170 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004171 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004172 """
4173 return a.is_finite()
4174
4175 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004176 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004177
4178 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004179 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004180 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004181 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004182 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004183 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004184 """
4185 return a.is_infinite()
4186
4187 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004188 """Return True if the operand is a qNaN or sNaN;
4189 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004190
4191 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004192 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004193 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004194 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004195 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004196 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004197 """
4198 return a.is_nan()
4199
4200 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004201 """Return True if the operand is a normal number;
4202 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004203
4204 >>> c = ExtendedContext.copy()
4205 >>> c.Emin = -999
4206 >>> c.Emax = 999
4207 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004208 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004209 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004210 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004211 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004212 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004213 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004214 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004215 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004216 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004217 """
4218 return a.is_normal(context=self)
4219
4220 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004221 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004222
4223 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004224 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004225 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004226 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004227 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004228 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004229 """
4230 return a.is_qnan()
4231
4232 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004233 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004234
4235 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004236 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004237 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004238 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004239 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004240 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004241 """
4242 return a.is_signed()
4243
4244 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004245 """Return True if the operand is a signaling NaN;
4246 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004247
4248 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004249 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004250 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004251 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004252 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004253 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004254 """
4255 return a.is_snan()
4256
4257 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004258 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004259
4260 >>> c = ExtendedContext.copy()
4261 >>> c.Emin = -999
4262 >>> c.Emax = 999
4263 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004264 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004265 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004266 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004267 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004268 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004269 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004270 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004271 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004272 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004273 """
4274 return a.is_subnormal(context=self)
4275
4276 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004277 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004278
4279 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004280 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004281 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004282 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004283 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004284 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004285 """
4286 return a.is_zero()
4287
4288 def ln(self, a):
4289 """Returns the natural (base e) logarithm of the operand.
4290
4291 >>> c = ExtendedContext.copy()
4292 >>> c.Emin = -999
4293 >>> c.Emax = 999
4294 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004295 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004296 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004297 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004298 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004299 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004300 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004301 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004302 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004303 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004304 """
4305 return a.ln(context=self)
4306
4307 def log10(self, a):
4308 """Returns the base 10 logarithm of the operand.
4309
4310 >>> c = ExtendedContext.copy()
4311 >>> c.Emin = -999
4312 >>> c.Emax = 999
4313 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004314 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004315 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004316 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004317 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004318 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004319 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004320 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004321 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004322 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004323 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004324 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004325 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004326 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004327 """
4328 return a.log10(context=self)
4329
4330 def logb(self, a):
4331 """ Returns the exponent of the magnitude of the operand's MSD.
4332
4333 The result is the integer which is the exponent of the magnitude
4334 of the most significant digit of the operand (as though the
4335 operand were truncated to a single digit while maintaining the
4336 value of that digit and without limiting the resulting exponent).
4337
4338 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004339 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004340 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004341 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004342 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004343 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004344 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004345 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004346 """
4347 return a.logb(context=self)
4348
4349 def logical_and(self, a, b):
4350 """Applies the logical operation 'and' between each operand's digits.
4351
4352 The operands must be both logical numbers.
4353
4354 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004355 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004356 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004357 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004358 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004359 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004360 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004361 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004362 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004363 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004364 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004365 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004366 """
4367 return a.logical_and(b, context=self)
4368
4369 def logical_invert(self, a):
4370 """Invert all the digits in the operand.
4371
4372 The operand must be a logical number.
4373
4374 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004375 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004376 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004377 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004378 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004379 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004380 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004381 Decimal('10101010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004382 """
4383 return a.logical_invert(context=self)
4384
4385 def logical_or(self, a, b):
4386 """Applies the logical operation 'or' between each operand's digits.
4387
4388 The operands must be both logical numbers.
4389
4390 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004391 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004392 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004393 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004394 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004395 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004396 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004397 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004398 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004399 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004400 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004401 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004402 """
4403 return a.logical_or(b, context=self)
4404
4405 def logical_xor(self, a, b):
4406 """Applies the logical operation 'xor' between each operand's digits.
4407
4408 The operands must be both logical numbers.
4409
4410 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004411 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004412 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004413 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004414 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004415 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004416 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004417 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004418 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004419 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004420 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004421 Decimal('1101')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004422 """
4423 return a.logical_xor(b, context=self)
4424
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004425 def max(self, a,b):
4426 """max compares two values numerically and returns the maximum.
4427
4428 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004429 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004430 operation. If they are numerically equal then the left-hand operand
4431 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004432 infinity) of the two operands is chosen as the result.
4433
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004434 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004435 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004436 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004437 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004438 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004439 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004440 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004441 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004442 """
4443 return a.max(b, context=self)
4444
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004445 def max_mag(self, a, b):
4446 """Compares the values numerically with their sign ignored."""
4447 return a.max_mag(b, context=self)
4448
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004449 def min(self, a,b):
4450 """min compares two values numerically and returns the minimum.
4451
4452 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004453 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004454 operation. If they are numerically equal then the left-hand operand
4455 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004456 infinity) of the two operands is chosen as the result.
4457
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004458 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004459 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004460 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004461 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004462 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004463 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004464 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004465 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004466 """
4467 return a.min(b, context=self)
4468
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004469 def min_mag(self, a, b):
4470 """Compares the values numerically with their sign ignored."""
4471 return a.min_mag(b, context=self)
4472
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004473 def minus(self, a):
4474 """Minus corresponds to unary prefix minus in Python.
4475
4476 The operation is evaluated using the same rules as subtract; the
4477 operation minus(a) is calculated as subtract('0', a) where the '0'
4478 has the same exponent as the operand.
4479
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004480 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004481 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004482 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004483 Decimal('1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004484 """
4485 return a.__neg__(context=self)
4486
4487 def multiply(self, a, b):
4488 """multiply multiplies two operands.
4489
4490 If either operand is a special value then the general rules apply.
4491 Otherwise, the operands are multiplied together ('long multiplication'),
4492 resulting in a number which may be as long as the sum of the lengths
4493 of the two operands.
4494
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004495 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004496 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004497 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004498 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004499 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004500 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004501 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004502 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004503 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004504 Decimal('4.28135971E+11')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004505 """
4506 return a.__mul__(b, context=self)
4507
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004508 def next_minus(self, a):
4509 """Returns the largest representable number smaller than a.
4510
4511 >>> c = ExtendedContext.copy()
4512 >>> c.Emin = -999
4513 >>> c.Emax = 999
4514 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004515 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004516 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004517 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004518 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004519 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004520 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004521 Decimal('9.99999999E+999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004522 """
4523 return a.next_minus(context=self)
4524
4525 def next_plus(self, a):
4526 """Returns the smallest representable number larger than a.
4527
4528 >>> c = ExtendedContext.copy()
4529 >>> c.Emin = -999
4530 >>> c.Emax = 999
4531 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004532 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004533 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004534 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004535 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004536 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004537 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004538 Decimal('-9.99999999E+999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004539 """
4540 return a.next_plus(context=self)
4541
4542 def next_toward(self, a, b):
4543 """Returns the number closest to a, in direction towards b.
4544
4545 The result is the closest representable number from the first
4546 operand (but not the first operand) that is in the direction
4547 towards the second operand, unless the operands have the same
4548 value.
4549
4550 >>> c = ExtendedContext.copy()
4551 >>> c.Emin = -999
4552 >>> c.Emax = 999
4553 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004554 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004555 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004556 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004557 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004558 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004559 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004560 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004561 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004562 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004563 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004564 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004565 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004566 Decimal('-0.00')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004567 """
4568 return a.next_toward(b, context=self)
4569
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004570 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004571 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004572
4573 Essentially a plus operation with all trailing zeros removed from the
4574 result.
4575
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004576 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004577 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004578 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004579 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004580 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004581 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004582 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004583 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004584 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004585 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004586 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004587 Decimal('0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004588 """
4589 return a.normalize(context=self)
4590
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004591 def number_class(self, a):
4592 """Returns an indication of the class of the operand.
4593
4594 The class is one of the following strings:
4595 -sNaN
4596 -NaN
4597 -Infinity
4598 -Normal
4599 -Subnormal
4600 -Zero
4601 +Zero
4602 +Subnormal
4603 +Normal
4604 +Infinity
4605
4606 >>> c = Context(ExtendedContext)
4607 >>> c.Emin = -999
4608 >>> c.Emax = 999
4609 >>> c.number_class(Decimal('Infinity'))
4610 '+Infinity'
4611 >>> c.number_class(Decimal('1E-10'))
4612 '+Normal'
4613 >>> c.number_class(Decimal('2.50'))
4614 '+Normal'
4615 >>> c.number_class(Decimal('0.1E-999'))
4616 '+Subnormal'
4617 >>> c.number_class(Decimal('0'))
4618 '+Zero'
4619 >>> c.number_class(Decimal('-0'))
4620 '-Zero'
4621 >>> c.number_class(Decimal('-0.1E-999'))
4622 '-Subnormal'
4623 >>> c.number_class(Decimal('-1E-10'))
4624 '-Normal'
4625 >>> c.number_class(Decimal('-2.50'))
4626 '-Normal'
4627 >>> c.number_class(Decimal('-Infinity'))
4628 '-Infinity'
4629 >>> c.number_class(Decimal('NaN'))
4630 'NaN'
4631 >>> c.number_class(Decimal('-NaN'))
4632 'NaN'
4633 >>> c.number_class(Decimal('sNaN'))
4634 'sNaN'
4635 """
4636 return a.number_class(context=self)
4637
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004638 def plus(self, a):
4639 """Plus corresponds to unary prefix plus in Python.
4640
4641 The operation is evaluated using the same rules as add; the
4642 operation plus(a) is calculated as add('0', a) where the '0'
4643 has the same exponent as the operand.
4644
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004645 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004646 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004647 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004648 Decimal('-1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004649 """
4650 return a.__pos__(context=self)
4651
4652 def power(self, a, b, modulo=None):
4653 """Raises a to the power of b, to modulo if given.
4654
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004655 With two arguments, compute a**b. If a is negative then b
4656 must be integral. The result will be inexact unless b is
4657 integral and the result is finite and can be expressed exactly
4658 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004659
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004660 With three arguments, compute (a**b) % modulo. For the
4661 three argument form, the following restrictions on the
4662 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004663
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004664 - all three arguments must be integral
4665 - b must be nonnegative
4666 - at least one of a or b must be nonzero
4667 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004668
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004669 The result of pow(a, b, modulo) is identical to the result
4670 that would be obtained by computing (a**b) % modulo with
4671 unbounded precision, but is computed more efficiently. It is
4672 always exact.
4673
4674 >>> c = ExtendedContext.copy()
4675 >>> c.Emin = -999
4676 >>> c.Emax = 999
4677 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004678 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004679 >>> c.power(Decimal('-2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004680 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004681 >>> c.power(Decimal('2'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004682 Decimal('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004683 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004684 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004685 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004686 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004687 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004688 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004689 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004690 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004691 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004692 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004693 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004694 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004695 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004696 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004697 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004698 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004699 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004700 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004701 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004702 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004703
4704 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004705 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004706 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004707 Decimal('-11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004708 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004709 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004710 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004711 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004712 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004713 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004714 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004715 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004716 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004717 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004718 """
4719 return a.__pow__(b, modulo, context=self)
4720
4721 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004722 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004723
4724 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004725 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004726 exponent is being increased), multiplied by a positive power of ten (if
4727 the exponent is being decreased), or is unchanged (if the exponent is
4728 already equal to that of the right-hand operand).
4729
4730 Unlike other operations, if the length of the coefficient after the
4731 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004732 operation condition is raised. This guarantees that, unless there is
4733 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004734 equal to that of the right-hand operand.
4735
4736 Also unlike other operations, quantize will never raise Underflow, even
4737 if the result is subnormal and inexact.
4738
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004739 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004740 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004741 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004742 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004743 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004744 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004745 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004746 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004747 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004748 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004749 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004750 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004751 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004752 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004753 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004754 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004755 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004756 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004757 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004758 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004759 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004760 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004761 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004762 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004763 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004764 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004765 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004766 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004767 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004768 Decimal('2E+2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004769 """
4770 return a.quantize(b, context=self)
4771
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004772 def radix(self):
4773 """Just returns 10, as this is Decimal, :)
4774
4775 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004776 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004777 """
4778 return Decimal(10)
4779
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004780 def remainder(self, a, b):
4781 """Returns the remainder from integer division.
4782
4783 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004784 calculating integer division as described for divide-integer, rounded
4785 to precision digits if necessary. The sign of the result, if
4786 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004787
4788 This operation will fail under the same conditions as integer division
4789 (that is, if integer division on the same two operands would fail, the
4790 remainder cannot be calculated).
4791
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004792 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004793 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004794 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004795 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004796 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004797 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004798 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004799 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004800 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004801 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004802 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004803 Decimal('1.0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004804 """
4805 return a.__mod__(b, context=self)
4806
4807 def remainder_near(self, a, b):
4808 """Returns to be "a - b * n", where n is the integer nearest the exact
4809 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004810 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004811 sign of a.
4812
4813 This operation will fail under the same conditions as integer division
4814 (that is, if integer division on the same two operands would fail, the
4815 remainder cannot be calculated).
4816
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004817 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004818 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004819 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004820 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004821 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004822 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004823 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004824 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004825 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004826 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004827 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004828 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004829 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004830 Decimal('-0.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004831 """
4832 return a.remainder_near(b, context=self)
4833
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004834 def rotate(self, a, b):
4835 """Returns a rotated copy of a, b times.
4836
4837 The coefficient of the result is a rotated copy of the digits in
4838 the coefficient of the first operand. The number of places of
4839 rotation is taken from the absolute value of the second operand,
4840 with the rotation being to the left if the second operand is
4841 positive or to the right otherwise.
4842
4843 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004844 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004845 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004846 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004847 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004848 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004849 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004850 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004851 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004852 Decimal('345678912')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004853 """
4854 return a.rotate(b, context=self)
4855
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004856 def same_quantum(self, a, b):
4857 """Returns True if the two operands have the same exponent.
4858
4859 The result is never affected by either the sign or the coefficient of
4860 either operand.
4861
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004862 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004863 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004864 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004865 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004866 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004867 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004868 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004869 True
4870 """
4871 return a.same_quantum(b)
4872
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004873 def scaleb (self, a, b):
4874 """Returns the first operand after adding the second value its exp.
4875
4876 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004877 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004878 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004879 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004880 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004881 Decimal('7.50E+3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004882 """
4883 return a.scaleb (b, context=self)
4884
4885 def shift(self, a, b):
4886 """Returns a shifted copy of a, b times.
4887
4888 The coefficient of the result is a shifted copy of the digits
4889 in the coefficient of the first operand. The number of places
4890 to shift is taken from the absolute value of the second operand,
4891 with the shift being to the left if the second operand is
4892 positive or to the right otherwise. Digits shifted into the
4893 coefficient are zeros.
4894
4895 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004896 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004897 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004898 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004899 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004900 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004901 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004902 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004903 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004904 Decimal('345678900')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004905 """
4906 return a.shift(b, context=self)
4907
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004908 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004909 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004910
4911 If the result must be inexact, it is rounded using the round-half-even
4912 algorithm.
4913
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004914 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004915 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004916 >>> ExtendedContext.sqrt(Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004917 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004918 >>> ExtendedContext.sqrt(Decimal('0.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004919 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004920 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004921 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004922 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004923 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004924 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004925 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004926 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004927 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004928 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004929 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004930 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004931 Decimal('3.16227766')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004932 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004933 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004934 """
4935 return a.sqrt(context=self)
4936
4937 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004938 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004939
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004940 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004941 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004942 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004943 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004944 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004945 Decimal('-0.77')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004946 """
4947 return a.__sub__(b, context=self)
4948
4949 def to_eng_string(self, a):
4950 """Converts a number to a string, using scientific notation.
4951
4952 The operation is not affected by the context.
4953 """
4954 return a.to_eng_string(context=self)
4955
4956 def to_sci_string(self, a):
4957 """Converts a number to a string, using scientific notation.
4958
4959 The operation is not affected by the context.
4960 """
4961 return a.__str__(context=self)
4962
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004963 def to_integral_exact(self, a):
4964 """Rounds to an integer.
4965
4966 When the operand has a negative exponent, the result is the same
4967 as using the quantize() operation using the given operand as the
4968 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4969 of the operand as the precision setting; Inexact and Rounded flags
4970 are allowed in this operation. The rounding mode is taken from the
4971 context.
4972
4973 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004974 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004975 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004976 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004977 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004978 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004979 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004980 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004981 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004982 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004983 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004984 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004985 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004986 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004987 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004988 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004989 """
4990 return a.to_integral_exact(context=self)
4991
4992 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004993 """Rounds to an integer.
4994
4995 When the operand has a negative exponent, the result is the same
4996 as using the quantize() operation using the given operand as the
4997 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4998 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004999 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005000
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005001 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005002 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005003 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005004 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005005 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005006 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005007 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005008 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005009 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005010 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005011 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005012 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005013 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005014 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005015 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005016 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005017 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005018 return a.to_integral_value(context=self)
5019
5020 # the method name changed, but we provide also the old one, for compatibility
5021 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005022
5023class _WorkRep(object):
5024 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005025 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005026 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005027 # exp: None, int, or string
5028
5029 def __init__(self, value=None):
5030 if value is None:
5031 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005032 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005033 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005034 elif isinstance(value, Decimal):
5035 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005036 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005037 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005038 else:
5039 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005040 self.sign = value[0]
5041 self.int = value[1]
5042 self.exp = value[2]
5043
5044 def __repr__(self):
5045 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5046
5047 __str__ = __repr__
5048
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005049
5050
Christian Heimes2c181612007-12-17 20:04:13 +00005051def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005052 """Normalizes op1, op2 to have the same exp and length of coefficient.
5053
5054 Done during addition.
5055 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005056 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005057 tmp = op2
5058 other = op1
5059 else:
5060 tmp = op1
5061 other = op2
5062
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005063 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5064 # Then adding 10**exp to tmp has the same effect (after rounding)
5065 # as adding any positive quantity smaller than 10**exp; similarly
5066 # for subtraction. So if other is smaller than 10**exp we replace
5067 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00005068 tmp_len = len(str(tmp.int))
5069 other_len = len(str(other.int))
5070 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5071 if other_len + other.exp - 1 < exp:
5072 other.int = 1
5073 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005074
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005075 tmp.int *= 10 ** (tmp.exp - other.exp)
5076 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005077 return op1, op2
5078
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005079##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005080
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005081# This function from Tim Peters was taken from here:
5082# http://mail.python.org/pipermail/python-list/1999-July/007758.html
5083# The correction being in the function definition is for speed, and
5084# the whole function is not resolved with math.log because of avoiding
5085# the use of floats.
5086def _nbits(n, correction = {
5087 '0': 4, '1': 3, '2': 2, '3': 2,
5088 '4': 1, '5': 1, '6': 1, '7': 1,
5089 '8': 0, '9': 0, 'a': 0, 'b': 0,
5090 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
5091 """Number of bits in binary representation of the positive integer n,
5092 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005093 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005094 if n < 0:
5095 raise ValueError("The argument to _nbits should be nonnegative.")
5096 hex_n = "%x" % n
5097 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005098
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005099def _sqrt_nearest(n, a):
5100 """Closest integer to the square root of the positive integer n. a is
5101 an initial approximation to the square root. Any positive integer
5102 will do for a, but the closer a is to the square root of n the
5103 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005104
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005105 """
5106 if n <= 0 or a <= 0:
5107 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5108
5109 b=0
5110 while a != b:
5111 b, a = a, a--n//a>>1
5112 return a
5113
5114def _rshift_nearest(x, shift):
5115 """Given an integer x and a nonnegative integer shift, return closest
5116 integer to x / 2**shift; use round-to-even in case of a tie.
5117
5118 """
5119 b, q = 1 << shift, x >> shift
5120 return q + (2*(x & (b-1)) + (q&1) > b)
5121
5122def _div_nearest(a, b):
5123 """Closest integer to a/b, a and b positive integers; rounds to even
5124 in the case of a tie.
5125
5126 """
5127 q, r = divmod(a, b)
5128 return q + (2*r + (q&1) > b)
5129
5130def _ilog(x, M, L = 8):
5131 """Integer approximation to M*log(x/M), with absolute error boundable
5132 in terms only of x/M.
5133
5134 Given positive integers x and M, return an integer approximation to
5135 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5136 between the approximation and the exact result is at most 22. For
5137 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5138 both cases these are upper bounds on the error; it will usually be
5139 much smaller."""
5140
5141 # The basic algorithm is the following: let log1p be the function
5142 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5143 # the reduction
5144 #
5145 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5146 #
5147 # repeatedly until the argument to log1p is small (< 2**-L in
5148 # absolute value). For small y we can use the Taylor series
5149 # expansion
5150 #
5151 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5152 #
5153 # truncating at T such that y**T is small enough. The whole
5154 # computation is carried out in a form of fixed-point arithmetic,
5155 # with a real number z being represented by an integer
5156 # approximation to z*M. To avoid loss of precision, the y below
5157 # is actually an integer approximation to 2**R*y*M, where R is the
5158 # number of reductions performed so far.
5159
5160 y = x-M
5161 # argument reduction; R = number of reductions performed
5162 R = 0
5163 while (R <= L and abs(y) << L-R >= M or
5164 R > L and abs(y) >> R-L >= M):
5165 y = _div_nearest((M*y) << 1,
5166 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5167 R += 1
5168
5169 # Taylor series with T terms
5170 T = -int(-10*len(str(M))//(3*L))
5171 yshift = _rshift_nearest(y, R)
5172 w = _div_nearest(M, T)
5173 for k in range(T-1, 0, -1):
5174 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5175
5176 return _div_nearest(w*y, M)
5177
5178def _dlog10(c, e, p):
5179 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5180 approximation to 10**p * log10(c*10**e), with an absolute error of
5181 at most 1. Assumes that c*10**e is not exactly 1."""
5182
5183 # increase precision by 2; compensate for this by dividing
5184 # final result by 100
5185 p += 2
5186
5187 # write c*10**e as d*10**f with either:
5188 # f >= 0 and 1 <= d <= 10, or
5189 # f <= 0 and 0.1 <= d <= 1.
5190 # Thus for c*10**e close to 1, f = 0
5191 l = len(str(c))
5192 f = e+l - (e+l >= 1)
5193
5194 if p > 0:
5195 M = 10**p
5196 k = e+p-f
5197 if k >= 0:
5198 c *= 10**k
5199 else:
5200 c = _div_nearest(c, 10**-k)
5201
5202 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005203 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005204 log_d = _div_nearest(log_d*M, log_10)
5205 log_tenpower = f*M # exact
5206 else:
5207 log_d = 0 # error < 2.31
Neal Norwitz2f99b242008-08-24 05:48:10 +00005208 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005209
5210 return _div_nearest(log_tenpower+log_d, 100)
5211
5212def _dlog(c, e, p):
5213 """Given integers c, e and p with c > 0, compute an integer
5214 approximation to 10**p * log(c*10**e), with an absolute error of
5215 at most 1. Assumes that c*10**e is not exactly 1."""
5216
5217 # Increase precision by 2. The precision increase is compensated
5218 # for at the end with a division by 100.
5219 p += 2
5220
5221 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5222 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5223 # as 10**p * log(d) + 10**p*f * log(10).
5224 l = len(str(c))
5225 f = e+l - (e+l >= 1)
5226
5227 # compute approximation to 10**p*log(d), with error < 27
5228 if p > 0:
5229 k = e+p-f
5230 if k >= 0:
5231 c *= 10**k
5232 else:
5233 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5234
5235 # _ilog magnifies existing error in c by a factor of at most 10
5236 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5237 else:
5238 # p <= 0: just approximate the whole thing by 0; error < 2.31
5239 log_d = 0
5240
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005241 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005242 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005243 extra = len(str(abs(f)))-1
5244 if p + extra >= 0:
5245 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5246 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5247 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005248 else:
5249 f_log_ten = 0
5250 else:
5251 f_log_ten = 0
5252
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005253 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005254 return _div_nearest(f_log_ten + log_d, 100)
5255
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005256class _Log10Memoize(object):
5257 """Class to compute, store, and allow retrieval of, digits of the
5258 constant log(10) = 2.302585.... This constant is needed by
5259 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5260 def __init__(self):
5261 self.digits = "23025850929940456840179914546843642076011014886"
5262
5263 def getdigits(self, p):
5264 """Given an integer p >= 0, return floor(10**p)*log(10).
5265
5266 For example, self.getdigits(3) returns 2302.
5267 """
5268 # digits are stored as a string, for quick conversion to
5269 # integer in the case that we've already computed enough
5270 # digits; the stored digits should always be correct
5271 # (truncated, not rounded to nearest).
5272 if p < 0:
5273 raise ValueError("p should be nonnegative")
5274
5275 if p >= len(self.digits):
5276 # compute p+3, p+6, p+9, ... digits; continue until at
5277 # least one of the extra digits is nonzero
5278 extra = 3
5279 while True:
5280 # compute p+extra digits, correct to within 1ulp
5281 M = 10**(p+extra+2)
5282 digits = str(_div_nearest(_ilog(10*M, M), 100))
5283 if digits[-extra:] != '0'*extra:
5284 break
5285 extra += 3
5286 # keep all reliable digits so far; remove trailing zeros
5287 # and next nonzero digit
5288 self.digits = digits.rstrip('0')[:-1]
5289 return int(self.digits[:p+1])
5290
5291_log10_digits = _Log10Memoize().getdigits
5292
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005293def _iexp(x, M, L=8):
5294 """Given integers x and M, M > 0, such that x/M is small in absolute
5295 value, compute an integer approximation to M*exp(x/M). For 0 <=
5296 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5297 is usually much smaller)."""
5298
5299 # Algorithm: to compute exp(z) for a real number z, first divide z
5300 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5301 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5302 # series
5303 #
5304 # expm1(x) = x + x**2/2! + x**3/3! + ...
5305 #
5306 # Now use the identity
5307 #
5308 # expm1(2x) = expm1(x)*(expm1(x)+2)
5309 #
5310 # R times to compute the sequence expm1(z/2**R),
5311 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5312
5313 # Find R such that x/2**R/M <= 2**-L
5314 R = _nbits((x<<L)//M)
5315
5316 # Taylor series. (2**L)**T > M
5317 T = -int(-10*len(str(M))//(3*L))
5318 y = _div_nearest(x, T)
5319 Mshift = M<<R
5320 for i in range(T-1, 0, -1):
5321 y = _div_nearest(x*(Mshift + y), Mshift * i)
5322
5323 # Expansion
5324 for k in range(R-1, -1, -1):
5325 Mshift = M<<(k+2)
5326 y = _div_nearest(y*(y+Mshift), Mshift)
5327
5328 return M+y
5329
5330def _dexp(c, e, p):
5331 """Compute an approximation to exp(c*10**e), with p decimal places of
5332 precision.
5333
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005334 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005335
5336 10**(p-1) <= d <= 10**p, and
5337 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5338
5339 In other words, d*10**f is an approximation to exp(c*10**e) with p
5340 digits of precision, and with an error in d of at most 1. This is
5341 almost, but not quite, the same as the error being < 1ulp: when d
5342 = 10**(p-1) the error could be up to 10 ulp."""
5343
5344 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5345 p += 2
5346
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005347 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005348 extra = max(0, e + len(str(c)) - 1)
5349 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005350
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005351 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005352 # rounding down
5353 shift = e+q
5354 if shift >= 0:
5355 cshift = c*10**shift
5356 else:
5357 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005358 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005359
5360 # reduce remainder back to original precision
5361 rem = _div_nearest(rem, 10**extra)
5362
5363 # error in result of _iexp < 120; error after division < 0.62
5364 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5365
5366def _dpower(xc, xe, yc, ye, p):
5367 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5368 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5369
5370 10**(p-1) <= c <= 10**p, and
5371 (c-1)*10**e < x**y < (c+1)*10**e
5372
5373 in other words, c*10**e is an approximation to x**y with p digits
5374 of precision, and with an error in c of at most 1. (This is
5375 almost, but not quite, the same as the error being < 1ulp: when c
5376 == 10**(p-1) we can only guarantee error < 10ulp.)
5377
5378 We assume that: x is positive and not equal to 1, and y is nonzero.
5379 """
5380
5381 # Find b such that 10**(b-1) <= |y| <= 10**b
5382 b = len(str(abs(yc))) + ye
5383
5384 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5385 lxc = _dlog(xc, xe, p+b+1)
5386
5387 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5388 shift = ye-b
5389 if shift >= 0:
5390 pc = lxc*yc*10**shift
5391 else:
5392 pc = _div_nearest(lxc*yc, 10**-shift)
5393
5394 if pc == 0:
5395 # we prefer a result that isn't exactly 1; this makes it
5396 # easier to compute a correctly rounded result in __pow__
5397 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5398 coeff, exp = 10**(p-1)+1, 1-p
5399 else:
5400 coeff, exp = 10**p-1, -p
5401 else:
5402 coeff, exp = _dexp(pc, -(p+1), p+1)
5403 coeff = _div_nearest(coeff, 10)
5404 exp += 1
5405
5406 return coeff, exp
5407
5408def _log10_lb(c, correction = {
5409 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5410 '6': 23, '7': 16, '8': 10, '9': 5}):
5411 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5412 if c <= 0:
5413 raise ValueError("The argument to _log10_lb should be nonnegative.")
5414 str_c = str(c)
5415 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005416
Guido van Rossumd8faa362007-04-27 19:54:29 +00005417##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005418
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005419def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005420 """Convert other to Decimal.
5421
5422 Verifies that it's ok to use in an implicit construction.
5423 """
5424 if isinstance(other, Decimal):
5425 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005426 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005427 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005428 if raiseit:
5429 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005430 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005431
Guido van Rossumd8faa362007-04-27 19:54:29 +00005432##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005433
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005434# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005435# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005436
5437DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005438 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005439 traps=[DivisionByZero, Overflow, InvalidOperation],
5440 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005441 Emax=999999999,
5442 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005443 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005444)
5445
5446# Pre-made alternate contexts offered by the specification
5447# Don't change these; the user should be able to select these
5448# contexts and be able to reproduce results from other implementations
5449# of the spec.
5450
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005451BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005452 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005453 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5454 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005455)
5456
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005457ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005458 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005459 traps=[],
5460 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005461)
5462
5463
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005464##### crud for parsing strings #############################################
Christian Heimes23daade02008-02-25 12:39:23 +00005465#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005466# Regular expression used for parsing numeric strings. Additional
5467# comments:
5468#
5469# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5470# whitespace. But note that the specification disallows whitespace in
5471# a numeric string.
5472#
5473# 2. For finite numbers (not infinities and NaNs) the body of the
5474# number between the optional sign and the optional exponent must have
5475# at least one decimal digit, possibly after the decimal point. The
Antoine Pitroufd036452008-08-19 17:56:33 +00005476# lookahead expression '(?=[0-9]|\.[0-9])' checks this.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005477#
5478# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5479# other meaning for \d than the numbers [0-9].
5480
5481import re
Benjamin Peterson41181742008-07-02 20:22:54 +00005482_parser = re.compile(r""" # A numeric string consists of:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005483# \s*
Benjamin Peterson41181742008-07-02 20:22:54 +00005484 (?P<sign>[-+])? # an optional sign, followed by either...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005485 (
Benjamin Peterson41181742008-07-02 20:22:54 +00005486 (?=[0-9]|\.[0-9]) # ...a number (with at least one digit)
5487 (?P<int>[0-9]*) # having a (possibly empty) integer part
5488 (\.(?P<frac>[0-9]*))? # followed by an optional fractional part
5489 (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005490 |
Benjamin Peterson41181742008-07-02 20:22:54 +00005491 Inf(inity)? # ...an infinity, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005492 |
Benjamin Peterson41181742008-07-02 20:22:54 +00005493 (?P<signal>s)? # ...an (optionally signaling)
5494 NaN # NaN
5495 (?P<diag>[0-9]*) # with (possibly empty) diagnostic info.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005496 )
5497# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00005498 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005499""", re.VERBOSE | re.IGNORECASE).match
5500
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005501_all_zeros = re.compile('0*$').match
5502_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00005503
5504##### PEP3101 support functions ##############################################
5505# The functions parse_format_specifier and format_align have little to do
5506# with the Decimal class, and could potentially be reused for other pure
5507# Python numeric classes that want to implement __format__
5508#
5509# A format specifier for Decimal looks like:
5510#
5511# [[fill]align][sign][0][minimumwidth][.precision][type]
5512#
5513
5514_parse_format_specifier_regex = re.compile(r"""\A
5515(?:
5516 (?P<fill>.)?
5517 (?P<align>[<>=^])
5518)?
5519(?P<sign>[-+ ])?
5520(?P<zeropad>0)?
5521(?P<minimumwidth>(?!0)\d+)?
5522(?:\.(?P<precision>0|(?!0)\d+))?
5523(?P<type>[eEfFgG%])?
5524\Z
5525""", re.VERBOSE)
5526
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005527del re
5528
Christian Heimesf16baeb2008-02-29 14:57:44 +00005529def _parse_format_specifier(format_spec):
5530 """Parse and validate a format specifier.
5531
5532 Turns a standard numeric format specifier into a dict, with the
5533 following entries:
5534
5535 fill: fill character to pad field to minimum width
5536 align: alignment type, either '<', '>', '=' or '^'
5537 sign: either '+', '-' or ' '
5538 minimumwidth: nonnegative integer giving minimum width
5539 precision: nonnegative integer giving precision, or None
5540 type: one of the characters 'eEfFgG%', or None
5541 unicode: either True or False (always True for Python 3.x)
5542
5543 """
5544 m = _parse_format_specifier_regex.match(format_spec)
5545 if m is None:
5546 raise ValueError("Invalid format specifier: " + format_spec)
5547
5548 # get the dictionary
5549 format_dict = m.groupdict()
5550
5551 # defaults for fill and alignment
5552 fill = format_dict['fill']
5553 align = format_dict['align']
5554 if format_dict.pop('zeropad') is not None:
5555 # in the face of conflict, refuse the temptation to guess
5556 if fill is not None and fill != '0':
5557 raise ValueError("Fill character conflicts with '0'"
5558 " in format specifier: " + format_spec)
5559 if align is not None and align != '=':
5560 raise ValueError("Alignment conflicts with '0' in "
5561 "format specifier: " + format_spec)
5562 fill = '0'
5563 align = '='
5564 format_dict['fill'] = fill or ' '
5565 format_dict['align'] = align or '<'
5566
5567 if format_dict['sign'] is None:
5568 format_dict['sign'] = '-'
5569
5570 # turn minimumwidth and precision entries into integers.
5571 # minimumwidth defaults to 0; precision remains None if not given
5572 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5573 if format_dict['precision'] is not None:
5574 format_dict['precision'] = int(format_dict['precision'])
5575
5576 # if format type is 'g' or 'G' then a precision of 0 makes little
5577 # sense; convert it to 1. Same if format type is unspecified.
5578 if format_dict['precision'] == 0:
5579 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5580 format_dict['precision'] = 1
5581
5582 # record whether return type should be str or unicode
Christian Heimes295f4fa2008-02-29 15:03:39 +00005583 format_dict['unicode'] = True
Christian Heimesf16baeb2008-02-29 14:57:44 +00005584
5585 return format_dict
5586
5587def _format_align(body, spec_dict):
5588 """Given an unpadded, non-aligned numeric string, add padding and
5589 aligment to conform with the given format specifier dictionary (as
5590 output from parse_format_specifier).
5591
5592 It's assumed that if body is negative then it starts with '-'.
5593 Any leading sign ('-' or '+') is stripped from the body before
5594 applying the alignment and padding rules, and replaced in the
5595 appropriate position.
5596
5597 """
5598 # figure out the sign; we only examine the first character, so if
5599 # body has leading whitespace the results may be surprising.
5600 if len(body) > 0 and body[0] in '-+':
5601 sign = body[0]
5602 body = body[1:]
5603 else:
5604 sign = ''
5605
5606 if sign != '-':
5607 if spec_dict['sign'] in ' +':
5608 sign = spec_dict['sign']
5609 else:
5610 sign = ''
5611
5612 # how much extra space do we have to play with?
5613 minimumwidth = spec_dict['minimumwidth']
5614 fill = spec_dict['fill']
5615 padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5616
5617 align = spec_dict['align']
5618 if align == '<':
5619 result = padding + sign + body
5620 elif align == '>':
5621 result = sign + body + padding
5622 elif align == '=':
5623 result = sign + padding + body
5624 else: #align == '^'
5625 half = len(padding)//2
5626 result = padding[:half] + sign + body + padding[half:]
5627
Christian Heimesf16baeb2008-02-29 14:57:44 +00005628 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005629
Guido van Rossumd8faa362007-04-27 19:54:29 +00005630##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005631
Guido van Rossumd8faa362007-04-27 19:54:29 +00005632# Reusable defaults
Mark Dickinson627cf6a2009-01-03 12:11:47 +00005633_Infinity = Decimal('Inf')
5634_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonf9236412009-01-02 23:23:21 +00005635_NaN = Decimal('NaN')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00005636_Zero = Decimal(0)
5637_One = Decimal(1)
5638_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005639
Mark Dickinson627cf6a2009-01-03 12:11:47 +00005640# _SignedInfinity[sign] is infinity w/ that sign
5641_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005642
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005643
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005644
5645if __name__ == '__main__':
5646 import doctest, sys
5647 doctest.testmod(sys.modules[__name__])