blob: ab38ed4ef0b2d69f84d8409d3f41975c6caa0c37 [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
Facundo Batista6ab24792009-02-16 15:41:37 +000010# This module should be kept in sync with the latest updates of the
11# IBM specification as it evolves. Those updates will be treated
Raymond Hettinger27dbcf22004-08-19 22:39:55 +000012# as bug fixes (deviation from the spec is a compatibility, usability
13# bug) and will be backported. At this point the spec is stabilizing
14# and the updates are becoming fewer, smaller, and less significant.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000015
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000016"""
Facundo Batista6ab24792009-02-16 15:41:37 +000017This is an implementation of decimal floating point arithmetic based on
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000018the General Decimal Arithmetic Specification:
19
Raymond Hettinger960dc362009-04-21 03:43:15 +000020 http://speleotrove.com/decimal/decarith.html
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000021
Raymond Hettinger0ea241e2004-07-04 13:53:24 +000022and IEEE standard 854-1987:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000023
24 www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
25
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000026Decimal floating point has finite precision with arbitrarily large bounds.
27
Guido van Rossumd8faa362007-04-27 19:54:29 +000028The purpose of this module is to support arithmetic using familiar
29"schoolhouse" rules and to avoid some of the tricky representation
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000030issues associated with binary floating point. The package is especially
31useful for financial applications or for contexts where users have
32expectations that are at odds with binary floating point (for instance,
33in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
Christian Heimes68f5fbe2008-02-14 08:27:37 +000034of the expected Decimal('0.00') returned by decimal floating point).
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000035
36Here are some examples of using the decimal module:
37
38>>> from decimal import *
Raymond Hettingerbd7f76d2004-07-08 00:49:18 +000039>>> setcontext(ExtendedContext)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000040>>> Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000041Decimal('0')
42>>> Decimal('1')
43Decimal('1')
44>>> Decimal('-.0123')
45Decimal('-0.0123')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000046>>> Decimal(123456)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000047Decimal('123456')
48>>> Decimal('123.45e12345678901234567890')
49Decimal('1.2345E+12345678901234567892')
50>>> Decimal('1.33') + Decimal('1.27')
51Decimal('2.60')
52>>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
53Decimal('-2.20')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000054>>> dig = Decimal(1)
Guido van Rossum7131f842007-02-09 20:13:25 +000055>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000560.333333333
57>>> getcontext().prec = 18
Guido van Rossum7131f842007-02-09 20:13:25 +000058>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000590.333333333333333333
Guido van Rossum7131f842007-02-09 20:13:25 +000060>>> print(dig.sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000611
Guido van Rossum7131f842007-02-09 20:13:25 +000062>>> print(Decimal(3).sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000631.73205080756887729
Guido van Rossum7131f842007-02-09 20:13:25 +000064>>> print(Decimal(3) ** 123)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000654.85192780976896427E+58
66>>> inf = Decimal(1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000067>>> print(inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000068Infinity
69>>> neginf = Decimal(-1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000070>>> print(neginf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000071-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000072>>> print(neginf + inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000073NaN
Guido van Rossum7131f842007-02-09 20:13:25 +000074>>> print(neginf * inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000075-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000076>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000077Infinity
Raymond Hettingerbf440692004-07-10 14:14:37 +000078>>> getcontext().traps[DivisionByZero] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000079>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000080Traceback (most recent call last):
81 ...
82 ...
83 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +000084decimal.DivisionByZero: x / 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000085>>> c = Context()
Raymond Hettingerbf440692004-07-10 14:14:37 +000086>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000087>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000880
89>>> c.divide(Decimal(0), Decimal(0))
Christian Heimes68f5fbe2008-02-14 08:27:37 +000090Decimal('NaN')
Raymond Hettingerbf440692004-07-10 14:14:37 +000091>>> c.traps[InvalidOperation] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000092>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000931
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000094>>> c.flags[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000095>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000960
Guido van Rossum7131f842007-02-09 20:13:25 +000097>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000098Traceback (most recent call last):
99 ...
100 ...
101 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +0000102decimal.InvalidOperation: 0 / 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000103>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001041
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000105>>> c.flags[InvalidOperation] = 0
Raymond Hettingerbf440692004-07-10 14:14:37 +0000106>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000107>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000108NaN
Guido van Rossum7131f842007-02-09 20:13:25 +0000109>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001101
111>>>
112"""
113
114__all__ = [
115 # Two major classes
116 'Decimal', 'Context',
117
118 # Contexts
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +0000119 'DefaultContext', 'BasicContext', 'ExtendedContext',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000120
121 # Exceptions
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +0000122 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
123 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000124
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000125 # Constants for use in setting up contexts
126 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000127 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000128
129 # Functions for manipulating contexts
Thomas Wouters89f507f2006-12-13 04:49:30 +0000130 'setcontext', 'getcontext', 'localcontext'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000131]
132
Raymond Hettinger960dc362009-04-21 03:43:15 +0000133__version__ = '1.70' # Highest version of the spec this complies with
134
Raymond Hettingereb260842005-06-07 18:52:34 +0000135import copy as _copy
Raymond Hettinger771ed762009-01-03 19:20:32 +0000136import math as _math
Raymond Hettinger82417ca2009-02-03 03:54:28 +0000137import numbers as _numbers
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000138
Christian Heimes25bb7832008-01-11 16:17:00 +0000139try:
140 from collections import namedtuple as _namedtuple
141 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
142except ImportError:
143 DecimalTuple = lambda *args: args
144
Guido van Rossumd8faa362007-04-27 19:54:29 +0000145# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000146ROUND_DOWN = 'ROUND_DOWN'
147ROUND_HALF_UP = 'ROUND_HALF_UP'
148ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
149ROUND_CEILING = 'ROUND_CEILING'
150ROUND_FLOOR = 'ROUND_FLOOR'
151ROUND_UP = 'ROUND_UP'
152ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000153ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000154
Guido van Rossumd8faa362007-04-27 19:54:29 +0000155# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000156
157class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000158 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000159
160 Used exceptions derive from this.
161 If an exception derives from another exception besides this (such as
162 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
163 called if the others are present. This isn't actually used for
164 anything, though.
165
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000166 handle -- Called when context._raise_error is called and the
167 trap_enabler is set. First argument is self, second is the
168 context. More arguments can be given, those being after
169 the explanation in _raise_error (For example,
170 context._raise_error(NewError, '(-x)!', self._sign) would
171 call NewError().handle(context, self._sign).)
172
173 To define a new exception, it should be sufficient to have it derive
174 from DecimalException.
175 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000176 def handle(self, context, *args):
177 pass
178
179
180class Clamped(DecimalException):
181 """Exponent of a 0 changed to fit bounds.
182
183 This occurs and signals clamped if the exponent of a result has been
184 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000185 representation. This may occur when the exponent of a zero result would
186 be outside the bounds of a representation, or when a large normal
187 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000188 this latter case, the exponent is reduced to fit and the corresponding
189 number of zero digits are appended to the coefficient ("fold-down").
190 """
191
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000192class InvalidOperation(DecimalException):
193 """An invalid operation was performed.
194
195 Various bad things cause this:
196
197 Something creates a signaling NaN
198 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000199 0 * (+-)INF
200 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000201 x % 0
202 (+-)INF % x
203 x._rescale( non-integer )
204 sqrt(-x) , x > 0
205 0 ** 0
206 x ** (non-integer)
207 x ** (+-)INF
208 An operand is invalid
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000209
210 The result of the operation after these is a quiet positive NaN,
211 except when the cause is a signaling NaN, in which case the result is
212 also a quiet NaN, but with the original sign, and an optional
213 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000214 """
215 def handle(self, context, *args):
216 if args:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000217 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
218 return ans._fix_nan(context)
Mark Dickinsonf9236412009-01-02 23:23:21 +0000219 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000220
221class ConversionSyntax(InvalidOperation):
222 """Trying to convert badly formed string.
223
224 This occurs and signals invalid-operation if an string is being
225 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000226 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000227 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000228 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000229 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000230
231class DivisionByZero(DecimalException, ZeroDivisionError):
232 """Division by 0.
233
234 This occurs and signals division-by-zero if division of a finite number
235 by zero was attempted (during a divide-integer or divide operation, or a
236 power operation with negative right-hand operand), and the dividend was
237 not zero.
238
239 The result of the operation is [sign,inf], where sign is the exclusive
240 or of the signs of the operands for divide, or is 1 for an odd power of
241 -0, for power.
242 """
243
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000244 def handle(self, context, sign, *args):
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000245 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000246
247class DivisionImpossible(InvalidOperation):
248 """Cannot perform the division adequately.
249
250 This occurs and signals invalid-operation if the integer result of a
251 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000252 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000253 """
254
255 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000256 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000257
258class DivisionUndefined(InvalidOperation, ZeroDivisionError):
259 """Undefined result of division.
260
261 This occurs and signals invalid-operation if division by zero was
262 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000263 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000264 """
265
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000266 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000267 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000268
269class Inexact(DecimalException):
270 """Had to round, losing information.
271
272 This occurs and signals inexact whenever the result of an operation is
273 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000274 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000275 result in all cases is unchanged.
276
277 The inexact signal may be tested (or trapped) to determine if a given
278 operation (or sequence of operations) was inexact.
279 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000280
281class InvalidContext(InvalidOperation):
282 """Invalid context. Unknown rounding, for example.
283
284 This occurs and signals invalid-operation if an invalid context was
Guido van Rossumd8faa362007-04-27 19:54:29 +0000285 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000286 on creation and either the precision exceeds the capability of the
287 underlying concrete representation or an unknown or unsupported rounding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000288 was specified. These aspects of the context need only be checked when
289 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000290 """
291
292 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000293 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000294
295class Rounded(DecimalException):
296 """Number got rounded (not necessarily changed during rounding).
297
298 This occurs and signals rounded whenever the result of an operation is
299 rounded (that is, some zero or non-zero digits were discarded from the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000300 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000301 result in all cases is unchanged.
302
303 The rounded signal may be tested (or trapped) to determine if a given
304 operation (or sequence of operations) caused a loss of precision.
305 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000306
307class Subnormal(DecimalException):
308 """Exponent < Emin before rounding.
309
310 This occurs and signals subnormal whenever the result of a conversion or
311 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000312 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000313
314 The subnormal signal may be tested (or trapped) to determine if a given
315 or operation (or sequence of operations) yielded a subnormal result.
316 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000317
318class Overflow(Inexact, Rounded):
319 """Numerical overflow.
320
321 This occurs and signals overflow if the adjusted exponent of a result
322 (from a conversion or from an operation that is not an attempt to divide
323 by zero), after rounding, would be greater than the largest value that
324 can be handled by the implementation (the value Emax).
325
326 The result depends on the rounding mode:
327
328 For round-half-up and round-half-even (and for round-half-down and
329 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000330 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000331 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000332 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000333 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000334 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000335 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000336 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 will also be raised.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000338 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000339
340 def handle(self, context, sign, *args):
341 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000342 ROUND_HALF_DOWN, ROUND_UP):
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000343 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000344 if sign == 0:
345 if context.rounding == ROUND_CEILING:
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000346 return _SignedInfinity[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000347 return _dec_from_triple(sign, '9'*context.prec,
348 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000349 if sign == 1:
350 if context.rounding == ROUND_FLOOR:
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000351 return _SignedInfinity[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000352 return _dec_from_triple(sign, '9'*context.prec,
353 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000354
355
356class Underflow(Inexact, Rounded, Subnormal):
357 """Numerical underflow with result rounded to 0.
358
359 This occurs and signals underflow if a result is inexact and the
360 adjusted exponent of the result would be smaller (more negative) than
361 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000362 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000363
364 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000365 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000366 in 0 with the sign of the intermediate result and an exponent of Etiny.
367
368 In all cases, Inexact, Rounded, and Subnormal will also be raised.
369 """
370
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000371# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000372_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000373 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000374
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000375# Map conditions (per the spec) to signals
376_condition_map = {ConversionSyntax:InvalidOperation,
377 DivisionImpossible:InvalidOperation,
378 DivisionUndefined:InvalidOperation,
379 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000380
Guido van Rossumd8faa362007-04-27 19:54:29 +0000381##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000382
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000383# The getcontext() and setcontext() function manage access to a thread-local
384# current context. Py2.4 offers direct support for thread locals. If that
Georg Brandlf9926402008-06-13 06:32:25 +0000385# is not available, use threading.current_thread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000386# work for older Pythons. If threads are not part of the build, create a
387# mock threading object with threading.local() returning the module namespace.
388
389try:
390 import threading
391except ImportError:
392 # Python was compiled without threads; create a mock object instead
393 import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +0000394 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000395 def local(self, sys=sys):
396 return sys.modules[__name__]
397 threading = MockThreading()
398 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000399
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000400try:
401 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000402
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000403except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000404
Guido van Rossumd8faa362007-04-27 19:54:29 +0000405 # To fix reloading, force it to create a new context
406 # Old contexts have different exceptions in their dicts, making problems.
Georg Brandlf9926402008-06-13 06:32:25 +0000407 if hasattr(threading.current_thread(), '__decimal_context__'):
408 del threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000409
410 def setcontext(context):
411 """Set this thread's context to context."""
412 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000413 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000414 context.clear_flags()
Georg Brandlf9926402008-06-13 06:32:25 +0000415 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000416
417 def getcontext():
418 """Returns this thread's context.
419
420 If this thread does not yet have a context, returns
421 a new context and sets this thread's context.
422 New contexts are copies of DefaultContext.
423 """
424 try:
Georg Brandlf9926402008-06-13 06:32:25 +0000425 return threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000426 except AttributeError:
427 context = Context()
Georg Brandlf9926402008-06-13 06:32:25 +0000428 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000429 return context
430
431else:
432
433 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000434 if hasattr(local, '__decimal_context__'):
435 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000436
437 def getcontext(_local=local):
438 """Returns this thread's context.
439
440 If this thread does not yet have a context, returns
441 a new context and sets this thread's context.
442 New contexts are copies of DefaultContext.
443 """
444 try:
445 return _local.__decimal_context__
446 except AttributeError:
447 context = Context()
448 _local.__decimal_context__ = context
449 return context
450
451 def setcontext(context, _local=local):
452 """Set this thread's context to context."""
453 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000454 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000455 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000456 _local.__decimal_context__ = context
457
458 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000459
Thomas Wouters89f507f2006-12-13 04:49:30 +0000460def localcontext(ctx=None):
461 """Return a context manager for a copy of the supplied context
462
463 Uses a copy of the current context if no context is specified
464 The returned context manager creates a local decimal context
465 in a with statement:
466 def sin(x):
467 with localcontext() as ctx:
468 ctx.prec += 2
469 # Rest of sin calculation algorithm
470 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000471 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000472
473 def sin(x):
474 with localcontext(ExtendedContext):
475 # Rest of sin calculation algorithm
476 # uses the Extended Context from the
477 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000478 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000479
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000480 >>> setcontext(DefaultContext)
Guido van Rossum7131f842007-02-09 20:13:25 +0000481 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000482 28
483 >>> with localcontext():
484 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000485 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000486 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000487 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000488 30
489 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000490 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000491 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000492 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000493 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000494 28
495 """
496 if ctx is None: ctx = getcontext()
497 return _ContextManager(ctx)
498
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000499
Guido van Rossumd8faa362007-04-27 19:54:29 +0000500##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000501
Raymond Hettingera0fd8882009-01-20 07:24:44 +0000502# Do not subclass Decimal from numbers.Real and do not register it as such
503# (because Decimals are not interoperable with floats). See the notes in
504# numbers.py for more detail.
505
506class Decimal(object):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000507 """Floating point class for decimal arithmetic."""
508
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000509 __slots__ = ('_exp','_int','_sign', '_is_special')
510 # Generally, the value of the Decimal instance is given by
511 # (-1)**_sign * _int * 10**_exp
512 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000513
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000514 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000515 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000516 """Create a decimal point instance.
517
518 >>> Decimal('3.14') # string input
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000519 Decimal('3.14')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000520 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000521 Decimal('3.14')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000522 >>> Decimal(314) # int
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000523 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000524 >>> Decimal(Decimal(314)) # another decimal instance
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000525 Decimal('314')
Christian Heimesa62da1d2008-01-12 19:39:10 +0000526 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000527 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000528 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000529
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000530 # Note that the coefficient, self._int, is actually stored as
531 # a string rather than as a tuple of digits. This speeds up
532 # the "digits to integer" and "integer to digits" conversions
533 # that are used in almost every arithmetic operation on
534 # Decimals. This is an internal detail: the as_tuple function
535 # and the Decimal constructor still deal with tuples of
536 # digits.
537
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000538 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000539
Christian Heimesd59c64c2007-11-30 19:27:20 +0000540 # From a string
541 # REs insist on real strings, so we can too.
542 if isinstance(value, str):
Christian Heimesa62da1d2008-01-12 19:39:10 +0000543 m = _parser(value.strip())
Christian Heimesd59c64c2007-11-30 19:27:20 +0000544 if m is None:
545 if context is None:
546 context = getcontext()
547 return context._raise_error(ConversionSyntax,
548 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000549
Christian Heimesd59c64c2007-11-30 19:27:20 +0000550 if m.group('sign') == "-":
551 self._sign = 1
552 else:
553 self._sign = 0
554 intpart = m.group('int')
555 if intpart is not None:
556 # finite number
Mark Dickinson345adc42009-08-02 10:14:23 +0000557 fracpart = m.group('frac') or ''
Christian Heimesd59c64c2007-11-30 19:27:20 +0000558 exp = int(m.group('exp') or '0')
Mark Dickinson345adc42009-08-02 10:14:23 +0000559 self._int = str(int(intpart+fracpart))
560 self._exp = exp - len(fracpart)
Christian Heimesd59c64c2007-11-30 19:27:20 +0000561 self._is_special = False
562 else:
563 diag = m.group('diag')
564 if diag is not None:
565 # NaN
Mark Dickinson345adc42009-08-02 10:14:23 +0000566 self._int = str(int(diag or '0')).lstrip('0')
Christian Heimesd59c64c2007-11-30 19:27:20 +0000567 if m.group('signal'):
568 self._exp = 'N'
569 else:
570 self._exp = 'n'
571 else:
572 # infinity
573 self._int = '0'
574 self._exp = 'F'
575 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000576 return self
577
578 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000579 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000580 if value >= 0:
581 self._sign = 0
582 else:
583 self._sign = 1
584 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000585 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000586 self._is_special = False
587 return self
588
589 # From another decimal
590 if isinstance(value, Decimal):
591 self._exp = value._exp
592 self._sign = value._sign
593 self._int = value._int
594 self._is_special = value._is_special
595 return self
596
597 # From an internal working value
598 if isinstance(value, _WorkRep):
599 self._sign = value.sign
600 self._int = str(value.int)
601 self._exp = int(value.exp)
602 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000603 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000604
605 # tuple/list conversion (possibly from as_tuple())
606 if isinstance(value, (list,tuple)):
607 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000608 raise ValueError('Invalid tuple size in creation of Decimal '
609 'from list or tuple. The list or tuple '
610 'should have exactly three elements.')
611 # process sign. The isinstance test rejects floats
612 if not (isinstance(value[0], int) and value[0] in (0,1)):
613 raise ValueError("Invalid sign. The first value in the tuple "
614 "should be an integer; either 0 for a "
615 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000616 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000617 if value[2] == 'F':
618 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000619 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000620 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000621 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000622 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000623 # process and validate the digits in value[1]
624 digits = []
625 for digit in value[1]:
626 if isinstance(digit, int) and 0 <= digit <= 9:
627 # skip leading zeros
628 if digits or digit != 0:
629 digits.append(digit)
630 else:
631 raise ValueError("The second value in the tuple must "
632 "be composed of integers in the range "
633 "0 through 9.")
634 if value[2] in ('n', 'N'):
635 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000636 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000637 self._exp = value[2]
638 self._is_special = True
639 elif isinstance(value[2], int):
640 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000641 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000642 self._exp = value[2]
643 self._is_special = False
644 else:
645 raise ValueError("The third value in the tuple must "
646 "be an integer, or one of the "
647 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000648 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000649
Raymond Hettingerbf440692004-07-10 14:14:37 +0000650 if isinstance(value, float):
Raymond Hettinger96798592010-04-02 16:58:27 +0000651 value = Decimal.from_float(value)
652 self._exp = value._exp
653 self._sign = value._sign
654 self._int = value._int
655 self._is_special = value._is_special
656 return self
Raymond Hettingerbf440692004-07-10 14:14:37 +0000657
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000658 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000659
Mark Dickinsonba298e42009-01-04 21:17:43 +0000660 # @classmethod, but @decorator is not valid Python 2.3 syntax, so
661 # don't use it (see notes on Py2.3 compatibility at top of file)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000662 def from_float(cls, f):
663 """Converts a float to a decimal number, exactly.
664
665 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
666 Since 0.1 is not exactly representable in binary floating point, the
667 value is stored as the nearest representable value which is
668 0x1.999999999999ap-4. The exact equivalent of the value in decimal
669 is 0.1000000000000000055511151231257827021181583404541015625.
670
671 >>> Decimal.from_float(0.1)
672 Decimal('0.1000000000000000055511151231257827021181583404541015625')
673 >>> Decimal.from_float(float('nan'))
674 Decimal('NaN')
675 >>> Decimal.from_float(float('inf'))
676 Decimal('Infinity')
677 >>> Decimal.from_float(-float('inf'))
678 Decimal('-Infinity')
679 >>> Decimal.from_float(-0.0)
680 Decimal('-0')
681
682 """
683 if isinstance(f, int): # handle integer inputs
684 return cls(f)
685 if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float
686 return cls(repr(f))
Mark Dickinsonba298e42009-01-04 21:17:43 +0000687 if _math.copysign(1.0, f) == 1.0:
688 sign = 0
689 else:
690 sign = 1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000691 n, d = abs(f).as_integer_ratio()
692 k = d.bit_length() - 1
693 result = _dec_from_triple(sign, str(n*5**k), -k)
Mark Dickinsonba298e42009-01-04 21:17:43 +0000694 if cls is Decimal:
695 return result
696 else:
697 return cls(result)
698 from_float = classmethod(from_float)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000699
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000700 def _isnan(self):
701 """Returns whether the number is not actually one.
702
703 0 if a number
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000704 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000705 2 if sNaN
706 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000707 if self._is_special:
708 exp = self._exp
709 if exp == 'n':
710 return 1
711 elif exp == 'N':
712 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000713 return 0
714
715 def _isinfinity(self):
716 """Returns whether the number is infinite
717
718 0 if finite or not a number
719 1 if +INF
720 -1 if -INF
721 """
722 if self._exp == 'F':
723 if self._sign:
724 return -1
725 return 1
726 return 0
727
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000728 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000729 """Returns whether the number is not actually one.
730
731 if self, other are sNaN, signal
732 if self, other are NaN return nan
733 return 0
734
735 Done before operations.
736 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000737
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000738 self_is_nan = self._isnan()
739 if other is None:
740 other_is_nan = False
741 else:
742 other_is_nan = other._isnan()
743
744 if self_is_nan or other_is_nan:
745 if context is None:
746 context = getcontext()
747
748 if self_is_nan == 2:
749 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000750 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000751 if other_is_nan == 2:
752 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000753 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000754 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000755 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000756
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000757 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000758 return 0
759
Christian Heimes77c02eb2008-02-09 02:18:51 +0000760 def _compare_check_nans(self, other, context):
761 """Version of _check_nans used for the signaling comparisons
762 compare_signal, __le__, __lt__, __ge__, __gt__.
763
764 Signal InvalidOperation if either self or other is a (quiet
765 or signaling) NaN. Signaling NaNs take precedence over quiet
766 NaNs.
767
768 Return 0 if neither operand is a NaN.
769
770 """
771 if context is None:
772 context = getcontext()
773
774 if self._is_special or other._is_special:
775 if self.is_snan():
776 return context._raise_error(InvalidOperation,
777 'comparison involving sNaN',
778 self)
779 elif other.is_snan():
780 return context._raise_error(InvalidOperation,
781 'comparison involving sNaN',
782 other)
783 elif self.is_qnan():
784 return context._raise_error(InvalidOperation,
785 'comparison involving NaN',
786 self)
787 elif other.is_qnan():
788 return context._raise_error(InvalidOperation,
789 'comparison involving NaN',
790 other)
791 return 0
792
Jack Diederich4dafcc42006-11-28 19:15:13 +0000793 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000794 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000795
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000796 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000797 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000798 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000799
Christian Heimes77c02eb2008-02-09 02:18:51 +0000800 def _cmp(self, other):
801 """Compare the two non-NaN decimal instances self and other.
802
803 Returns -1 if self < other, 0 if self == other and 1
804 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000805
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000806 if self._is_special or other._is_special:
Mark Dickinsone6aad752009-01-25 10:48:51 +0000807 self_inf = self._isinfinity()
808 other_inf = other._isinfinity()
809 if self_inf == other_inf:
810 return 0
811 elif self_inf < other_inf:
812 return -1
813 else:
814 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000815
Mark Dickinsone6aad752009-01-25 10:48:51 +0000816 # check for zeros; Decimal('0') == Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000817 if not self:
818 if not other:
819 return 0
820 else:
821 return -((-1)**other._sign)
822 if not other:
823 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000824
Guido van Rossumd8faa362007-04-27 19:54:29 +0000825 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000826 if other._sign < self._sign:
827 return -1
828 if self._sign < other._sign:
829 return 1
830
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000831 self_adjusted = self.adjusted()
832 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000833 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000834 self_padded = self._int + '0'*(self._exp - other._exp)
835 other_padded = other._int + '0'*(other._exp - self._exp)
Mark Dickinsone6aad752009-01-25 10:48:51 +0000836 if self_padded == other_padded:
837 return 0
838 elif self_padded < other_padded:
839 return -(-1)**self._sign
840 else:
841 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000842 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000843 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000844 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000845 return -((-1)**self._sign)
846
Christian Heimes77c02eb2008-02-09 02:18:51 +0000847 # Note: The Decimal standard doesn't cover rich comparisons for
848 # Decimals. In particular, the specification is silent on the
849 # subject of what should happen for a comparison involving a NaN.
850 # We take the following approach:
851 #
852 # == comparisons involving a NaN always return False
853 # != comparisons involving a NaN always return True
854 # <, >, <= and >= comparisons involving a (quiet or signaling)
855 # NaN signal InvalidOperation, and return False if the
Christian Heimes3feef612008-02-11 06:19:17 +0000856 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000857 #
858 # This behavior is designed to conform as closely as possible to
859 # that specified by IEEE 754.
860
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000861 def __eq__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000862 other = _convert_other(other)
863 if other is NotImplemented:
864 return other
865 if self.is_nan() or other.is_nan():
866 return False
867 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000868
869 def __ne__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000870 other = _convert_other(other)
871 if other is NotImplemented:
872 return other
873 if self.is_nan() or other.is_nan():
874 return True
875 return self._cmp(other) != 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000876
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000877
Christian Heimes77c02eb2008-02-09 02:18:51 +0000878 def __lt__(self, other, context=None):
879 other = _convert_other(other)
880 if other is NotImplemented:
881 return other
882 ans = self._compare_check_nans(other, context)
883 if ans:
884 return False
885 return self._cmp(other) < 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000886
Christian Heimes77c02eb2008-02-09 02:18:51 +0000887 def __le__(self, other, context=None):
888 other = _convert_other(other)
889 if other is NotImplemented:
890 return other
891 ans = self._compare_check_nans(other, context)
892 if ans:
893 return False
894 return self._cmp(other) <= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000895
Christian Heimes77c02eb2008-02-09 02:18:51 +0000896 def __gt__(self, other, context=None):
897 other = _convert_other(other)
898 if other is NotImplemented:
899 return other
900 ans = self._compare_check_nans(other, context)
901 if ans:
902 return False
903 return self._cmp(other) > 0
904
905 def __ge__(self, other, context=None):
906 other = _convert_other(other)
907 if other is NotImplemented:
908 return other
909 ans = self._compare_check_nans(other, context)
910 if ans:
911 return False
912 return self._cmp(other) >= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000913
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000914 def compare(self, other, context=None):
915 """Compares one to another.
916
917 -1 => a < b
918 0 => a = b
919 1 => a > b
920 NaN => one is NaN
921 Like __cmp__, but returns Decimal instances.
922 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000923 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000924
Guido van Rossumd8faa362007-04-27 19:54:29 +0000925 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000926 if (self._is_special or other and other._is_special):
927 ans = self._check_nans(other, context)
928 if ans:
929 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000930
Christian Heimes77c02eb2008-02-09 02:18:51 +0000931 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000932
933 def __hash__(self):
934 """x.__hash__() <==> hash(x)"""
935 # Decimal integers must hash the same as the ints
Christian Heimes2380ac72008-01-09 00:17:24 +0000936 #
937 # The hash of a nonspecial noninteger Decimal must depend only
938 # on the value of that Decimal, and not on its representation.
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000939 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000940 if self._is_special:
941 if self._isnan():
942 raise TypeError('Cannot hash a NaN value.')
943 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000944 if not self:
945 return 0
946 if self._isinteger():
947 op = _WorkRep(self.to_integral_value())
948 # to make computation feasible for Decimals with large
949 # exponent, we use the fact that hash(n) == hash(m) for
950 # any two nonzero integers n and m such that (i) n and m
951 # have the same sign, and (ii) n is congruent to m modulo
952 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
953 # hash((-1)**s*c*pow(10, e, 2**64-1).
954 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Christian Heimes2380ac72008-01-09 00:17:24 +0000955 # The value of a nonzero nonspecial Decimal instance is
956 # faithfully represented by the triple consisting of its sign,
957 # its adjusted exponent, and its coefficient with trailing
958 # zeros removed.
959 return hash((self._sign,
960 self._exp+len(self._int),
961 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000962
963 def as_tuple(self):
964 """Represents the number as a triple tuple.
965
966 To show the internals exactly as they are.
967 """
Christian Heimes25bb7832008-01-11 16:17:00 +0000968 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000969
970 def __repr__(self):
971 """Represents the number as an instance of Decimal."""
972 # Invariant: eval(repr(d)) == d
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000973 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000974
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000975 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000976 """Return string representation of the number in scientific notation.
977
978 Captures all of the information in the underlying representation.
979 """
980
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000981 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000982 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000983 if self._exp == 'F':
984 return sign + 'Infinity'
985 elif self._exp == 'n':
986 return sign + 'NaN' + self._int
987 else: # self._exp == 'N'
988 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000989
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000990 # number of digits of self._int to left of decimal point
991 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000992
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000993 # dotplace is number of digits of self._int to the left of the
994 # decimal point in the mantissa of the output string (that is,
995 # after adjusting the exponent)
996 if self._exp <= 0 and leftdigits > -6:
997 # no exponent required
998 dotplace = leftdigits
999 elif not eng:
1000 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001001 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001002 elif self._int == '0':
1003 # engineering notation, zero
1004 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001005 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001006 # engineering notation, nonzero
1007 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001008
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001009 if dotplace <= 0:
1010 intpart = '0'
1011 fracpart = '.' + '0'*(-dotplace) + self._int
1012 elif dotplace >= len(self._int):
1013 intpart = self._int+'0'*(dotplace-len(self._int))
1014 fracpart = ''
1015 else:
1016 intpart = self._int[:dotplace]
1017 fracpart = '.' + self._int[dotplace:]
1018 if leftdigits == dotplace:
1019 exp = ''
1020 else:
1021 if context is None:
1022 context = getcontext()
1023 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1024
1025 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001026
1027 def to_eng_string(self, context=None):
1028 """Convert to engineering-type string.
1029
1030 Engineering notation has an exponent which is a multiple of 3, so there
1031 are up to 3 digits left of the decimal place.
1032
1033 Same rules for when in exponential and when as a value as in __str__.
1034 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001035 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001036
1037 def __neg__(self, context=None):
1038 """Returns a copy with the sign switched.
1039
1040 Rounds, if it has reason.
1041 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001042 if self._is_special:
1043 ans = self._check_nans(context=context)
1044 if ans:
1045 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001046
1047 if not self:
1048 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001049 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001050 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001051 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001052
1053 if context is None:
1054 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001055 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001056
1057 def __pos__(self, context=None):
1058 """Returns a copy, unless it is a sNaN.
1059
1060 Rounds the number (if more then precision digits)
1061 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001062 if self._is_special:
1063 ans = self._check_nans(context=context)
1064 if ans:
1065 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001066
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001067 if not self:
1068 # + (-0) = 0
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001069 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001070 else:
1071 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001072
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001073 if context is None:
1074 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001075 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001076
Christian Heimes2c181612007-12-17 20:04:13 +00001077 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001078 """Returns the absolute value of self.
1079
Christian Heimes2c181612007-12-17 20:04:13 +00001080 If the keyword argument 'round' is false, do not round. The
1081 expression self.__abs__(round=False) is equivalent to
1082 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001083 """
Christian Heimes2c181612007-12-17 20:04:13 +00001084 if not round:
1085 return self.copy_abs()
1086
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001087 if self._is_special:
1088 ans = self._check_nans(context=context)
1089 if ans:
1090 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001091
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001092 if self._sign:
1093 ans = self.__neg__(context=context)
1094 else:
1095 ans = self.__pos__(context=context)
1096
1097 return ans
1098
1099 def __add__(self, other, context=None):
1100 """Returns self + other.
1101
1102 -INF + INF (or the reverse) cause InvalidOperation errors.
1103 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001104 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001105 if other is NotImplemented:
1106 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001107
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001108 if context is None:
1109 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001110
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001111 if self._is_special or other._is_special:
1112 ans = self._check_nans(other, context)
1113 if ans:
1114 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001115
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001116 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001117 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001118 if self._sign != other._sign and other._isinfinity():
1119 return context._raise_error(InvalidOperation, '-INF + INF')
1120 return Decimal(self)
1121 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001122 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001123
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001124 exp = min(self._exp, other._exp)
1125 negativezero = 0
1126 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001127 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001128 negativezero = 1
1129
1130 if not self and not other:
1131 sign = min(self._sign, other._sign)
1132 if negativezero:
1133 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001134 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001135 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001137 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001138 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001139 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001140 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141 return ans
1142 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001143 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001144 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001145 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001146 return ans
1147
1148 op1 = _WorkRep(self)
1149 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001150 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001151
1152 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001153 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001154 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001155 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001156 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001157 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001158 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001159 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001160 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001161 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001162 if op1.sign == 1:
1163 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001164 op1.sign, op2.sign = op2.sign, op1.sign
1165 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001166 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001167 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001168 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001169 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001170 op1.sign, op2.sign = (0, 0)
1171 else:
1172 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001173 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001174
Raymond Hettinger17931de2004-10-27 06:21:46 +00001175 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001176 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001177 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001178 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001179
1180 result.exp = op1.exp
1181 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001182 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001183 return ans
1184
1185 __radd__ = __add__
1186
1187 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001188 """Return self - other"""
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
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001193 if self._is_special or other._is_special:
1194 ans = self._check_nans(other, context=context)
1195 if ans:
1196 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001197
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001198 # self - other is computed as self + other.copy_negate()
1199 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001200
1201 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001202 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001203 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001204 if other is NotImplemented:
1205 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001206
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001207 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001208
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001209 def __mul__(self, other, context=None):
1210 """Return self * other.
1211
1212 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1213 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001214 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001215 if other is NotImplemented:
1216 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001217
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001218 if context is None:
1219 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001220
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001221 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001222
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001223 if self._is_special or other._is_special:
1224 ans = self._check_nans(other, context)
1225 if ans:
1226 return ans
1227
1228 if self._isinfinity():
1229 if not other:
1230 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001231 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001232
1233 if other._isinfinity():
1234 if not self:
1235 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001236 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001237
1238 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001239
1240 # Special case for multiplying by zero
1241 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001242 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001243 # Fixing in case the exponent is out of bounds
1244 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001245 return ans
1246
1247 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001248 if self._int == '1':
1249 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001250 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001251 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001252 if other._int == '1':
1253 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001254 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001255 return ans
1256
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001257 op1 = _WorkRep(self)
1258 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001259
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001260 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001261 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001262
1263 return ans
1264 __rmul__ = __mul__
1265
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001266 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001267 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001268 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001269 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001270 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001271
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001272 if context is None:
1273 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001274
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001275 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001276
1277 if self._is_special or other._is_special:
1278 ans = self._check_nans(other, context)
1279 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001280 return ans
1281
1282 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001283 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001284
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001285 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001286 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001287
1288 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001289 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001290 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001291
1292 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001293 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001294 if not self:
1295 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001296 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001297
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001298 if not self:
1299 exp = self._exp - other._exp
1300 coeff = 0
1301 else:
1302 # OK, so neither = 0, INF or NaN
1303 shift = len(other._int) - len(self._int) + context.prec + 1
1304 exp = self._exp - other._exp - shift
1305 op1 = _WorkRep(self)
1306 op2 = _WorkRep(other)
1307 if shift >= 0:
1308 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1309 else:
1310 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1311 if remainder:
1312 # result is not exact; adjust to ensure correct rounding
1313 if coeff % 5 == 0:
1314 coeff += 1
1315 else:
1316 # result is exact; get as close to ideal exponent as possible
1317 ideal_exp = self._exp - other._exp
1318 while exp < ideal_exp and coeff % 10 == 0:
1319 coeff //= 10
1320 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001321
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001322 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001323 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001324
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001325 def _divide(self, other, context):
1326 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001327
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001328 Assumes that neither self nor other is a NaN, that self is not
1329 infinite and that other is nonzero.
1330 """
1331 sign = self._sign ^ other._sign
1332 if other._isinfinity():
1333 ideal_exp = self._exp
1334 else:
1335 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001336
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001337 expdiff = self.adjusted() - other.adjusted()
1338 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001339 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001340 self._rescale(ideal_exp, context.rounding))
1341 if expdiff <= context.prec:
1342 op1 = _WorkRep(self)
1343 op2 = _WorkRep(other)
1344 if op1.exp >= op2.exp:
1345 op1.int *= 10**(op1.exp - op2.exp)
1346 else:
1347 op2.int *= 10**(op2.exp - op1.exp)
1348 q, r = divmod(op1.int, op2.int)
1349 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001350 return (_dec_from_triple(sign, str(q), 0),
1351 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001352
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001353 # Here the quotient is too large to be representable
1354 ans = context._raise_error(DivisionImpossible,
1355 'quotient too large in //, % or divmod')
1356 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001357
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001358 def __rtruediv__(self, other, context=None):
1359 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001360 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001361 if other is NotImplemented:
1362 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001363 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001364
1365 def __divmod__(self, other, context=None):
1366 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001367 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001368 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001369 other = _convert_other(other)
1370 if other is NotImplemented:
1371 return other
1372
1373 if context is None:
1374 context = getcontext()
1375
1376 ans = self._check_nans(other, context)
1377 if ans:
1378 return (ans, ans)
1379
1380 sign = self._sign ^ other._sign
1381 if self._isinfinity():
1382 if other._isinfinity():
1383 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1384 return ans, ans
1385 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001386 return (_SignedInfinity[sign],
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001387 context._raise_error(InvalidOperation, 'INF % x'))
1388
1389 if not other:
1390 if not self:
1391 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1392 return ans, ans
1393 else:
1394 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1395 context._raise_error(InvalidOperation, 'x % 0'))
1396
1397 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001398 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001399 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001400
1401 def __rdivmod__(self, other, context=None):
1402 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001403 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001404 if other is NotImplemented:
1405 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001406 return other.__divmod__(self, context=context)
1407
1408 def __mod__(self, other, context=None):
1409 """
1410 self % other
1411 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001412 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001413 if other is NotImplemented:
1414 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001415
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001416 if context is None:
1417 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001418
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001419 ans = self._check_nans(other, context)
1420 if ans:
1421 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001422
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001423 if self._isinfinity():
1424 return context._raise_error(InvalidOperation, 'INF % x')
1425 elif not other:
1426 if self:
1427 return context._raise_error(InvalidOperation, 'x % 0')
1428 else:
1429 return context._raise_error(DivisionUndefined, '0 % 0')
1430
1431 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001432 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001433 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001434
1435 def __rmod__(self, other, context=None):
1436 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001437 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001438 if other is NotImplemented:
1439 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001440 return other.__mod__(self, context=context)
1441
1442 def remainder_near(self, other, context=None):
1443 """
1444 Remainder nearest to 0- abs(remainder-near) <= other/2
1445 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001446 if context is None:
1447 context = getcontext()
1448
1449 other = _convert_other(other, raiseit=True)
1450
1451 ans = self._check_nans(other, context)
1452 if ans:
1453 return ans
1454
1455 # self == +/-infinity -> InvalidOperation
1456 if self._isinfinity():
1457 return context._raise_error(InvalidOperation,
1458 'remainder_near(infinity, x)')
1459
1460 # other == 0 -> either InvalidOperation or DivisionUndefined
1461 if not other:
1462 if self:
1463 return context._raise_error(InvalidOperation,
1464 'remainder_near(x, 0)')
1465 else:
1466 return context._raise_error(DivisionUndefined,
1467 'remainder_near(0, 0)')
1468
1469 # other = +/-infinity -> remainder = self
1470 if other._isinfinity():
1471 ans = Decimal(self)
1472 return ans._fix(context)
1473
1474 # self = 0 -> remainder = self, with ideal exponent
1475 ideal_exponent = min(self._exp, other._exp)
1476 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001477 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001478 return ans._fix(context)
1479
1480 # catch most cases of large or small quotient
1481 expdiff = self.adjusted() - other.adjusted()
1482 if expdiff >= context.prec + 1:
1483 # expdiff >= prec+1 => abs(self/other) > 10**prec
1484 return context._raise_error(DivisionImpossible)
1485 if expdiff <= -2:
1486 # expdiff <= -2 => abs(self/other) < 0.1
1487 ans = self._rescale(ideal_exponent, context.rounding)
1488 return ans._fix(context)
1489
1490 # adjust both arguments to have the same exponent, then divide
1491 op1 = _WorkRep(self)
1492 op2 = _WorkRep(other)
1493 if op1.exp >= op2.exp:
1494 op1.int *= 10**(op1.exp - op2.exp)
1495 else:
1496 op2.int *= 10**(op2.exp - op1.exp)
1497 q, r = divmod(op1.int, op2.int)
1498 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1499 # 10**ideal_exponent. Apply correction to ensure that
1500 # abs(remainder) <= abs(other)/2
1501 if 2*r + (q&1) > op2.int:
1502 r -= op2.int
1503 q += 1
1504
1505 if q >= 10**context.prec:
1506 return context._raise_error(DivisionImpossible)
1507
1508 # result has same sign as self unless r is negative
1509 sign = self._sign
1510 if r < 0:
1511 sign = 1-sign
1512 r = -r
1513
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001514 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001515 return ans._fix(context)
1516
1517 def __floordiv__(self, other, context=None):
1518 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001519 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001520 if other is NotImplemented:
1521 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001522
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001523 if context is None:
1524 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001525
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001526 ans = self._check_nans(other, context)
1527 if ans:
1528 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001529
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001530 if self._isinfinity():
1531 if other._isinfinity():
1532 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001533 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001534 return _SignedInfinity[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001535
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001536 if not other:
1537 if self:
1538 return context._raise_error(DivisionByZero, 'x // 0',
1539 self._sign ^ other._sign)
1540 else:
1541 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001542
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001543 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001544
1545 def __rfloordiv__(self, other, context=None):
1546 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001547 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001548 if other is NotImplemented:
1549 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001550 return other.__floordiv__(self, context=context)
1551
1552 def __float__(self):
1553 """Float representation."""
1554 return float(str(self))
1555
1556 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001557 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001558 if self._is_special:
1559 if self._isnan():
Mark Dickinson825fce32009-09-07 18:08:12 +00001560 raise ValueError("Cannot convert NaN to integer")
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001561 elif self._isinfinity():
Mark Dickinson825fce32009-09-07 18:08:12 +00001562 raise OverflowError("Cannot convert infinity to integer")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001563 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001564 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001565 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001566 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001567 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001568
Christian Heimes969fe572008-01-25 11:23:10 +00001569 __trunc__ = __int__
1570
Christian Heimes0bd4e112008-02-12 22:59:25 +00001571 def real(self):
1572 return self
Mark Dickinson315a20a2009-01-04 21:34:18 +00001573 real = property(real)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001574
Christian Heimes0bd4e112008-02-12 22:59:25 +00001575 def imag(self):
1576 return Decimal(0)
Mark Dickinson315a20a2009-01-04 21:34:18 +00001577 imag = property(imag)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001578
1579 def conjugate(self):
1580 return self
1581
1582 def __complex__(self):
1583 return complex(float(self))
1584
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001585 def _fix_nan(self, context):
1586 """Decapitate the payload of a NaN to fit the context"""
1587 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001588
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001589 # maximum length of payload is precision if _clamp=0,
1590 # precision-1 if _clamp=1.
1591 max_payload_len = context.prec - context._clamp
1592 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001593 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1594 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001595 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001596
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001597 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001598 """Round if it is necessary to keep self within prec precision.
1599
1600 Rounds and fixes the exponent. Does not raise on a sNaN.
1601
1602 Arguments:
1603 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001604 context - context used.
1605 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001606
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001607 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001608 if self._isnan():
1609 # decapitate payload if necessary
1610 return self._fix_nan(context)
1611 else:
1612 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001613 return Decimal(self)
1614
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001615 # if self is zero then exponent should be between Etiny and
1616 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1617 Etiny = context.Etiny()
1618 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001619 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001620 exp_max = [context.Emax, Etop][context._clamp]
1621 new_exp = min(max(self._exp, Etiny), exp_max)
1622 if new_exp != self._exp:
1623 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001624 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001625 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001626 return Decimal(self)
1627
1628 # exp_min is the smallest allowable exponent of the result,
1629 # equal to max(self.adjusted()-context.prec+1, Etiny)
1630 exp_min = len(self._int) + self._exp - context.prec
1631 if exp_min > Etop:
1632 # overflow: exp_min > Etop iff self.adjusted() > Emax
1633 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001634 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001635 return context._raise_error(Overflow, 'above Emax', self._sign)
1636 self_is_subnormal = exp_min < Etiny
1637 if self_is_subnormal:
1638 context._raise_error(Subnormal)
1639 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001640
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001641 # round if self has too many digits
1642 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001643 context._raise_error(Rounded)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001644 digits = len(self._int) + self._exp - exp_min
1645 if digits < 0:
1646 self = _dec_from_triple(self._sign, '1', exp_min-1)
1647 digits = 0
1648 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1649 changed = this_function(digits)
1650 coeff = self._int[:digits] or '0'
1651 if changed == 1:
1652 coeff = str(int(coeff)+1)
1653 ans = _dec_from_triple(self._sign, coeff, exp_min)
1654
1655 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001656 context._raise_error(Inexact)
1657 if self_is_subnormal:
1658 context._raise_error(Underflow)
1659 if not ans:
1660 # raise Clamped on underflow to 0
1661 context._raise_error(Clamped)
1662 elif len(ans._int) == context.prec+1:
1663 # we get here only if rescaling rounds the
1664 # cofficient up to exactly 10**context.prec
1665 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001666 ans = _dec_from_triple(ans._sign,
1667 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001668 else:
1669 # Inexact and Rounded have already been raised
1670 ans = context._raise_error(Overflow, 'above Emax',
1671 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001672 return ans
1673
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001674 # fold down if _clamp == 1 and self has too few digits
1675 if context._clamp == 1 and self._exp > Etop:
1676 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001677 self_padded = self._int + '0'*(self._exp - Etop)
1678 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001679
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001680 # here self was representable to begin with; return unchanged
1681 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001682
1683 _pick_rounding_function = {}
1684
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001685 # for each of the rounding functions below:
1686 # self is a finite, nonzero Decimal
1687 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001688 #
1689 # each function returns either -1, 0, or 1, as follows:
1690 # 1 indicates that self should be rounded up (away from zero)
1691 # 0 indicates that self should be truncated, and that all the
1692 # digits to be truncated are zeros (so the value is unchanged)
1693 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001694
1695 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001696 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001697 if _all_zeros(self._int, prec):
1698 return 0
1699 else:
1700 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001701
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001702 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001703 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001704 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001705
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001706 def _round_half_up(self, prec):
1707 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001708 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001709 return 1
1710 elif _all_zeros(self._int, prec):
1711 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001712 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001713 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001714
1715 def _round_half_down(self, prec):
1716 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001717 if _exact_half(self._int, prec):
1718 return -1
1719 else:
1720 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001721
1722 def _round_half_even(self, prec):
1723 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001724 if _exact_half(self._int, prec) and \
1725 (prec == 0 or self._int[prec-1] in '02468'):
1726 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001727 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001728 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001729
1730 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001731 """Rounds up (not away from 0 if negative.)"""
1732 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001733 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001734 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001735 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001736
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001737 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001738 """Rounds down (not towards 0 if negative)"""
1739 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001740 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001741 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001742 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001743
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001744 def _round_05up(self, prec):
1745 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001746 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001747 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001748 else:
1749 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001750
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001751 def __round__(self, n=None):
1752 """Round self to the nearest integer, or to a given precision.
1753
1754 If only one argument is supplied, round a finite Decimal
1755 instance self to the nearest integer. If self is infinite or
1756 a NaN then a Python exception is raised. If self is finite
1757 and lies exactly halfway between two integers then it is
1758 rounded to the integer with even last digit.
1759
1760 >>> round(Decimal('123.456'))
1761 123
1762 >>> round(Decimal('-456.789'))
1763 -457
1764 >>> round(Decimal('-3.0'))
1765 -3
1766 >>> round(Decimal('2.5'))
1767 2
1768 >>> round(Decimal('3.5'))
1769 4
1770 >>> round(Decimal('Inf'))
1771 Traceback (most recent call last):
1772 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001773 OverflowError: cannot round an infinity
1774 >>> round(Decimal('NaN'))
1775 Traceback (most recent call last):
1776 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001777 ValueError: cannot round a NaN
1778
1779 If a second argument n is supplied, self is rounded to n
1780 decimal places using the rounding mode for the current
1781 context.
1782
1783 For an integer n, round(self, -n) is exactly equivalent to
1784 self.quantize(Decimal('1En')).
1785
1786 >>> round(Decimal('123.456'), 0)
1787 Decimal('123')
1788 >>> round(Decimal('123.456'), 2)
1789 Decimal('123.46')
1790 >>> round(Decimal('123.456'), -2)
1791 Decimal('1E+2')
1792 >>> round(Decimal('-Infinity'), 37)
1793 Decimal('NaN')
1794 >>> round(Decimal('sNaN123'), 0)
1795 Decimal('NaN123')
1796
1797 """
1798 if n is not None:
1799 # two-argument form: use the equivalent quantize call
1800 if not isinstance(n, int):
1801 raise TypeError('Second argument to round should be integral')
1802 exp = _dec_from_triple(0, '1', -n)
1803 return self.quantize(exp)
1804
1805 # one-argument form
1806 if self._is_special:
1807 if self.is_nan():
1808 raise ValueError("cannot round a NaN")
1809 else:
1810 raise OverflowError("cannot round an infinity")
1811 return int(self._rescale(0, ROUND_HALF_EVEN))
1812
1813 def __floor__(self):
1814 """Return the floor of self, as an integer.
1815
1816 For a finite Decimal instance self, return the greatest
1817 integer n such that n <= self. If self is infinite or a NaN
1818 then a Python exception is raised.
1819
1820 """
1821 if self._is_special:
1822 if self.is_nan():
1823 raise ValueError("cannot round a NaN")
1824 else:
1825 raise OverflowError("cannot round an infinity")
1826 return int(self._rescale(0, ROUND_FLOOR))
1827
1828 def __ceil__(self):
1829 """Return the ceiling of self, as an integer.
1830
1831 For a finite Decimal instance self, return the least integer n
1832 such that n >= self. If self is infinite or a NaN then a
1833 Python exception is raised.
1834
1835 """
1836 if self._is_special:
1837 if self.is_nan():
1838 raise ValueError("cannot round a NaN")
1839 else:
1840 raise OverflowError("cannot round an infinity")
1841 return int(self._rescale(0, ROUND_CEILING))
1842
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001843 def fma(self, other, third, context=None):
1844 """Fused multiply-add.
1845
1846 Returns self*other+third with no rounding of the intermediate
1847 product self*other.
1848
1849 self and other are multiplied together, with no rounding of
1850 the result. The third operand is then added to the result,
1851 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001852 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001853
1854 other = _convert_other(other, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001855
1856 # compute product; raise InvalidOperation if either operand is
1857 # a signaling NaN or if the product is zero times infinity.
1858 if self._is_special or other._is_special:
1859 if context is None:
1860 context = getcontext()
1861 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001862 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001863 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001864 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001865 if self._exp == 'n':
1866 product = self
1867 elif other._exp == 'n':
1868 product = other
1869 elif self._exp == 'F':
1870 if not other:
1871 return context._raise_error(InvalidOperation,
1872 'INF * 0 in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001873 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001874 elif other._exp == 'F':
1875 if not self:
1876 return context._raise_error(InvalidOperation,
1877 '0 * INF in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001878 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001879 else:
1880 product = _dec_from_triple(self._sign ^ other._sign,
1881 str(int(self._int) * int(other._int)),
1882 self._exp + other._exp)
1883
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001884 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001885 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001886
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001887 def _power_modulo(self, other, modulo, context=None):
1888 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001889
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001890 # if can't convert other and modulo to Decimal, raise
1891 # TypeError; there's no point returning NotImplemented (no
1892 # equivalent of __rpow__ for three argument pow)
1893 other = _convert_other(other, raiseit=True)
1894 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001895
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001896 if context is None:
1897 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001898
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001899 # deal with NaNs: if there are any sNaNs then first one wins,
1900 # (i.e. behaviour for NaNs is identical to that of fma)
1901 self_is_nan = self._isnan()
1902 other_is_nan = other._isnan()
1903 modulo_is_nan = modulo._isnan()
1904 if self_is_nan or other_is_nan or modulo_is_nan:
1905 if self_is_nan == 2:
1906 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001907 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001908 if other_is_nan == 2:
1909 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001910 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001911 if modulo_is_nan == 2:
1912 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001913 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001914 if self_is_nan:
1915 return self._fix_nan(context)
1916 if other_is_nan:
1917 return other._fix_nan(context)
1918 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001919
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001920 # check inputs: we apply same restrictions as Python's pow()
1921 if not (self._isinteger() and
1922 other._isinteger() and
1923 modulo._isinteger()):
1924 return context._raise_error(InvalidOperation,
1925 'pow() 3rd argument not allowed '
1926 'unless all arguments are integers')
1927 if other < 0:
1928 return context._raise_error(InvalidOperation,
1929 'pow() 2nd argument cannot be '
1930 'negative when 3rd argument specified')
1931 if not modulo:
1932 return context._raise_error(InvalidOperation,
1933 'pow() 3rd argument cannot be 0')
1934
1935 # additional restriction for decimal: the modulus must be less
1936 # than 10**prec in absolute value
1937 if modulo.adjusted() >= context.prec:
1938 return context._raise_error(InvalidOperation,
1939 'insufficient precision: pow() 3rd '
1940 'argument must not have more than '
1941 'precision digits')
1942
1943 # define 0**0 == NaN, for consistency with two-argument pow
1944 # (even though it hurts!)
1945 if not other and not self:
1946 return context._raise_error(InvalidOperation,
1947 'at least one of pow() 1st argument '
1948 'and 2nd argument must be nonzero ;'
1949 '0**0 is not defined')
1950
1951 # compute sign of result
1952 if other._iseven():
1953 sign = 0
1954 else:
1955 sign = self._sign
1956
1957 # convert modulo to a Python integer, and self and other to
1958 # Decimal integers (i.e. force their exponents to be >= 0)
1959 modulo = abs(int(modulo))
1960 base = _WorkRep(self.to_integral_value())
1961 exponent = _WorkRep(other.to_integral_value())
1962
1963 # compute result using integer pow()
1964 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1965 for i in range(exponent.exp):
1966 base = pow(base, 10, modulo)
1967 base = pow(base, exponent.int, modulo)
1968
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001969 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001970
1971 def _power_exact(self, other, p):
1972 """Attempt to compute self**other exactly.
1973
1974 Given Decimals self and other and an integer p, attempt to
1975 compute an exact result for the power self**other, with p
1976 digits of precision. Return None if self**other is not
1977 exactly representable in p digits.
1978
1979 Assumes that elimination of special cases has already been
1980 performed: self and other must both be nonspecial; self must
1981 be positive and not numerically equal to 1; other must be
1982 nonzero. For efficiency, other._exp should not be too large,
1983 so that 10**abs(other._exp) is a feasible calculation."""
1984
1985 # In the comments below, we write x for the value of self and
1986 # y for the value of other. Write x = xc*10**xe and y =
1987 # yc*10**ye.
1988
1989 # The main purpose of this method is to identify the *failure*
1990 # of x**y to be exactly representable with as little effort as
1991 # possible. So we look for cheap and easy tests that
1992 # eliminate the possibility of x**y being exact. Only if all
1993 # these tests are passed do we go on to actually compute x**y.
1994
1995 # Here's the main idea. First normalize both x and y. We
1996 # express y as a rational m/n, with m and n relatively prime
1997 # and n>0. Then for x**y to be exactly representable (at
1998 # *any* precision), xc must be the nth power of a positive
1999 # integer and xe must be divisible by n. If m is negative
2000 # then additionally xc must be a power of either 2 or 5, hence
2001 # a power of 2**n or 5**n.
2002 #
2003 # There's a limit to how small |y| can be: if y=m/n as above
2004 # then:
2005 #
2006 # (1) if xc != 1 then for the result to be representable we
2007 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
2008 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
2009 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
2010 # representable.
2011 #
2012 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
2013 # |y| < 1/|xe| then the result is not representable.
2014 #
2015 # Note that since x is not equal to 1, at least one of (1) and
2016 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2017 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2018 #
2019 # There's also a limit to how large y can be, at least if it's
2020 # positive: the normalized result will have coefficient xc**y,
2021 # so if it's representable then xc**y < 10**p, and y <
2022 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
2023 # not exactly representable.
2024
2025 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2026 # so |y| < 1/xe and the result is not representable.
2027 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2028 # < 1/nbits(xc).
2029
2030 x = _WorkRep(self)
2031 xc, xe = x.int, x.exp
2032 while xc % 10 == 0:
2033 xc //= 10
2034 xe += 1
2035
2036 y = _WorkRep(other)
2037 yc, ye = y.int, y.exp
2038 while yc % 10 == 0:
2039 yc //= 10
2040 ye += 1
2041
2042 # case where xc == 1: result is 10**(xe*y), with xe*y
2043 # required to be an integer
2044 if xc == 1:
2045 if ye >= 0:
2046 exponent = xe*yc*10**ye
2047 else:
2048 exponent, remainder = divmod(xe*yc, 10**-ye)
2049 if remainder:
2050 return None
2051 if y.sign == 1:
2052 exponent = -exponent
2053 # if other is a nonnegative integer, use ideal exponent
2054 if other._isinteger() and other._sign == 0:
2055 ideal_exponent = self._exp*int(other)
2056 zeros = min(exponent-ideal_exponent, p-1)
2057 else:
2058 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002059 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002060
2061 # case where y is negative: xc must be either a power
2062 # of 2 or a power of 5.
2063 if y.sign == 1:
2064 last_digit = xc % 10
2065 if last_digit in (2,4,6,8):
2066 # quick test for power of 2
2067 if xc & -xc != xc:
2068 return None
2069 # now xc is a power of 2; e is its exponent
2070 e = _nbits(xc)-1
2071 # find e*y and xe*y; both must be integers
2072 if ye >= 0:
2073 y_as_int = yc*10**ye
2074 e = e*y_as_int
2075 xe = xe*y_as_int
2076 else:
2077 ten_pow = 10**-ye
2078 e, remainder = divmod(e*yc, ten_pow)
2079 if remainder:
2080 return None
2081 xe, remainder = divmod(xe*yc, ten_pow)
2082 if remainder:
2083 return None
2084
2085 if e*65 >= p*93: # 93/65 > log(10)/log(5)
2086 return None
2087 xc = 5**e
2088
2089 elif last_digit == 5:
2090 # e >= log_5(xc) if xc is a power of 5; we have
2091 # equality all the way up to xc=5**2658
2092 e = _nbits(xc)*28//65
2093 xc, remainder = divmod(5**e, xc)
2094 if remainder:
2095 return None
2096 while xc % 5 == 0:
2097 xc //= 5
2098 e -= 1
2099 if ye >= 0:
2100 y_as_integer = yc*10**ye
2101 e = e*y_as_integer
2102 xe = xe*y_as_integer
2103 else:
2104 ten_pow = 10**-ye
2105 e, remainder = divmod(e*yc, ten_pow)
2106 if remainder:
2107 return None
2108 xe, remainder = divmod(xe*yc, ten_pow)
2109 if remainder:
2110 return None
2111 if e*3 >= p*10: # 10/3 > log(10)/log(2)
2112 return None
2113 xc = 2**e
2114 else:
2115 return None
2116
2117 if xc >= 10**p:
2118 return None
2119 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002120 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002121
2122 # now y is positive; find m and n such that y = m/n
2123 if ye >= 0:
2124 m, n = yc*10**ye, 1
2125 else:
2126 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2127 return None
2128 xc_bits = _nbits(xc)
2129 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2130 return None
2131 m, n = yc, 10**(-ye)
2132 while m % 2 == n % 2 == 0:
2133 m //= 2
2134 n //= 2
2135 while m % 5 == n % 5 == 0:
2136 m //= 5
2137 n //= 5
2138
2139 # compute nth root of xc*10**xe
2140 if n > 1:
2141 # if 1 < xc < 2**n then xc isn't an nth power
2142 if xc != 1 and xc_bits <= n:
2143 return None
2144
2145 xe, rem = divmod(xe, n)
2146 if rem != 0:
2147 return None
2148
2149 # compute nth root of xc using Newton's method
2150 a = 1 << -(-_nbits(xc)//n) # initial estimate
2151 while True:
2152 q, r = divmod(xc, a**(n-1))
2153 if a <= q:
2154 break
2155 else:
2156 a = (a*(n-1) + q)//n
2157 if not (a == q and r == 0):
2158 return None
2159 xc = a
2160
2161 # now xc*10**xe is the nth root of the original xc*10**xe
2162 # compute mth power of xc*10**xe
2163
2164 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2165 # 10**p and the result is not representable.
2166 if xc > 1 and m > p*100//_log10_lb(xc):
2167 return None
2168 xc = xc**m
2169 xe *= m
2170 if xc > 10**p:
2171 return None
2172
2173 # by this point the result *is* exactly representable
2174 # adjust the exponent to get as close as possible to the ideal
2175 # exponent, if necessary
2176 str_xc = str(xc)
2177 if other._isinteger() and other._sign == 0:
2178 ideal_exponent = self._exp*int(other)
2179 zeros = min(xe-ideal_exponent, p-len(str_xc))
2180 else:
2181 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002182 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002183
2184 def __pow__(self, other, modulo=None, context=None):
2185 """Return self ** other [ % modulo].
2186
2187 With two arguments, compute self**other.
2188
2189 With three arguments, compute (self**other) % modulo. For the
2190 three argument form, the following restrictions on the
2191 arguments hold:
2192
2193 - all three arguments must be integral
2194 - other must be nonnegative
2195 - either self or other (or both) must be nonzero
2196 - modulo must be nonzero and must have at most p digits,
2197 where p is the context precision.
2198
2199 If any of these restrictions is violated the InvalidOperation
2200 flag is raised.
2201
2202 The result of pow(self, other, modulo) is identical to the
2203 result that would be obtained by computing (self**other) %
2204 modulo with unbounded precision, but is computed more
2205 efficiently. It is always exact.
2206 """
2207
2208 if modulo is not None:
2209 return self._power_modulo(other, modulo, context)
2210
2211 other = _convert_other(other)
2212 if other is NotImplemented:
2213 return other
2214
2215 if context is None:
2216 context = getcontext()
2217
2218 # either argument is a NaN => result is NaN
2219 ans = self._check_nans(other, context)
2220 if ans:
2221 return ans
2222
2223 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2224 if not other:
2225 if not self:
2226 return context._raise_error(InvalidOperation, '0 ** 0')
2227 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002228 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002229
2230 # result has sign 1 iff self._sign is 1 and other is an odd integer
2231 result_sign = 0
2232 if self._sign == 1:
2233 if other._isinteger():
2234 if not other._iseven():
2235 result_sign = 1
2236 else:
2237 # -ve**noninteger = NaN
2238 # (-0)**noninteger = 0**noninteger
2239 if self:
2240 return context._raise_error(InvalidOperation,
2241 'x ** y with x negative and y not an integer')
2242 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002243 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002244
2245 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2246 if not self:
2247 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002248 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002249 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002250 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002251
2252 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002253 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002254 if other._sign == 0:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002255 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002256 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002257 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002258
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002259 # 1**other = 1, but the choice of exponent and the flags
2260 # depend on the exponent of self, and on whether other is a
2261 # positive integer, a negative integer, or neither
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002262 if self == _One:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002263 if other._isinteger():
2264 # exp = max(self._exp*max(int(other), 0),
2265 # 1-context.prec) but evaluating int(other) directly
2266 # is dangerous until we know other is small (other
2267 # could be 1e999999999)
2268 if other._sign == 1:
2269 multiplier = 0
2270 elif other > context.prec:
2271 multiplier = context.prec
2272 else:
2273 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002274
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002275 exp = self._exp * multiplier
2276 if exp < 1-context.prec:
2277 exp = 1-context.prec
2278 context._raise_error(Rounded)
2279 else:
2280 context._raise_error(Inexact)
2281 context._raise_error(Rounded)
2282 exp = 1-context.prec
2283
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002284 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002285
2286 # compute adjusted exponent of self
2287 self_adj = self.adjusted()
2288
2289 # self ** infinity is infinity if self > 1, 0 if self < 1
2290 # self ** -infinity is infinity if self < 1, 0 if self > 1
2291 if other._isinfinity():
2292 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002293 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002294 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002295 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002296
2297 # from here on, the result always goes through the call
2298 # to _fix at the end of this function.
2299 ans = None
2300
2301 # crude test to catch cases of extreme overflow/underflow. If
2302 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2303 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2304 # self**other >= 10**(Emax+1), so overflow occurs. The test
2305 # for underflow is similar.
2306 bound = self._log10_exp_bound() + other.adjusted()
2307 if (self_adj >= 0) == (other._sign == 0):
2308 # self > 1 and other +ve, or self < 1 and other -ve
2309 # possibility of overflow
2310 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002311 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002312 else:
2313 # self > 1 and other -ve, or self < 1 and other +ve
2314 # possibility of underflow to 0
2315 Etiny = context.Etiny()
2316 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002317 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002318
2319 # try for an exact result with precision +1
2320 if ans is None:
2321 ans = self._power_exact(other, context.prec + 1)
2322 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002323 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002324
2325 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2326 if ans is None:
2327 p = context.prec
2328 x = _WorkRep(self)
2329 xc, xe = x.int, x.exp
2330 y = _WorkRep(other)
2331 yc, ye = y.int, y.exp
2332 if y.sign == 1:
2333 yc = -yc
2334
2335 # compute correctly rounded result: start with precision +3,
2336 # then increase precision until result is unambiguously roundable
2337 extra = 3
2338 while True:
2339 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2340 if coeff % (5*10**(len(str(coeff))-p-1)):
2341 break
2342 extra += 3
2343
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002344 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002345
2346 # the specification says that for non-integer other we need to
2347 # raise Inexact, even when the result is actually exact. In
2348 # the same way, we need to raise Underflow here if the result
2349 # is subnormal. (The call to _fix will take care of raising
2350 # Rounded and Subnormal, as usual.)
2351 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002352 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002353 # pad with zeros up to length context.prec+1 if necessary
2354 if len(ans._int) <= context.prec:
2355 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002356 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2357 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002358 if ans.adjusted() < context.Emin:
2359 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002360
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002361 # unlike exp, ln and log10, the power function respects the
2362 # rounding mode; no need to use ROUND_HALF_EVEN here
2363 ans = ans._fix(context)
2364 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002365
2366 def __rpow__(self, other, context=None):
2367 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002368 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002369 if other is NotImplemented:
2370 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002371 return other.__pow__(self, context=context)
2372
2373 def normalize(self, context=None):
2374 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002375
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002376 if context is None:
2377 context = getcontext()
2378
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002379 if self._is_special:
2380 ans = self._check_nans(context=context)
2381 if ans:
2382 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002383
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002384 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002385 if dup._isinfinity():
2386 return dup
2387
2388 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002389 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002390 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002391 end = len(dup._int)
2392 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002393 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002394 exp += 1
2395 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002396 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002397
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002398 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002399 """Quantize self so its exponent is the same as that of exp.
2400
2401 Similar to self._rescale(exp._exp) but with error checking.
2402 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002403 exp = _convert_other(exp, raiseit=True)
2404
2405 if context is None:
2406 context = getcontext()
2407 if rounding is None:
2408 rounding = context.rounding
2409
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002410 if self._is_special or exp._is_special:
2411 ans = self._check_nans(exp, context)
2412 if ans:
2413 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002414
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002415 if exp._isinfinity() or self._isinfinity():
2416 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002417 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002418 return context._raise_error(InvalidOperation,
2419 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002420
2421 # if we're not watching exponents, do a simple rescale
2422 if not watchexp:
2423 ans = self._rescale(exp._exp, rounding)
2424 # raise Inexact and Rounded where appropriate
2425 if ans._exp > self._exp:
2426 context._raise_error(Rounded)
2427 if ans != self:
2428 context._raise_error(Inexact)
2429 return ans
2430
2431 # exp._exp should be between Etiny and Emax
2432 if not (context.Etiny() <= exp._exp <= context.Emax):
2433 return context._raise_error(InvalidOperation,
2434 'target exponent out of bounds in quantize')
2435
2436 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002437 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002438 return ans._fix(context)
2439
2440 self_adjusted = self.adjusted()
2441 if self_adjusted > context.Emax:
2442 return context._raise_error(InvalidOperation,
2443 'exponent of quantize result too large for current context')
2444 if self_adjusted - exp._exp + 1 > context.prec:
2445 return context._raise_error(InvalidOperation,
2446 'quantize result has too many digits for current context')
2447
2448 ans = self._rescale(exp._exp, rounding)
2449 if ans.adjusted() > context.Emax:
2450 return context._raise_error(InvalidOperation,
2451 'exponent of quantize result too large for current context')
2452 if len(ans._int) > context.prec:
2453 return context._raise_error(InvalidOperation,
2454 'quantize result has too many digits for current context')
2455
2456 # raise appropriate flags
2457 if ans._exp > self._exp:
2458 context._raise_error(Rounded)
2459 if ans != self:
2460 context._raise_error(Inexact)
2461 if ans and ans.adjusted() < context.Emin:
2462 context._raise_error(Subnormal)
2463
2464 # call to fix takes care of any necessary folddown
2465 ans = ans._fix(context)
2466 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002467
2468 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002469 """Return True if self and other have the same exponent; otherwise
2470 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002471
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002472 If either operand is a special value, the following rules are used:
2473 * return True if both operands are infinities
2474 * return True if both operands are NaNs
2475 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002476 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002477 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002478 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002479 return (self.is_nan() and other.is_nan() or
2480 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002481 return self._exp == other._exp
2482
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002483 def _rescale(self, exp, rounding):
2484 """Rescale self so that the exponent is exp, either by padding with zeros
2485 or by truncating digits, using the given rounding mode.
2486
2487 Specials are returned without change. This operation is
2488 quiet: it raises no flags, and uses no information from the
2489 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002490
2491 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002492 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002493 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002494 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002495 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002496 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002497 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002498
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002499 if self._exp >= exp:
2500 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002501 return _dec_from_triple(self._sign,
2502 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002503
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002504 # too many digits; round and lose data. If self.adjusted() <
2505 # exp-1, replace self by 10**(exp-1) before rounding
2506 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002507 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002508 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002509 digits = 0
2510 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002511 changed = this_function(digits)
2512 coeff = self._int[:digits] or '0'
2513 if changed == 1:
2514 coeff = str(int(coeff)+1)
2515 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002516
Christian Heimesf16baeb2008-02-29 14:57:44 +00002517 def _round(self, places, rounding):
2518 """Round a nonzero, nonspecial Decimal to a fixed number of
2519 significant figures, using the given rounding mode.
2520
2521 Infinities, NaNs and zeros are returned unaltered.
2522
2523 This operation is quiet: it raises no flags, and uses no
2524 information from the context.
2525
2526 """
2527 if places <= 0:
2528 raise ValueError("argument should be at least 1 in _round")
2529 if self._is_special or not self:
2530 return Decimal(self)
2531 ans = self._rescale(self.adjusted()+1-places, rounding)
2532 # it can happen that the rescale alters the adjusted exponent;
2533 # for example when rounding 99.97 to 3 significant figures.
2534 # When this happens we end up with an extra 0 at the end of
2535 # the number; a second rescale fixes this.
2536 if ans.adjusted() != self.adjusted():
2537 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2538 return ans
2539
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002540 def to_integral_exact(self, rounding=None, context=None):
2541 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002542
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002543 If no rounding mode is specified, take the rounding mode from
2544 the context. This method raises the Rounded and Inexact flags
2545 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002546
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002547 See also: to_integral_value, which does exactly the same as
2548 this method except that it doesn't raise Inexact or Rounded.
2549 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002550 if self._is_special:
2551 ans = self._check_nans(context=context)
2552 if ans:
2553 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002554 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002555 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002556 return Decimal(self)
2557 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002558 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002559 if context is None:
2560 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002561 if rounding is None:
2562 rounding = context.rounding
2563 context._raise_error(Rounded)
2564 ans = self._rescale(0, rounding)
2565 if ans != self:
2566 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002567 return ans
2568
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002569 def to_integral_value(self, rounding=None, context=None):
2570 """Rounds to the nearest integer, without raising inexact, rounded."""
2571 if context is None:
2572 context = getcontext()
2573 if rounding is None:
2574 rounding = context.rounding
2575 if self._is_special:
2576 ans = self._check_nans(context=context)
2577 if ans:
2578 return ans
2579 return Decimal(self)
2580 if self._exp >= 0:
2581 return Decimal(self)
2582 else:
2583 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002584
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002585 # the method name changed, but we provide also the old one, for compatibility
2586 to_integral = to_integral_value
2587
2588 def sqrt(self, context=None):
2589 """Return the square root of self."""
Christian Heimes0348fb62008-03-26 12:55:56 +00002590 if context is None:
2591 context = getcontext()
2592
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002593 if self._is_special:
2594 ans = self._check_nans(context=context)
2595 if ans:
2596 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002597
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002598 if self._isinfinity() and self._sign == 0:
2599 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002600
2601 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002602 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002603 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002604 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002605
2606 if self._sign == 1:
2607 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2608
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002609 # At this point self represents a positive number. Let p be
2610 # the desired precision and express self in the form c*100**e
2611 # with c a positive real number and e an integer, c and e
2612 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2613 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2614 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2615 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2616 # the closest integer to sqrt(c) with the even integer chosen
2617 # in the case of a tie.
2618 #
2619 # To ensure correct rounding in all cases, we use the
2620 # following trick: we compute the square root to an extra
2621 # place (precision p+1 instead of precision p), rounding down.
2622 # Then, if the result is inexact and its last digit is 0 or 5,
2623 # we increase the last digit to 1 or 6 respectively; if it's
2624 # exact we leave the last digit alone. Now the final round to
2625 # p places (or fewer in the case of underflow) will round
2626 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002627
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002628 # use an extra digit of precision
2629 prec = context.prec+1
2630
2631 # write argument in the form c*100**e where e = self._exp//2
2632 # is the 'ideal' exponent, to be used if the square root is
2633 # exactly representable. l is the number of 'digits' of c in
2634 # base 100, so that 100**(l-1) <= c < 100**l.
2635 op = _WorkRep(self)
2636 e = op.exp >> 1
2637 if op.exp & 1:
2638 c = op.int * 10
2639 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002640 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002641 c = op.int
2642 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002643
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002644 # rescale so that c has exactly prec base 100 'digits'
2645 shift = prec-l
2646 if shift >= 0:
2647 c *= 100**shift
2648 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002649 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002650 c, remainder = divmod(c, 100**-shift)
2651 exact = not remainder
2652 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002653
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002654 # find n = floor(sqrt(c)) using Newton's method
2655 n = 10**prec
2656 while True:
2657 q = c//n
2658 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002659 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002660 else:
2661 n = n + q >> 1
2662 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002663
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002664 if exact:
2665 # result is exact; rescale to use ideal exponent e
2666 if shift >= 0:
2667 # assert n % 10**shift == 0
2668 n //= 10**shift
2669 else:
2670 n *= 10**-shift
2671 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002672 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002673 # result is not exact; fix last digit as described above
2674 if n % 5 == 0:
2675 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002676
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002677 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002678
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002679 # round, and fit to current context
2680 context = context._shallow_copy()
2681 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002682 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002683 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002684
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002685 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002686
2687 def max(self, other, context=None):
2688 """Returns the larger value.
2689
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002690 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002691 NaN (and signals if one is sNaN). Also rounds.
2692 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002693 other = _convert_other(other, raiseit=True)
2694
2695 if context is None:
2696 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002697
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002698 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002699 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002700 # number is always returned
2701 sn = self._isnan()
2702 on = other._isnan()
2703 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002704 if on == 1 and sn == 0:
2705 return self._fix(context)
2706 if sn == 1 and on == 0:
2707 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002708 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002709
Christian Heimes77c02eb2008-02-09 02:18:51 +00002710 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002711 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002712 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002713 # then an ordering is applied:
2714 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002715 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002716 # positive sign and min returns the operand with the negative sign
2717 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002718 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002719 # the result. This is exactly the ordering used in compare_total.
2720 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002721
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002722 if c == -1:
2723 ans = other
2724 else:
2725 ans = self
2726
Christian Heimes2c181612007-12-17 20:04:13 +00002727 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002728
2729 def min(self, other, context=None):
2730 """Returns the smaller value.
2731
Guido van Rossumd8faa362007-04-27 19:54:29 +00002732 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002733 NaN (and signals if one is sNaN). Also rounds.
2734 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002735 other = _convert_other(other, raiseit=True)
2736
2737 if context is None:
2738 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002739
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002740 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002741 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002742 # number is always returned
2743 sn = self._isnan()
2744 on = other._isnan()
2745 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002746 if on == 1 and sn == 0:
2747 return self._fix(context)
2748 if sn == 1 and on == 0:
2749 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002750 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002751
Christian Heimes77c02eb2008-02-09 02:18:51 +00002752 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002753 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002754 c = self.compare_total(other)
2755
2756 if c == -1:
2757 ans = self
2758 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002759 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002760
Christian Heimes2c181612007-12-17 20:04:13 +00002761 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002762
2763 def _isinteger(self):
2764 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002765 if self._is_special:
2766 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002767 if self._exp >= 0:
2768 return True
2769 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002770 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002771
2772 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002773 """Returns True if self is even. Assumes self is an integer."""
2774 if not self or self._exp > 0:
2775 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002776 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002777
2778 def adjusted(self):
2779 """Return the adjusted exponent of self"""
2780 try:
2781 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002782 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002783 except TypeError:
2784 return 0
2785
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002786 def canonical(self, context=None):
2787 """Returns the same Decimal object.
2788
2789 As we do not have different encodings for the same number, the
2790 received object already is in its canonical form.
2791 """
2792 return self
2793
2794 def compare_signal(self, other, context=None):
2795 """Compares self to the other operand numerically.
2796
2797 It's pretty much like compare(), but all NaNs signal, with signaling
2798 NaNs taking precedence over quiet NaNs.
2799 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002800 other = _convert_other(other, raiseit = True)
2801 ans = self._compare_check_nans(other, context)
2802 if ans:
2803 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002804 return self.compare(other, context=context)
2805
2806 def compare_total(self, other):
2807 """Compares self to other using the abstract representations.
2808
2809 This is not like the standard compare, which use their numerical
2810 value. Note that a total ordering is defined for all possible abstract
2811 representations.
2812 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00002813 other = _convert_other(other, raiseit=True)
2814
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002815 # if one is negative and the other is positive, it's easy
2816 if self._sign and not other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002817 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002818 if not self._sign and other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002819 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002820 sign = self._sign
2821
2822 # let's handle both NaN types
2823 self_nan = self._isnan()
2824 other_nan = other._isnan()
2825 if self_nan or other_nan:
2826 if self_nan == other_nan:
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002827 # compare payloads as though they're integers
2828 self_key = len(self._int), self._int
2829 other_key = len(other._int), other._int
2830 if self_key < other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002831 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002832 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002833 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002834 return _NegativeOne
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002835 if self_key > other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002836 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002837 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002838 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002839 return _One
2840 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002841
2842 if sign:
2843 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002844 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002845 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002846 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002847 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002848 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002849 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002850 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002851 else:
2852 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002853 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002854 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002855 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002856 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002857 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002858 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002859 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002860
2861 if self < other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002862 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002863 if self > other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002864 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002865
2866 if self._exp < other._exp:
2867 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002868 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002869 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002870 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002871 if self._exp > other._exp:
2872 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002873 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002874 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002875 return _One
2876 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002877
2878
2879 def compare_total_mag(self, other):
2880 """Compares self to other using abstract repr., ignoring sign.
2881
2882 Like compare_total, but with operand's sign ignored and assumed to be 0.
2883 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00002884 other = _convert_other(other, raiseit=True)
2885
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002886 s = self.copy_abs()
2887 o = other.copy_abs()
2888 return s.compare_total(o)
2889
2890 def copy_abs(self):
2891 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002892 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002893
2894 def copy_negate(self):
2895 """Returns a copy with the sign inverted."""
2896 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002897 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002898 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002899 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002900
2901 def copy_sign(self, other):
2902 """Returns self with the sign of other."""
Mark Dickinson84230a12010-02-18 14:49:50 +00002903 other = _convert_other(other, raiseit=True)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002904 return _dec_from_triple(other._sign, self._int,
2905 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002906
2907 def exp(self, context=None):
2908 """Returns e ** self."""
2909
2910 if context is None:
2911 context = getcontext()
2912
2913 # exp(NaN) = NaN
2914 ans = self._check_nans(context=context)
2915 if ans:
2916 return ans
2917
2918 # exp(-Infinity) = 0
2919 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002920 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002921
2922 # exp(0) = 1
2923 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002924 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002925
2926 # exp(Infinity) = Infinity
2927 if self._isinfinity() == 1:
2928 return Decimal(self)
2929
2930 # the result is now guaranteed to be inexact (the true
2931 # mathematical result is transcendental). There's no need to
2932 # raise Rounded and Inexact here---they'll always be raised as
2933 # a result of the call to _fix.
2934 p = context.prec
2935 adj = self.adjusted()
2936
2937 # we only need to do any computation for quite a small range
2938 # of adjusted exponents---for example, -29 <= adj <= 10 for
2939 # the default context. For smaller exponent the result is
2940 # indistinguishable from 1 at the given precision, while for
2941 # larger exponent the result either overflows or underflows.
2942 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2943 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002944 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002945 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2946 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002947 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002948 elif self._sign == 0 and adj < -p:
2949 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002950 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002951 elif self._sign == 1 and adj < -p-1:
2952 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002953 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002954 # general case
2955 else:
2956 op = _WorkRep(self)
2957 c, e = op.int, op.exp
2958 if op.sign == 1:
2959 c = -c
2960
2961 # compute correctly rounded result: increase precision by
2962 # 3 digits at a time until we get an unambiguously
2963 # roundable result
2964 extra = 3
2965 while True:
2966 coeff, exp = _dexp(c, e, p+extra)
2967 if coeff % (5*10**(len(str(coeff))-p-1)):
2968 break
2969 extra += 3
2970
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002971 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002972
2973 # at this stage, ans should round correctly with *any*
2974 # rounding mode, not just with ROUND_HALF_EVEN
2975 context = context._shallow_copy()
2976 rounding = context._set_rounding(ROUND_HALF_EVEN)
2977 ans = ans._fix(context)
2978 context.rounding = rounding
2979
2980 return ans
2981
2982 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002983 """Return True if self is canonical; otherwise return False.
2984
2985 Currently, the encoding of a Decimal instance is always
2986 canonical, so this method returns True for any Decimal.
2987 """
2988 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002989
2990 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002991 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002992
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002993 A Decimal instance is considered finite if it is neither
2994 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002995 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002996 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002997
2998 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002999 """Return True if self is infinite; otherwise return False."""
3000 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003001
3002 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003003 """Return True if self is a qNaN or sNaN; otherwise return False."""
3004 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003005
3006 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003007 """Return True if self is a normal number; otherwise return False."""
3008 if self._is_special or not self:
3009 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003010 if context is None:
3011 context = getcontext()
Mark Dickinson06bb6742009-10-20 13:38:04 +00003012 return context.Emin <= self.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003013
3014 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003015 """Return True if self is a quiet NaN; otherwise return False."""
3016 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003017
3018 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003019 """Return True if self is negative; otherwise return False."""
3020 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003021
3022 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003023 """Return True if self is a signaling NaN; otherwise return False."""
3024 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003025
3026 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003027 """Return True if self is subnormal; otherwise return False."""
3028 if self._is_special or not self:
3029 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003030 if context is None:
3031 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003032 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003033
3034 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003035 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003036 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003037
3038 def _ln_exp_bound(self):
3039 """Compute a lower bound for the adjusted exponent of self.ln().
3040 In other words, compute r such that self.ln() >= 10**r. Assumes
3041 that self is finite and positive and that self != 1.
3042 """
3043
3044 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
3045 adj = self._exp + len(self._int) - 1
3046 if adj >= 1:
3047 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
3048 return len(str(adj*23//10)) - 1
3049 if adj <= -2:
3050 # argument <= 0.1
3051 return len(str((-1-adj)*23//10)) - 1
3052 op = _WorkRep(self)
3053 c, e = op.int, op.exp
3054 if adj == 0:
3055 # 1 < self < 10
3056 num = str(c-10**-e)
3057 den = str(c)
3058 return len(num) - len(den) - (num < den)
3059 # adj == -1, 0.1 <= self < 1
3060 return e + len(str(10**-e - c)) - 1
3061
3062
3063 def ln(self, context=None):
3064 """Returns the natural (base e) logarithm of self."""
3065
3066 if context is None:
3067 context = getcontext()
3068
3069 # ln(NaN) = NaN
3070 ans = self._check_nans(context=context)
3071 if ans:
3072 return ans
3073
3074 # ln(0.0) == -Infinity
3075 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003076 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003077
3078 # ln(Infinity) = Infinity
3079 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003080 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003081
3082 # ln(1.0) == 0.0
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003083 if self == _One:
3084 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003085
3086 # ln(negative) raises InvalidOperation
3087 if self._sign == 1:
3088 return context._raise_error(InvalidOperation,
3089 'ln of a negative value')
3090
3091 # result is irrational, so necessarily inexact
3092 op = _WorkRep(self)
3093 c, e = op.int, op.exp
3094 p = context.prec
3095
3096 # correctly rounded result: repeatedly increase precision by 3
3097 # until we get an unambiguously roundable result
3098 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3099 while True:
3100 coeff = _dlog(c, e, places)
3101 # assert len(str(abs(coeff)))-p >= 1
3102 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3103 break
3104 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003105 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003106
3107 context = context._shallow_copy()
3108 rounding = context._set_rounding(ROUND_HALF_EVEN)
3109 ans = ans._fix(context)
3110 context.rounding = rounding
3111 return ans
3112
3113 def _log10_exp_bound(self):
3114 """Compute a lower bound for the adjusted exponent of self.log10().
3115 In other words, find r such that self.log10() >= 10**r.
3116 Assumes that self is finite and positive and that self != 1.
3117 """
3118
3119 # For x >= 10 or x < 0.1 we only need a bound on the integer
3120 # part of log10(self), and this comes directly from the
3121 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3122 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3123 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3124
3125 adj = self._exp + len(self._int) - 1
3126 if adj >= 1:
3127 # self >= 10
3128 return len(str(adj))-1
3129 if adj <= -2:
3130 # self < 0.1
3131 return len(str(-1-adj))-1
3132 op = _WorkRep(self)
3133 c, e = op.int, op.exp
3134 if adj == 0:
3135 # 1 < self < 10
3136 num = str(c-10**-e)
3137 den = str(231*c)
3138 return len(num) - len(den) - (num < den) + 2
3139 # adj == -1, 0.1 <= self < 1
3140 num = str(10**-e-c)
3141 return len(num) + e - (num < "231") - 1
3142
3143 def log10(self, context=None):
3144 """Returns the base 10 logarithm of self."""
3145
3146 if context is None:
3147 context = getcontext()
3148
3149 # log10(NaN) = NaN
3150 ans = self._check_nans(context=context)
3151 if ans:
3152 return ans
3153
3154 # log10(0.0) == -Infinity
3155 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003156 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003157
3158 # log10(Infinity) = Infinity
3159 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003160 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003161
3162 # log10(negative or -Infinity) raises InvalidOperation
3163 if self._sign == 1:
3164 return context._raise_error(InvalidOperation,
3165 'log10 of a negative value')
3166
3167 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003168 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003169 # answer may need rounding
3170 ans = Decimal(self._exp + len(self._int) - 1)
3171 else:
3172 # result is irrational, so necessarily inexact
3173 op = _WorkRep(self)
3174 c, e = op.int, op.exp
3175 p = context.prec
3176
3177 # correctly rounded result: repeatedly increase precision
3178 # until result is unambiguously roundable
3179 places = p-self._log10_exp_bound()+2
3180 while True:
3181 coeff = _dlog10(c, e, places)
3182 # assert len(str(abs(coeff)))-p >= 1
3183 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3184 break
3185 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003186 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003187
3188 context = context._shallow_copy()
3189 rounding = context._set_rounding(ROUND_HALF_EVEN)
3190 ans = ans._fix(context)
3191 context.rounding = rounding
3192 return ans
3193
3194 def logb(self, context=None):
3195 """ Returns the exponent of the magnitude of self's MSD.
3196
3197 The result is the integer which is the exponent of the magnitude
3198 of the most significant digit of self (as though it were truncated
3199 to a single digit while maintaining the value of that digit and
3200 without limiting the resulting exponent).
3201 """
3202 # logb(NaN) = NaN
3203 ans = self._check_nans(context=context)
3204 if ans:
3205 return ans
3206
3207 if context is None:
3208 context = getcontext()
3209
3210 # logb(+/-Inf) = +Inf
3211 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003212 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003213
3214 # logb(0) = -Inf, DivisionByZero
3215 if not self:
3216 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3217
3218 # otherwise, simply return the adjusted exponent of self, as a
3219 # Decimal. Note that no attempt is made to fit the result
3220 # into the current context.
Mark Dickinson56df8872009-10-07 19:23:50 +00003221 ans = Decimal(self.adjusted())
3222 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003223
3224 def _islogical(self):
3225 """Return True if self is a logical operand.
3226
Christian Heimes679db4a2008-01-18 09:56:22 +00003227 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003228 an exponent of 0, and a coefficient whose digits must all be
3229 either 0 or 1.
3230 """
3231 if self._sign != 0 or self._exp != 0:
3232 return False
3233 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003234 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003235 return False
3236 return True
3237
3238 def _fill_logical(self, context, opa, opb):
3239 dif = context.prec - len(opa)
3240 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003241 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003242 elif dif < 0:
3243 opa = opa[-context.prec:]
3244 dif = context.prec - len(opb)
3245 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003246 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003247 elif dif < 0:
3248 opb = opb[-context.prec:]
3249 return opa, opb
3250
3251 def logical_and(self, other, context=None):
3252 """Applies an 'and' operation between self and other's digits."""
3253 if context is None:
3254 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003255
3256 other = _convert_other(other, raiseit=True)
3257
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003258 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
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003265 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3266 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003267
3268 def logical_invert(self, context=None):
3269 """Invert all its digits."""
3270 if context is None:
3271 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003272 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3273 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003274
3275 def logical_or(self, other, context=None):
3276 """Applies an 'or' operation between self and other's digits."""
3277 if context is None:
3278 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003279
3280 other = _convert_other(other, raiseit=True)
3281
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003282 if not self._islogical() or not other._islogical():
3283 return context._raise_error(InvalidOperation)
3284
3285 # fill to context.prec
3286 (opa, opb) = self._fill_logical(context, self._int, other._int)
3287
3288 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003289 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003290 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003291
3292 def logical_xor(self, other, context=None):
3293 """Applies an 'xor' operation between self and other's digits."""
3294 if context is None:
3295 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003296
3297 other = _convert_other(other, raiseit=True)
3298
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003299 if not self._islogical() or not other._islogical():
3300 return context._raise_error(InvalidOperation)
3301
3302 # fill to context.prec
3303 (opa, opb) = self._fill_logical(context, self._int, other._int)
3304
3305 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003306 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003307 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003308
3309 def max_mag(self, other, context=None):
3310 """Compares the values numerically with their sign ignored."""
3311 other = _convert_other(other, raiseit=True)
3312
3313 if context is None:
3314 context = getcontext()
3315
3316 if self._is_special or other._is_special:
3317 # If one operand is a quiet NaN and the other is number, then the
3318 # number is always returned
3319 sn = self._isnan()
3320 on = other._isnan()
3321 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003322 if on == 1 and sn == 0:
3323 return self._fix(context)
3324 if sn == 1 and on == 0:
3325 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003326 return self._check_nans(other, context)
3327
Christian Heimes77c02eb2008-02-09 02:18:51 +00003328 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003329 if c == 0:
3330 c = self.compare_total(other)
3331
3332 if c == -1:
3333 ans = other
3334 else:
3335 ans = self
3336
Christian Heimes2c181612007-12-17 20:04:13 +00003337 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003338
3339 def min_mag(self, other, context=None):
3340 """Compares the values numerically with their sign ignored."""
3341 other = _convert_other(other, raiseit=True)
3342
3343 if context is None:
3344 context = getcontext()
3345
3346 if self._is_special or other._is_special:
3347 # If one operand is a quiet NaN and the other is number, then the
3348 # number is always returned
3349 sn = self._isnan()
3350 on = other._isnan()
3351 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003352 if on == 1 and sn == 0:
3353 return self._fix(context)
3354 if sn == 1 and on == 0:
3355 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003356 return self._check_nans(other, context)
3357
Christian Heimes77c02eb2008-02-09 02:18:51 +00003358 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003359 if c == 0:
3360 c = self.compare_total(other)
3361
3362 if c == -1:
3363 ans = self
3364 else:
3365 ans = other
3366
Christian Heimes2c181612007-12-17 20:04:13 +00003367 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003368
3369 def next_minus(self, context=None):
3370 """Returns the largest representable number smaller than itself."""
3371 if context is None:
3372 context = getcontext()
3373
3374 ans = self._check_nans(context=context)
3375 if ans:
3376 return ans
3377
3378 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003379 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003380 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003381 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003382
3383 context = context.copy()
3384 context._set_rounding(ROUND_FLOOR)
3385 context._ignore_all_flags()
3386 new_self = self._fix(context)
3387 if new_self != self:
3388 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003389 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3390 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003391
3392 def next_plus(self, context=None):
3393 """Returns the smallest representable number larger than itself."""
3394 if context is None:
3395 context = getcontext()
3396
3397 ans = self._check_nans(context=context)
3398 if ans:
3399 return ans
3400
3401 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003402 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003403 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003404 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003405
3406 context = context.copy()
3407 context._set_rounding(ROUND_CEILING)
3408 context._ignore_all_flags()
3409 new_self = self._fix(context)
3410 if new_self != self:
3411 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003412 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3413 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003414
3415 def next_toward(self, other, context=None):
3416 """Returns the number closest to self, in the direction towards other.
3417
3418 The result is the closest representable number to self
3419 (excluding self) that is in the direction towards other,
3420 unless both have the same value. If the two operands are
3421 numerically equal, then the result is a copy of self with the
3422 sign set to be the same as the sign of other.
3423 """
3424 other = _convert_other(other, raiseit=True)
3425
3426 if context is None:
3427 context = getcontext()
3428
3429 ans = self._check_nans(other, context)
3430 if ans:
3431 return ans
3432
Christian Heimes77c02eb2008-02-09 02:18:51 +00003433 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003434 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003435 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003436
3437 if comparison == -1:
3438 ans = self.next_plus(context)
3439 else: # comparison == 1
3440 ans = self.next_minus(context)
3441
3442 # decide which flags to raise using value of ans
3443 if ans._isinfinity():
3444 context._raise_error(Overflow,
3445 'Infinite result from next_toward',
3446 ans._sign)
3447 context._raise_error(Rounded)
3448 context._raise_error(Inexact)
3449 elif ans.adjusted() < context.Emin:
3450 context._raise_error(Underflow)
3451 context._raise_error(Subnormal)
3452 context._raise_error(Rounded)
3453 context._raise_error(Inexact)
3454 # if precision == 1 then we don't raise Clamped for a
3455 # result 0E-Etiny.
3456 if not ans:
3457 context._raise_error(Clamped)
3458
3459 return ans
3460
3461 def number_class(self, context=None):
3462 """Returns an indication of the class of self.
3463
3464 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003465 sNaN
3466 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003467 -Infinity
3468 -Normal
3469 -Subnormal
3470 -Zero
3471 +Zero
3472 +Subnormal
3473 +Normal
3474 +Infinity
3475 """
3476 if self.is_snan():
3477 return "sNaN"
3478 if self.is_qnan():
3479 return "NaN"
3480 inf = self._isinfinity()
3481 if inf == 1:
3482 return "+Infinity"
3483 if inf == -1:
3484 return "-Infinity"
3485 if self.is_zero():
3486 if self._sign:
3487 return "-Zero"
3488 else:
3489 return "+Zero"
3490 if context is None:
3491 context = getcontext()
3492 if self.is_subnormal(context=context):
3493 if self._sign:
3494 return "-Subnormal"
3495 else:
3496 return "+Subnormal"
3497 # just a normal, regular, boring number, :)
3498 if self._sign:
3499 return "-Normal"
3500 else:
3501 return "+Normal"
3502
3503 def radix(self):
3504 """Just returns 10, as this is Decimal, :)"""
3505 return Decimal(10)
3506
3507 def rotate(self, other, context=None):
3508 """Returns a rotated copy of self, value-of-other times."""
3509 if context is None:
3510 context = getcontext()
3511
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003512 other = _convert_other(other, raiseit=True)
3513
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003514 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 if not (-context.prec <= int(other) <= context.prec):
3521 return context._raise_error(InvalidOperation)
3522
3523 if self._isinfinity():
3524 return Decimal(self)
3525
3526 # get values, pad if necessary
3527 torot = int(other)
3528 rotdig = self._int
3529 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003530 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003531 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003532 elif topad < 0:
3533 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003534
3535 # let's rotate!
3536 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003537 return _dec_from_triple(self._sign,
3538 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003539
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003540 def scaleb(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003541 """Returns self operand after adding the second value to its exp."""
3542 if context is None:
3543 context = getcontext()
3544
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003545 other = _convert_other(other, raiseit=True)
3546
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003547 ans = self._check_nans(other, context)
3548 if ans:
3549 return ans
3550
3551 if other._exp != 0:
3552 return context._raise_error(InvalidOperation)
3553 liminf = -2 * (context.Emax + context.prec)
3554 limsup = 2 * (context.Emax + context.prec)
3555 if not (liminf <= int(other) <= limsup):
3556 return context._raise_error(InvalidOperation)
3557
3558 if self._isinfinity():
3559 return Decimal(self)
3560
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003561 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003562 d = d._fix(context)
3563 return d
3564
3565 def shift(self, other, context=None):
3566 """Returns a shifted copy of self, value-of-other times."""
3567 if context is None:
3568 context = getcontext()
3569
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003570 other = _convert_other(other, raiseit=True)
3571
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003572 ans = self._check_nans(other, context)
3573 if ans:
3574 return ans
3575
3576 if other._exp != 0:
3577 return context._raise_error(InvalidOperation)
3578 if not (-context.prec <= int(other) <= context.prec):
3579 return context._raise_error(InvalidOperation)
3580
3581 if self._isinfinity():
3582 return Decimal(self)
3583
3584 # get values, pad if necessary
3585 torot = int(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003586 rotdig = self._int
3587 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003588 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003589 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003590 elif topad < 0:
3591 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003592
3593 # let's shift!
3594 if torot < 0:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003595 shifted = rotdig[:torot]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003596 else:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003597 shifted = rotdig + '0'*torot
3598 shifted = shifted[-context.prec:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003599
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003600 return _dec_from_triple(self._sign,
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003601 shifted.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003602
Guido van Rossumd8faa362007-04-27 19:54:29 +00003603 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003604 def __reduce__(self):
3605 return (self.__class__, (str(self),))
3606
3607 def __copy__(self):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003608 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003609 return self # I'm immutable; therefore I am my own clone
3610 return self.__class__(str(self))
3611
3612 def __deepcopy__(self, memo):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003613 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003614 return self # My components are also immutable
3615 return self.__class__(str(self))
3616
Mark Dickinson79f52032009-03-17 23:12:51 +00003617 # PEP 3101 support. the _localeconv keyword argument should be
3618 # considered private: it's provided for ease of testing only.
3619 def __format__(self, specifier, context=None, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00003620 """Format a Decimal instance according to the given specifier.
3621
3622 The specifier should be a standard format specifier, with the
3623 form described in PEP 3101. Formatting types 'e', 'E', 'f',
Mark Dickinson79f52032009-03-17 23:12:51 +00003624 'F', 'g', 'G', 'n' and '%' are supported. If the formatting
3625 type is omitted it defaults to 'g' or 'G', depending on the
3626 value of context.capitals.
Christian Heimesf16baeb2008-02-29 14:57:44 +00003627 """
3628
3629 # Note: PEP 3101 says that if the type is not present then
3630 # there should be at least one digit after the decimal point.
3631 # We take the liberty of ignoring this requirement for
3632 # Decimal---it's presumably there to make sure that
3633 # format(float, '') behaves similarly to str(float).
3634 if context is None:
3635 context = getcontext()
3636
Mark Dickinson79f52032009-03-17 23:12:51 +00003637 spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003638
Mark Dickinson79f52032009-03-17 23:12:51 +00003639 # special values don't care about the type or precision
Christian Heimesf16baeb2008-02-29 14:57:44 +00003640 if self._is_special:
Mark Dickinson79f52032009-03-17 23:12:51 +00003641 sign = _format_sign(self._sign, spec)
3642 body = str(self.copy_abs())
3643 return _format_align(sign, body, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003644
3645 # a type of None defaults to 'g' or 'G', depending on context
Christian Heimesf16baeb2008-02-29 14:57:44 +00003646 if spec['type'] is None:
3647 spec['type'] = ['g', 'G'][context.capitals]
Mark Dickinson79f52032009-03-17 23:12:51 +00003648
3649 # if type is '%', adjust exponent of self accordingly
3650 if spec['type'] == '%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003651 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3652
3653 # round if necessary, taking rounding mode from the context
3654 rounding = context.rounding
3655 precision = spec['precision']
3656 if precision is not None:
3657 if spec['type'] in 'eE':
3658 self = self._round(precision+1, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003659 elif spec['type'] in 'fF%':
3660 self = self._rescale(-precision, rounding)
Mark Dickinson79f52032009-03-17 23:12:51 +00003661 elif spec['type'] in 'gG' and len(self._int) > precision:
3662 self = self._round(precision, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003663 # special case: zeros with a positive exponent can't be
3664 # represented in fixed point; rescale them to 0e0.
Mark Dickinson79f52032009-03-17 23:12:51 +00003665 if not self and self._exp > 0 and spec['type'] in 'fF%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003666 self = self._rescale(0, rounding)
3667
3668 # figure out placement of the decimal point
3669 leftdigits = self._exp + len(self._int)
Mark Dickinson79f52032009-03-17 23:12:51 +00003670 if spec['type'] in 'eE':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003671 if not self and precision is not None:
3672 dotplace = 1 - precision
3673 else:
3674 dotplace = 1
Mark Dickinson79f52032009-03-17 23:12:51 +00003675 elif spec['type'] in 'fF%':
3676 dotplace = leftdigits
Christian Heimesf16baeb2008-02-29 14:57:44 +00003677 elif spec['type'] in 'gG':
3678 if self._exp <= 0 and leftdigits > -6:
3679 dotplace = leftdigits
3680 else:
3681 dotplace = 1
3682
Mark Dickinson79f52032009-03-17 23:12:51 +00003683 # find digits before and after decimal point, and get exponent
3684 if dotplace < 0:
3685 intpart = '0'
3686 fracpart = '0'*(-dotplace) + self._int
3687 elif dotplace > len(self._int):
3688 intpart = self._int + '0'*(dotplace-len(self._int))
3689 fracpart = ''
Christian Heimesf16baeb2008-02-29 14:57:44 +00003690 else:
Mark Dickinson79f52032009-03-17 23:12:51 +00003691 intpart = self._int[:dotplace] or '0'
3692 fracpart = self._int[dotplace:]
3693 exp = leftdigits-dotplace
Christian Heimesf16baeb2008-02-29 14:57:44 +00003694
Mark Dickinson79f52032009-03-17 23:12:51 +00003695 # done with the decimal-specific stuff; hand over the rest
3696 # of the formatting to the _format_number function
3697 return _format_number(self._sign, intpart, fracpart, exp, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003698
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003699def _dec_from_triple(sign, coefficient, exponent, special=False):
3700 """Create a decimal instance directly, without any validation,
3701 normalization (e.g. removal of leading zeros) or argument
3702 conversion.
3703
3704 This function is for *internal use only*.
3705 """
3706
3707 self = object.__new__(Decimal)
3708 self._sign = sign
3709 self._int = coefficient
3710 self._exp = exponent
3711 self._is_special = special
3712
3713 return self
3714
Raymond Hettinger82417ca2009-02-03 03:54:28 +00003715# Register Decimal as a kind of Number (an abstract base class).
3716# However, do not register it as Real (because Decimals are not
3717# interoperable with floats).
3718_numbers.Number.register(Decimal)
3719
3720
Guido van Rossumd8faa362007-04-27 19:54:29 +00003721##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003722
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003723
3724# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003725rounding_functions = [name for name in Decimal.__dict__.keys()
3726 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003727for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003728 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003729 globalname = name[1:].upper()
3730 val = globals()[globalname]
3731 Decimal._pick_rounding_function[val] = name
3732
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003733del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003734
Thomas Wouters89f507f2006-12-13 04:49:30 +00003735class _ContextManager(object):
3736 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003737
Thomas Wouters89f507f2006-12-13 04:49:30 +00003738 Sets a copy of the supplied context in __enter__() and restores
3739 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003740 """
3741 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003742 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003743 def __enter__(self):
3744 self.saved_context = getcontext()
3745 setcontext(self.new_context)
3746 return self.new_context
3747 def __exit__(self, t, v, tb):
3748 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003749
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003750class Context(object):
3751 """Contains the context for a Decimal instance.
3752
3753 Contains:
3754 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003755 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003756 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003757 raised when it is caused. Otherwise, a value is
3758 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003759 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003760 (Whether or not the trap_enabler is set)
3761 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003762 Emin - Minimum exponent
3763 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003764 capitals - If 1, 1*10^1 is printed as 1E+1.
3765 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003766 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003767 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003768
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003769 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003770 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003771 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003772 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003773 _ignored_flags=None):
3774 if flags is None:
3775 flags = []
3776 if _ignored_flags is None:
3777 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003778 if not isinstance(flags, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003779 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003780 if traps is not None and not isinstance(traps, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003781 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003782 for name, val in locals().items():
3783 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003784 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003785 else:
3786 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003787 del self.self
3788
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003789 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003790 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003791 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003792 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3793 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3794 % vars(self))
3795 names = [f.__name__ for f, v in self.flags.items() if v]
3796 s.append('flags=[' + ', '.join(names) + ']')
3797 names = [t.__name__ for t, v in self.traps.items() if v]
3798 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003799 return ', '.join(s) + ')'
3800
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003801 def clear_flags(self):
3802 """Reset all flags to zero"""
3803 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003804 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003805
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003806 def _shallow_copy(self):
3807 """Returns a shallow copy from self."""
Christian Heimes2c181612007-12-17 20:04:13 +00003808 nc = Context(self.prec, self.rounding, self.traps,
3809 self.flags, self.Emin, self.Emax,
3810 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003811 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003812
3813 def copy(self):
3814 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003815 nc = Context(self.prec, self.rounding, self.traps.copy(),
Christian Heimes2c181612007-12-17 20:04:13 +00003816 self.flags.copy(), self.Emin, self.Emax,
3817 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003818 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003819 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003820
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003821 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003822 """Handles an error
3823
3824 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003825 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003826 trap_enabler is set, it reaises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00003827 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003828 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003829 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003830 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003831 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003832 return error().handle(self, *args)
3833
Raymond Hettinger86173da2008-02-01 20:38:12 +00003834 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003835 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003836 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003837 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003838
3839 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003840 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003841 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003842
3843 def _ignore_all_flags(self):
3844 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003845 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003846
3847 def _ignore_flags(self, *flags):
3848 """Ignore the flags, if they are raised"""
3849 # Do not mutate-- This way, copies of a context leave the original
3850 # alone.
3851 self._ignored_flags = (self._ignored_flags + list(flags))
3852 return list(flags)
3853
3854 def _regard_flags(self, *flags):
3855 """Stop ignoring the flags, if they are raised"""
3856 if flags and isinstance(flags[0], (tuple,list)):
3857 flags = flags[0]
3858 for flag in flags:
3859 self._ignored_flags.remove(flag)
3860
Nick Coghland1abd252008-07-15 15:46:38 +00003861 # We inherit object.__hash__, so we must deny this explicitly
3862 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003863
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003864 def Etiny(self):
3865 """Returns Etiny (= Emin - prec + 1)"""
3866 return int(self.Emin - self.prec + 1)
3867
3868 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003869 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003870 return int(self.Emax - self.prec + 1)
3871
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003872 def _set_rounding(self, type):
3873 """Sets the rounding type.
3874
3875 Sets the rounding type, and returns the current (previous)
3876 rounding type. Often used like:
3877
3878 context = context.copy()
3879 # so you don't change the calling context
3880 # if an error occurs in the middle.
3881 rounding = context._set_rounding(ROUND_UP)
3882 val = self.__sub__(other, context=context)
3883 context._set_rounding(rounding)
3884
3885 This will make it round up for that operation.
3886 """
3887 rounding = self.rounding
3888 self.rounding= type
3889 return rounding
3890
Raymond Hettingerfed52962004-07-14 15:41:57 +00003891 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00003892 """Creates a new Decimal instance but using self as context.
3893
3894 This method implements the to-number operation of the
3895 IBM Decimal specification."""
3896
3897 if isinstance(num, str) and num != num.strip():
3898 return self._raise_error(ConversionSyntax,
3899 "no trailing or leading whitespace is "
3900 "permitted.")
3901
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003902 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003903 if d._isnan() and len(d._int) > self.prec - self._clamp:
3904 return self._raise_error(ConversionSyntax,
3905 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003906 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003907
Raymond Hettinger771ed762009-01-03 19:20:32 +00003908 def create_decimal_from_float(self, f):
3909 """Creates a new Decimal instance from a float but rounding using self
3910 as the context.
3911
3912 >>> context = Context(prec=5, rounding=ROUND_DOWN)
3913 >>> context.create_decimal_from_float(3.1415926535897932)
3914 Decimal('3.1415')
3915 >>> context = Context(prec=5, traps=[Inexact])
3916 >>> context.create_decimal_from_float(3.1415926535897932)
3917 Traceback (most recent call last):
3918 ...
3919 decimal.Inexact: None
3920
3921 """
3922 d = Decimal.from_float(f) # An exact conversion
3923 return d._fix(self) # Apply the context rounding
3924
Guido van Rossumd8faa362007-04-27 19:54:29 +00003925 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003926 def abs(self, a):
3927 """Returns the absolute value of the operand.
3928
3929 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003930 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003931 the plus operation on the operand.
3932
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003933 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003934 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003935 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003936 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003937 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003938 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003939 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003940 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00003941 >>> ExtendedContext.abs(-1)
3942 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003943 """
Mark Dickinson84230a12010-02-18 14:49:50 +00003944 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003945 return a.__abs__(context=self)
3946
3947 def add(self, a, b):
3948 """Return the sum of the two operands.
3949
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003950 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003951 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003952 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003953 Decimal('1.02E+4')
Mark Dickinson84230a12010-02-18 14:49:50 +00003954 >>> ExtendedContext.add(1, Decimal(2))
3955 Decimal('3')
3956 >>> ExtendedContext.add(Decimal(8), 5)
3957 Decimal('13')
3958 >>> ExtendedContext.add(5, 5)
3959 Decimal('10')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003960 """
Mark Dickinson84230a12010-02-18 14:49:50 +00003961 a = _convert_other(a, raiseit=True)
3962 r = a.__add__(b, context=self)
3963 if r is NotImplemented:
3964 raise TypeError("Unable to convert %s to Decimal" % b)
3965 else:
3966 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003967
3968 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003969 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003970
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003971 def canonical(self, a):
3972 """Returns the same Decimal object.
3973
3974 As we do not have different encodings for the same number, the
3975 received object already is in its canonical form.
3976
3977 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003978 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003979 """
3980 return a.canonical(context=self)
3981
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003982 def compare(self, a, b):
3983 """Compares values numerically.
3984
3985 If the signs of the operands differ, a value representing each operand
3986 ('-1' if the operand is less than zero, '0' if the operand is zero or
3987 negative zero, or '1' if the operand is greater than zero) is used in
3988 place of that operand for the comparison instead of the actual
3989 operand.
3990
3991 The comparison is then effected by subtracting the second operand from
3992 the first and then returning a value according to the result of the
3993 subtraction: '-1' if the result is less than zero, '0' if the result is
3994 zero or negative zero, or '1' if the result is greater than zero.
3995
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003996 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003997 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003998 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003999 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004000 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004001 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004002 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004003 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004004 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004005 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004006 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004007 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004008 >>> ExtendedContext.compare(1, 2)
4009 Decimal('-1')
4010 >>> ExtendedContext.compare(Decimal(1), 2)
4011 Decimal('-1')
4012 >>> ExtendedContext.compare(1, Decimal(2))
4013 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004014 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004015 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004016 return a.compare(b, context=self)
4017
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004018 def compare_signal(self, a, b):
4019 """Compares the values of the two operands numerically.
4020
4021 It's pretty much like compare(), but all NaNs signal, with signaling
4022 NaNs taking precedence over quiet NaNs.
4023
4024 >>> c = ExtendedContext
4025 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004026 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004027 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004028 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004029 >>> c.flags[InvalidOperation] = 0
4030 >>> print(c.flags[InvalidOperation])
4031 0
4032 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004033 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004034 >>> print(c.flags[InvalidOperation])
4035 1
4036 >>> c.flags[InvalidOperation] = 0
4037 >>> print(c.flags[InvalidOperation])
4038 0
4039 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004040 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004041 >>> print(c.flags[InvalidOperation])
4042 1
Mark Dickinson84230a12010-02-18 14:49:50 +00004043 >>> c.compare_signal(-1, 2)
4044 Decimal('-1')
4045 >>> c.compare_signal(Decimal(-1), 2)
4046 Decimal('-1')
4047 >>> c.compare_signal(-1, Decimal(2))
4048 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004049 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004050 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004051 return a.compare_signal(b, context=self)
4052
4053 def compare_total(self, a, b):
4054 """Compares two operands using their abstract representation.
4055
4056 This is not like the standard compare, which use their numerical
4057 value. Note that a total ordering is defined for all possible abstract
4058 representations.
4059
4060 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004061 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004062 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004063 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004064 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004065 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004066 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004067 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004068 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004069 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004070 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004071 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004072 >>> ExtendedContext.compare_total(1, 2)
4073 Decimal('-1')
4074 >>> ExtendedContext.compare_total(Decimal(1), 2)
4075 Decimal('-1')
4076 >>> ExtendedContext.compare_total(1, Decimal(2))
4077 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004078 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004079 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004080 return a.compare_total(b)
4081
4082 def compare_total_mag(self, a, b):
4083 """Compares two operands using their abstract representation ignoring sign.
4084
4085 Like compare_total, but with operand's sign ignored and assumed to be 0.
4086 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004087 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004088 return a.compare_total_mag(b)
4089
4090 def copy_abs(self, a):
4091 """Returns a copy of the operand with the sign set to 0.
4092
4093 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004094 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004095 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004096 Decimal('100')
Mark Dickinson84230a12010-02-18 14:49:50 +00004097 >>> ExtendedContext.copy_abs(-1)
4098 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004099 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004100 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004101 return a.copy_abs()
4102
4103 def copy_decimal(self, a):
Mark Dickinson84230a12010-02-18 14:49:50 +00004104 """Returns a copy of the decimal object.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004105
4106 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004107 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004108 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004109 Decimal('-1.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00004110 >>> ExtendedContext.copy_decimal(1)
4111 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004112 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004113 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004114 return Decimal(a)
4115
4116 def copy_negate(self, a):
4117 """Returns a copy of the operand with the sign inverted.
4118
4119 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004120 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004121 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004122 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00004123 >>> ExtendedContext.copy_negate(1)
4124 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004125 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004126 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004127 return a.copy_negate()
4128
4129 def copy_sign(self, a, b):
4130 """Copies the second operand's sign to the first one.
4131
4132 In detail, it returns a copy of the first operand with the sign
4133 equal to the sign of the second operand.
4134
4135 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004136 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004137 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004138 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004139 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004140 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004141 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004142 Decimal('-1.50')
Mark Dickinson84230a12010-02-18 14:49:50 +00004143 >>> ExtendedContext.copy_sign(1, -2)
4144 Decimal('-1')
4145 >>> ExtendedContext.copy_sign(Decimal(1), -2)
4146 Decimal('-1')
4147 >>> ExtendedContext.copy_sign(1, Decimal(-2))
4148 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004149 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004150 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004151 return a.copy_sign(b)
4152
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004153 def divide(self, a, b):
4154 """Decimal division in a specified context.
4155
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004156 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004157 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004158 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004159 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004160 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004161 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004162 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004163 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004164 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004165 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004166 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004167 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004168 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004169 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004170 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004171 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004172 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004173 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004174 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004175 Decimal('1.20E+6')
Mark Dickinson84230a12010-02-18 14:49:50 +00004176 >>> ExtendedContext.divide(5, 5)
4177 Decimal('1')
4178 >>> ExtendedContext.divide(Decimal(5), 5)
4179 Decimal('1')
4180 >>> ExtendedContext.divide(5, Decimal(5))
4181 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004182 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004183 a = _convert_other(a, raiseit=True)
4184 r = a.__truediv__(b, context=self)
4185 if r is NotImplemented:
4186 raise TypeError("Unable to convert %s to Decimal" % b)
4187 else:
4188 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004189
4190 def divide_int(self, a, b):
4191 """Divides two numbers and returns the integer part of the result.
4192
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004193 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004194 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004195 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004196 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004197 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004198 Decimal('3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004199 >>> ExtendedContext.divide_int(10, 3)
4200 Decimal('3')
4201 >>> ExtendedContext.divide_int(Decimal(10), 3)
4202 Decimal('3')
4203 >>> ExtendedContext.divide_int(10, Decimal(3))
4204 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004205 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004206 a = _convert_other(a, raiseit=True)
4207 r = a.__floordiv__(b, context=self)
4208 if r is NotImplemented:
4209 raise TypeError("Unable to convert %s to Decimal" % b)
4210 else:
4211 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004212
4213 def divmod(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004214 """Return (a // b, a % b).
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004215
4216 >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
4217 (Decimal('2'), Decimal('2'))
4218 >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
4219 (Decimal('2'), Decimal('0'))
Mark Dickinson84230a12010-02-18 14:49:50 +00004220 >>> ExtendedContext.divmod(8, 4)
4221 (Decimal('2'), Decimal('0'))
4222 >>> ExtendedContext.divmod(Decimal(8), 4)
4223 (Decimal('2'), Decimal('0'))
4224 >>> ExtendedContext.divmod(8, Decimal(4))
4225 (Decimal('2'), Decimal('0'))
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004226 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004227 a = _convert_other(a, raiseit=True)
4228 r = a.__divmod__(b, context=self)
4229 if r is NotImplemented:
4230 raise TypeError("Unable to convert %s to Decimal" % b)
4231 else:
4232 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004233
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004234 def exp(self, a):
4235 """Returns e ** a.
4236
4237 >>> c = ExtendedContext.copy()
4238 >>> c.Emin = -999
4239 >>> c.Emax = 999
4240 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004241 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004242 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004243 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004244 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004245 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004246 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004247 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004248 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004249 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004250 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004251 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004252 >>> c.exp(10)
4253 Decimal('22026.4658')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004254 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004255 a =_convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004256 return a.exp(context=self)
4257
4258 def fma(self, a, b, c):
4259 """Returns a multiplied by b, plus c.
4260
4261 The first two operands are multiplied together, using multiply,
4262 the third operand is then added to the result of that
4263 multiplication, using add, all with only one final rounding.
4264
4265 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004266 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004267 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004268 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004269 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004270 Decimal('1.38435736E+12')
Mark Dickinson84230a12010-02-18 14:49:50 +00004271 >>> ExtendedContext.fma(1, 3, 4)
4272 Decimal('7')
4273 >>> ExtendedContext.fma(1, Decimal(3), 4)
4274 Decimal('7')
4275 >>> ExtendedContext.fma(1, 3, Decimal(4))
4276 Decimal('7')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004277 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004278 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004279 return a.fma(b, c, context=self)
4280
4281 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004282 """Return True if the operand is canonical; otherwise return False.
4283
4284 Currently, the encoding of a Decimal instance is always
4285 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004286
4287 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004288 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004289 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004290 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004291
4292 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004293 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004294
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004295 A Decimal instance is considered finite if it is neither
4296 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004297
4298 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004299 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004300 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004301 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004302 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004303 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004304 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004305 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004306 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004307 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004308 >>> ExtendedContext.is_finite(1)
4309 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004310 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004311 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004312 return a.is_finite()
4313
4314 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004315 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004316
4317 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004318 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004319 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004320 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004321 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004322 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004323 >>> ExtendedContext.is_infinite(1)
4324 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004325 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004326 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004327 return a.is_infinite()
4328
4329 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004330 """Return True if the operand is a qNaN or sNaN;
4331 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004332
4333 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004334 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004335 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004336 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004337 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004338 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004339 >>> ExtendedContext.is_nan(1)
4340 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004341 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004342 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004343 return a.is_nan()
4344
4345 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004346 """Return True if the operand is a normal number;
4347 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004348
4349 >>> c = ExtendedContext.copy()
4350 >>> c.Emin = -999
4351 >>> c.Emax = 999
4352 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004353 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004354 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004355 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004356 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004357 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004358 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004359 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004360 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004361 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004362 >>> c.is_normal(1)
4363 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004364 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004365 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004366 return a.is_normal(context=self)
4367
4368 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004369 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004370
4371 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004372 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004373 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004374 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004375 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004376 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004377 >>> ExtendedContext.is_qnan(1)
4378 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004379 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004380 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004381 return a.is_qnan()
4382
4383 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004384 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004385
4386 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004387 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004388 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004389 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004390 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004391 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004392 >>> ExtendedContext.is_signed(8)
4393 False
4394 >>> ExtendedContext.is_signed(-8)
4395 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004396 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004397 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004398 return a.is_signed()
4399
4400 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004401 """Return True if the operand is a signaling NaN;
4402 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004403
4404 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004405 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004406 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004407 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004408 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004409 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004410 >>> ExtendedContext.is_snan(1)
4411 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004412 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004413 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004414 return a.is_snan()
4415
4416 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004417 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004418
4419 >>> c = ExtendedContext.copy()
4420 >>> c.Emin = -999
4421 >>> c.Emax = 999
4422 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004423 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004424 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004425 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004426 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004427 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004428 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004429 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004430 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004431 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004432 >>> c.is_subnormal(1)
4433 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004434 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004435 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004436 return a.is_subnormal(context=self)
4437
4438 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004439 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004440
4441 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004442 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004443 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004444 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004445 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004446 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004447 >>> ExtendedContext.is_zero(1)
4448 False
4449 >>> ExtendedContext.is_zero(0)
4450 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004451 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004452 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004453 return a.is_zero()
4454
4455 def ln(self, a):
4456 """Returns the natural (base e) logarithm of the operand.
4457
4458 >>> c = ExtendedContext.copy()
4459 >>> c.Emin = -999
4460 >>> c.Emax = 999
4461 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004462 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004463 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004464 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004465 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004466 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004467 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004468 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004469 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004470 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004471 >>> c.ln(1)
4472 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004473 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004474 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004475 return a.ln(context=self)
4476
4477 def log10(self, a):
4478 """Returns the base 10 logarithm of the operand.
4479
4480 >>> c = ExtendedContext.copy()
4481 >>> c.Emin = -999
4482 >>> c.Emax = 999
4483 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004484 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004485 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004486 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004487 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004488 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004489 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004490 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004491 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004492 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004493 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004494 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004495 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004496 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004497 >>> c.log10(0)
4498 Decimal('-Infinity')
4499 >>> c.log10(1)
4500 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004501 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004502 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004503 return a.log10(context=self)
4504
4505 def logb(self, a):
4506 """ Returns the exponent of the magnitude of the operand's MSD.
4507
4508 The result is the integer which is the exponent of the magnitude
4509 of the most significant digit of the operand (as though the
4510 operand were truncated to a single digit while maintaining the
4511 value of that digit and without limiting the resulting exponent).
4512
4513 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004514 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004515 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004516 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004517 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004518 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004519 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004520 Decimal('-Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004521 >>> ExtendedContext.logb(1)
4522 Decimal('0')
4523 >>> ExtendedContext.logb(10)
4524 Decimal('1')
4525 >>> ExtendedContext.logb(100)
4526 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004527 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004528 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004529 return a.logb(context=self)
4530
4531 def logical_and(self, a, b):
4532 """Applies the logical operation 'and' between each operand's digits.
4533
4534 The operands must be both logical numbers.
4535
4536 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004537 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004538 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004539 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004540 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004541 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004542 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004543 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004544 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004545 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004546 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004547 Decimal('10')
Mark Dickinson84230a12010-02-18 14:49:50 +00004548 >>> ExtendedContext.logical_and(110, 1101)
4549 Decimal('100')
4550 >>> ExtendedContext.logical_and(Decimal(110), 1101)
4551 Decimal('100')
4552 >>> ExtendedContext.logical_and(110, Decimal(1101))
4553 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004554 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004555 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004556 return a.logical_and(b, context=self)
4557
4558 def logical_invert(self, a):
4559 """Invert all the digits in the operand.
4560
4561 The operand must be a logical number.
4562
4563 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004564 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004565 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004566 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004567 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004568 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004569 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004570 Decimal('10101010')
Mark Dickinson84230a12010-02-18 14:49:50 +00004571 >>> ExtendedContext.logical_invert(1101)
4572 Decimal('111110010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004573 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004574 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004575 return a.logical_invert(context=self)
4576
4577 def logical_or(self, a, b):
4578 """Applies the logical operation 'or' between each operand's digits.
4579
4580 The operands must be both logical numbers.
4581
4582 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004583 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004584 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004585 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004586 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004587 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004588 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004589 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004590 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004591 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004592 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004593 Decimal('1110')
Mark Dickinson84230a12010-02-18 14:49:50 +00004594 >>> ExtendedContext.logical_or(110, 1101)
4595 Decimal('1111')
4596 >>> ExtendedContext.logical_or(Decimal(110), 1101)
4597 Decimal('1111')
4598 >>> ExtendedContext.logical_or(110, Decimal(1101))
4599 Decimal('1111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004600 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004601 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004602 return a.logical_or(b, context=self)
4603
4604 def logical_xor(self, a, b):
4605 """Applies the logical operation 'xor' between each operand's digits.
4606
4607 The operands must be both logical numbers.
4608
4609 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004610 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004611 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004612 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004613 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004614 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004615 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004616 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004617 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004618 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004619 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004620 Decimal('1101')
Mark Dickinson84230a12010-02-18 14:49:50 +00004621 >>> ExtendedContext.logical_xor(110, 1101)
4622 Decimal('1011')
4623 >>> ExtendedContext.logical_xor(Decimal(110), 1101)
4624 Decimal('1011')
4625 >>> ExtendedContext.logical_xor(110, Decimal(1101))
4626 Decimal('1011')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004627 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004628 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004629 return a.logical_xor(b, context=self)
4630
Mark Dickinson84230a12010-02-18 14:49:50 +00004631 def max(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004632 """max compares two values numerically and returns the maximum.
4633
4634 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004635 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004636 operation. If they are numerically equal then the left-hand operand
4637 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004638 infinity) of the two operands is chosen as the result.
4639
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004640 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004641 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004642 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004643 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004644 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004645 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004646 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004647 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004648 >>> ExtendedContext.max(1, 2)
4649 Decimal('2')
4650 >>> ExtendedContext.max(Decimal(1), 2)
4651 Decimal('2')
4652 >>> ExtendedContext.max(1, Decimal(2))
4653 Decimal('2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004654 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004655 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004656 return a.max(b, context=self)
4657
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004658 def max_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004659 """Compares the values numerically with their sign ignored.
4660
4661 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
4662 Decimal('7')
4663 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
4664 Decimal('-10')
4665 >>> ExtendedContext.max_mag(1, -2)
4666 Decimal('-2')
4667 >>> ExtendedContext.max_mag(Decimal(1), -2)
4668 Decimal('-2')
4669 >>> ExtendedContext.max_mag(1, Decimal(-2))
4670 Decimal('-2')
4671 """
4672 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004673 return a.max_mag(b, context=self)
4674
Mark Dickinson84230a12010-02-18 14:49:50 +00004675 def min(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004676 """min compares two values numerically and returns the minimum.
4677
4678 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004679 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004680 operation. If they are numerically equal then the left-hand operand
4681 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004682 infinity) of the two operands is chosen as the result.
4683
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004684 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004685 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004686 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004687 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004688 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004689 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004690 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004691 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004692 >>> ExtendedContext.min(1, 2)
4693 Decimal('1')
4694 >>> ExtendedContext.min(Decimal(1), 2)
4695 Decimal('1')
4696 >>> ExtendedContext.min(1, Decimal(29))
4697 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004698 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004699 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004700 return a.min(b, context=self)
4701
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004702 def min_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004703 """Compares the values numerically with their sign ignored.
4704
4705 >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
4706 Decimal('-2')
4707 >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
4708 Decimal('-3')
4709 >>> ExtendedContext.min_mag(1, -2)
4710 Decimal('1')
4711 >>> ExtendedContext.min_mag(Decimal(1), -2)
4712 Decimal('1')
4713 >>> ExtendedContext.min_mag(1, Decimal(-2))
4714 Decimal('1')
4715 """
4716 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004717 return a.min_mag(b, context=self)
4718
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004719 def minus(self, a):
4720 """Minus corresponds to unary prefix minus in Python.
4721
4722 The operation is evaluated using the same rules as subtract; the
4723 operation minus(a) is calculated as subtract('0', a) where the '0'
4724 has the same exponent as the operand.
4725
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004726 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004727 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004728 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004729 Decimal('1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004730 >>> ExtendedContext.minus(1)
4731 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004732 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004733 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004734 return a.__neg__(context=self)
4735
4736 def multiply(self, a, b):
4737 """multiply multiplies two operands.
4738
4739 If either operand is a special value then the general rules apply.
Mark Dickinson84230a12010-02-18 14:49:50 +00004740 Otherwise, the operands are multiplied together
4741 ('long multiplication'), resulting in a number which may be as long as
4742 the sum of the lengths of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004743
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004744 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004745 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004746 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004747 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004748 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004749 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004750 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004751 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004752 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004753 Decimal('4.28135971E+11')
Mark Dickinson84230a12010-02-18 14:49:50 +00004754 >>> ExtendedContext.multiply(7, 7)
4755 Decimal('49')
4756 >>> ExtendedContext.multiply(Decimal(7), 7)
4757 Decimal('49')
4758 >>> ExtendedContext.multiply(7, Decimal(7))
4759 Decimal('49')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004760 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004761 a = _convert_other(a, raiseit=True)
4762 r = a.__mul__(b, context=self)
4763 if r is NotImplemented:
4764 raise TypeError("Unable to convert %s to Decimal" % b)
4765 else:
4766 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004767
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004768 def next_minus(self, a):
4769 """Returns the largest representable number smaller than a.
4770
4771 >>> c = ExtendedContext.copy()
4772 >>> c.Emin = -999
4773 >>> c.Emax = 999
4774 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004775 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004776 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004777 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004778 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004779 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004780 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004781 Decimal('9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00004782 >>> c.next_minus(1)
4783 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004784 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004785 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004786 return a.next_minus(context=self)
4787
4788 def next_plus(self, a):
4789 """Returns the smallest representable number larger than a.
4790
4791 >>> c = ExtendedContext.copy()
4792 >>> c.Emin = -999
4793 >>> c.Emax = 999
4794 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004795 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004796 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004797 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004798 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004799 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004800 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004801 Decimal('-9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00004802 >>> c.next_plus(1)
4803 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004804 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004805 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004806 return a.next_plus(context=self)
4807
4808 def next_toward(self, a, b):
4809 """Returns the number closest to a, in direction towards b.
4810
4811 The result is the closest representable number from the first
4812 operand (but not the first operand) that is in the direction
4813 towards the second operand, unless the operands have the same
4814 value.
4815
4816 >>> c = ExtendedContext.copy()
4817 >>> c.Emin = -999
4818 >>> c.Emax = 999
4819 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004820 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004821 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004822 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004823 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004824 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004825 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004826 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004827 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004828 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004829 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004830 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004831 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004832 Decimal('-0.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00004833 >>> c.next_toward(0, 1)
4834 Decimal('1E-1007')
4835 >>> c.next_toward(Decimal(0), 1)
4836 Decimal('1E-1007')
4837 >>> c.next_toward(0, Decimal(1))
4838 Decimal('1E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004839 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004840 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004841 return a.next_toward(b, context=self)
4842
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004843 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004844 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004845
4846 Essentially a plus operation with all trailing zeros removed from the
4847 result.
4848
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004849 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004850 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004851 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004852 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004853 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004854 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004855 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004856 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004857 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004858 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004859 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004860 Decimal('0')
Mark Dickinson84230a12010-02-18 14:49:50 +00004861 >>> ExtendedContext.normalize(6)
4862 Decimal('6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004863 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004864 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004865 return a.normalize(context=self)
4866
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004867 def number_class(self, a):
4868 """Returns an indication of the class of the operand.
4869
4870 The class is one of the following strings:
4871 -sNaN
4872 -NaN
4873 -Infinity
4874 -Normal
4875 -Subnormal
4876 -Zero
4877 +Zero
4878 +Subnormal
4879 +Normal
4880 +Infinity
4881
4882 >>> c = Context(ExtendedContext)
4883 >>> c.Emin = -999
4884 >>> c.Emax = 999
4885 >>> c.number_class(Decimal('Infinity'))
4886 '+Infinity'
4887 >>> c.number_class(Decimal('1E-10'))
4888 '+Normal'
4889 >>> c.number_class(Decimal('2.50'))
4890 '+Normal'
4891 >>> c.number_class(Decimal('0.1E-999'))
4892 '+Subnormal'
4893 >>> c.number_class(Decimal('0'))
4894 '+Zero'
4895 >>> c.number_class(Decimal('-0'))
4896 '-Zero'
4897 >>> c.number_class(Decimal('-0.1E-999'))
4898 '-Subnormal'
4899 >>> c.number_class(Decimal('-1E-10'))
4900 '-Normal'
4901 >>> c.number_class(Decimal('-2.50'))
4902 '-Normal'
4903 >>> c.number_class(Decimal('-Infinity'))
4904 '-Infinity'
4905 >>> c.number_class(Decimal('NaN'))
4906 'NaN'
4907 >>> c.number_class(Decimal('-NaN'))
4908 'NaN'
4909 >>> c.number_class(Decimal('sNaN'))
4910 'sNaN'
Mark Dickinson84230a12010-02-18 14:49:50 +00004911 >>> c.number_class(123)
4912 '+Normal'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004913 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004914 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004915 return a.number_class(context=self)
4916
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004917 def plus(self, a):
4918 """Plus corresponds to unary prefix plus in Python.
4919
4920 The operation is evaluated using the same rules as add; the
4921 operation plus(a) is calculated as add('0', a) where the '0'
4922 has the same exponent as the operand.
4923
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004924 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004925 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004926 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004927 Decimal('-1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004928 >>> ExtendedContext.plus(-1)
4929 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004930 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004931 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004932 return a.__pos__(context=self)
4933
4934 def power(self, a, b, modulo=None):
4935 """Raises a to the power of b, to modulo if given.
4936
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004937 With two arguments, compute a**b. If a is negative then b
4938 must be integral. The result will be inexact unless b is
4939 integral and the result is finite and can be expressed exactly
4940 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004941
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004942 With three arguments, compute (a**b) % modulo. For the
4943 three argument form, the following restrictions on the
4944 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004945
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004946 - all three arguments must be integral
4947 - b must be nonnegative
4948 - at least one of a or b must be nonzero
4949 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004950
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004951 The result of pow(a, b, modulo) is identical to the result
4952 that would be obtained by computing (a**b) % modulo with
4953 unbounded precision, but is computed more efficiently. It is
4954 always exact.
4955
4956 >>> c = ExtendedContext.copy()
4957 >>> c.Emin = -999
4958 >>> c.Emax = 999
4959 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004960 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004961 >>> c.power(Decimal('-2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004962 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004963 >>> c.power(Decimal('2'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004964 Decimal('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004965 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004966 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004967 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004968 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004969 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004970 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004971 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004972 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004973 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004974 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004975 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004976 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004977 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004978 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004979 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004980 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004981 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004982 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004983 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004984 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004985
4986 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004987 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004988 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004989 Decimal('-11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004990 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004991 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004992 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004993 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004994 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004995 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004996 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004997 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004998 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004999 Decimal('1')
Mark Dickinson84230a12010-02-18 14:49:50 +00005000 >>> ExtendedContext.power(7, 7)
5001 Decimal('823543')
5002 >>> ExtendedContext.power(Decimal(7), 7)
5003 Decimal('823543')
5004 >>> ExtendedContext.power(7, Decimal(7), 2)
5005 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005006 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005007 a = _convert_other(a, raiseit=True)
5008 r = a.__pow__(b, modulo, context=self)
5009 if r is NotImplemented:
5010 raise TypeError("Unable to convert %s to Decimal" % b)
5011 else:
5012 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005013
5014 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005015 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005016
5017 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00005018 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005019 exponent is being increased), multiplied by a positive power of ten (if
5020 the exponent is being decreased), or is unchanged (if the exponent is
5021 already equal to that of the right-hand operand).
5022
5023 Unlike other operations, if the length of the coefficient after the
5024 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00005025 operation condition is raised. This guarantees that, unless there is
5026 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005027 equal to that of the right-hand operand.
5028
5029 Also unlike other operations, quantize will never raise Underflow, even
5030 if the result is subnormal and inexact.
5031
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005032 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005033 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005034 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005035 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005036 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005037 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005038 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005039 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005040 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005041 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005042 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005043 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005044 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005045 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005046 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005047 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005048 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005049 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005050 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005051 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005052 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005053 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005054 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005055 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005056 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005057 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005058 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005059 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005060 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005061 Decimal('2E+2')
Mark Dickinson84230a12010-02-18 14:49:50 +00005062 >>> ExtendedContext.quantize(1, 2)
5063 Decimal('1')
5064 >>> ExtendedContext.quantize(Decimal(1), 2)
5065 Decimal('1')
5066 >>> ExtendedContext.quantize(1, Decimal(2))
5067 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005068 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005069 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005070 return a.quantize(b, context=self)
5071
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005072 def radix(self):
5073 """Just returns 10, as this is Decimal, :)
5074
5075 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005076 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005077 """
5078 return Decimal(10)
5079
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005080 def remainder(self, a, b):
5081 """Returns the remainder from integer division.
5082
5083 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00005084 calculating integer division as described for divide-integer, rounded
5085 to precision digits if necessary. The sign of the result, if
5086 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005087
5088 This operation will fail under the same conditions as integer division
5089 (that is, if integer division on the same two operands would fail, the
5090 remainder cannot be calculated).
5091
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005092 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005093 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005094 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005095 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005096 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005097 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005098 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005099 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005100 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005101 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005102 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005103 Decimal('1.0')
Mark Dickinson84230a12010-02-18 14:49:50 +00005104 >>> ExtendedContext.remainder(22, 6)
5105 Decimal('4')
5106 >>> ExtendedContext.remainder(Decimal(22), 6)
5107 Decimal('4')
5108 >>> ExtendedContext.remainder(22, Decimal(6))
5109 Decimal('4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005110 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005111 a = _convert_other(a, raiseit=True)
5112 r = a.__mod__(b, context=self)
5113 if r is NotImplemented:
5114 raise TypeError("Unable to convert %s to Decimal" % b)
5115 else:
5116 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005117
5118 def remainder_near(self, a, b):
5119 """Returns to be "a - b * n", where n is the integer nearest the exact
5120 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00005121 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005122 sign of a.
5123
5124 This operation will fail under the same conditions as integer division
5125 (that is, if integer division on the same two operands would fail, the
5126 remainder cannot be calculated).
5127
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005128 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005129 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005130 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005131 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005132 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005133 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005134 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005135 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005136 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005137 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005138 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005139 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005140 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005141 Decimal('-0.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005142 >>> ExtendedContext.remainder_near(3, 11)
5143 Decimal('3')
5144 >>> ExtendedContext.remainder_near(Decimal(3), 11)
5145 Decimal('3')
5146 >>> ExtendedContext.remainder_near(3, Decimal(11))
5147 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005148 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005149 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005150 return a.remainder_near(b, context=self)
5151
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005152 def rotate(self, a, b):
5153 """Returns a rotated copy of a, b times.
5154
5155 The coefficient of the result is a rotated copy of the digits in
5156 the coefficient of the first operand. The number of places of
5157 rotation is taken from the absolute value of the second operand,
5158 with the rotation being to the left if the second operand is
5159 positive or to the right otherwise.
5160
5161 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005162 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005163 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005164 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005165 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005166 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005167 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005168 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005169 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005170 Decimal('345678912')
Mark Dickinson84230a12010-02-18 14:49:50 +00005171 >>> ExtendedContext.rotate(1333333, 1)
5172 Decimal('13333330')
5173 >>> ExtendedContext.rotate(Decimal(1333333), 1)
5174 Decimal('13333330')
5175 >>> ExtendedContext.rotate(1333333, Decimal(1))
5176 Decimal('13333330')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005177 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005178 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005179 return a.rotate(b, context=self)
5180
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005181 def same_quantum(self, a, b):
5182 """Returns True if the two operands have the same exponent.
5183
5184 The result is never affected by either the sign or the coefficient of
5185 either operand.
5186
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005187 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005188 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005189 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005190 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005191 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005192 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005193 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005194 True
Mark Dickinson84230a12010-02-18 14:49:50 +00005195 >>> ExtendedContext.same_quantum(10000, -1)
5196 True
5197 >>> ExtendedContext.same_quantum(Decimal(10000), -1)
5198 True
5199 >>> ExtendedContext.same_quantum(10000, Decimal(-1))
5200 True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005201 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005202 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005203 return a.same_quantum(b)
5204
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005205 def scaleb (self, a, b):
5206 """Returns the first operand after adding the second value its exp.
5207
5208 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005209 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005210 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005211 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005212 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005213 Decimal('7.50E+3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005214 >>> ExtendedContext.scaleb(1, 4)
5215 Decimal('1E+4')
5216 >>> ExtendedContext.scaleb(Decimal(1), 4)
5217 Decimal('1E+4')
5218 >>> ExtendedContext.scaleb(1, Decimal(4))
5219 Decimal('1E+4')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005220 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005221 a = _convert_other(a, raiseit=True)
5222 return a.scaleb(b, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005223
5224 def shift(self, a, b):
5225 """Returns a shifted copy of a, b times.
5226
5227 The coefficient of the result is a shifted copy of the digits
5228 in the coefficient of the first operand. The number of places
5229 to shift is taken from the absolute value of the second operand,
5230 with the shift being to the left if the second operand is
5231 positive or to the right otherwise. Digits shifted into the
5232 coefficient are zeros.
5233
5234 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005235 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005236 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005237 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005238 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005239 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005240 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005241 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005242 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005243 Decimal('345678900')
Mark Dickinson84230a12010-02-18 14:49:50 +00005244 >>> ExtendedContext.shift(88888888, 2)
5245 Decimal('888888800')
5246 >>> ExtendedContext.shift(Decimal(88888888), 2)
5247 Decimal('888888800')
5248 >>> ExtendedContext.shift(88888888, Decimal(2))
5249 Decimal('888888800')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005250 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005251 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005252 return a.shift(b, context=self)
5253
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005254 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005255 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005256
5257 If the result must be inexact, it is rounded using the round-half-even
5258 algorithm.
5259
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005260 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005261 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005262 >>> ExtendedContext.sqrt(Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005263 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005264 >>> ExtendedContext.sqrt(Decimal('0.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005265 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005266 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005267 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005268 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005269 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005270 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005271 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005272 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005273 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005274 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005275 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005276 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005277 Decimal('3.16227766')
Mark Dickinson84230a12010-02-18 14:49:50 +00005278 >>> ExtendedContext.sqrt(2)
5279 Decimal('1.41421356')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005280 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005281 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005282 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005283 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005284 return a.sqrt(context=self)
5285
5286 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00005287 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005288
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005289 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005290 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005291 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005292 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005293 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005294 Decimal('-0.77')
Mark Dickinson84230a12010-02-18 14:49:50 +00005295 >>> ExtendedContext.subtract(8, 5)
5296 Decimal('3')
5297 >>> ExtendedContext.subtract(Decimal(8), 5)
5298 Decimal('3')
5299 >>> ExtendedContext.subtract(8, Decimal(5))
5300 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005301 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005302 a = _convert_other(a, raiseit=True)
5303 r = a.__sub__(b, context=self)
5304 if r is NotImplemented:
5305 raise TypeError("Unable to convert %s to Decimal" % b)
5306 else:
5307 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005308
5309 def to_eng_string(self, a):
5310 """Converts a number to a string, using scientific notation.
5311
5312 The operation is not affected by the context.
5313 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005314 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005315 return a.to_eng_string(context=self)
5316
5317 def to_sci_string(self, a):
5318 """Converts a number to a string, using scientific notation.
5319
5320 The operation is not affected by the context.
5321 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005322 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005323 return a.__str__(context=self)
5324
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005325 def to_integral_exact(self, a):
5326 """Rounds to an integer.
5327
5328 When the operand has a negative exponent, the result is the same
5329 as using the quantize() operation using the given operand as the
5330 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5331 of the operand as the precision setting; Inexact and Rounded flags
5332 are allowed in this operation. The rounding mode is taken from the
5333 context.
5334
5335 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005336 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005337 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005338 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005339 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005340 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005341 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005342 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005343 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005344 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005345 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005346 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005347 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005348 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005349 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005350 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005351 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005352 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005353 return a.to_integral_exact(context=self)
5354
5355 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005356 """Rounds to an integer.
5357
5358 When the operand has a negative exponent, the result is the same
5359 as using the quantize() operation using the given operand as the
5360 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5361 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00005362 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005363
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005364 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005365 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005366 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005367 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005368 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005369 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005370 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005371 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005372 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005373 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005374 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005375 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005376 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005377 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005378 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005379 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005380 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005381 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005382 return a.to_integral_value(context=self)
5383
5384 # the method name changed, but we provide also the old one, for compatibility
5385 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005386
5387class _WorkRep(object):
5388 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005389 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005390 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005391 # exp: None, int, or string
5392
5393 def __init__(self, value=None):
5394 if value is None:
5395 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005396 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005397 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005398 elif isinstance(value, Decimal):
5399 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005400 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005401 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005402 else:
5403 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005404 self.sign = value[0]
5405 self.int = value[1]
5406 self.exp = value[2]
5407
5408 def __repr__(self):
5409 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5410
5411 __str__ = __repr__
5412
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005413
5414
Christian Heimes2c181612007-12-17 20:04:13 +00005415def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005416 """Normalizes op1, op2 to have the same exp and length of coefficient.
5417
5418 Done during addition.
5419 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005420 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005421 tmp = op2
5422 other = op1
5423 else:
5424 tmp = op1
5425 other = op2
5426
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005427 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5428 # Then adding 10**exp to tmp has the same effect (after rounding)
5429 # as adding any positive quantity smaller than 10**exp; similarly
5430 # for subtraction. So if other is smaller than 10**exp we replace
5431 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00005432 tmp_len = len(str(tmp.int))
5433 other_len = len(str(other.int))
5434 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5435 if other_len + other.exp - 1 < exp:
5436 other.int = 1
5437 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005438
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005439 tmp.int *= 10 ** (tmp.exp - other.exp)
5440 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005441 return op1, op2
5442
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005443##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005444
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005445# This function from Tim Peters was taken from here:
5446# http://mail.python.org/pipermail/python-list/1999-July/007758.html
5447# The correction being in the function definition is for speed, and
5448# the whole function is not resolved with math.log because of avoiding
5449# the use of floats.
5450def _nbits(n, correction = {
5451 '0': 4, '1': 3, '2': 2, '3': 2,
5452 '4': 1, '5': 1, '6': 1, '7': 1,
5453 '8': 0, '9': 0, 'a': 0, 'b': 0,
5454 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
5455 """Number of bits in binary representation of the positive integer n,
5456 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005457 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005458 if n < 0:
5459 raise ValueError("The argument to _nbits should be nonnegative.")
5460 hex_n = "%x" % n
5461 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005462
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005463def _sqrt_nearest(n, a):
5464 """Closest integer to the square root of the positive integer n. a is
5465 an initial approximation to the square root. Any positive integer
5466 will do for a, but the closer a is to the square root of n the
5467 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005468
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005469 """
5470 if n <= 0 or a <= 0:
5471 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5472
5473 b=0
5474 while a != b:
5475 b, a = a, a--n//a>>1
5476 return a
5477
5478def _rshift_nearest(x, shift):
5479 """Given an integer x and a nonnegative integer shift, return closest
5480 integer to x / 2**shift; use round-to-even in case of a tie.
5481
5482 """
5483 b, q = 1 << shift, x >> shift
5484 return q + (2*(x & (b-1)) + (q&1) > b)
5485
5486def _div_nearest(a, b):
5487 """Closest integer to a/b, a and b positive integers; rounds to even
5488 in the case of a tie.
5489
5490 """
5491 q, r = divmod(a, b)
5492 return q + (2*r + (q&1) > b)
5493
5494def _ilog(x, M, L = 8):
5495 """Integer approximation to M*log(x/M), with absolute error boundable
5496 in terms only of x/M.
5497
5498 Given positive integers x and M, return an integer approximation to
5499 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5500 between the approximation and the exact result is at most 22. For
5501 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5502 both cases these are upper bounds on the error; it will usually be
5503 much smaller."""
5504
5505 # The basic algorithm is the following: let log1p be the function
5506 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5507 # the reduction
5508 #
5509 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5510 #
5511 # repeatedly until the argument to log1p is small (< 2**-L in
5512 # absolute value). For small y we can use the Taylor series
5513 # expansion
5514 #
5515 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5516 #
5517 # truncating at T such that y**T is small enough. The whole
5518 # computation is carried out in a form of fixed-point arithmetic,
5519 # with a real number z being represented by an integer
5520 # approximation to z*M. To avoid loss of precision, the y below
5521 # is actually an integer approximation to 2**R*y*M, where R is the
5522 # number of reductions performed so far.
5523
5524 y = x-M
5525 # argument reduction; R = number of reductions performed
5526 R = 0
5527 while (R <= L and abs(y) << L-R >= M or
5528 R > L and abs(y) >> R-L >= M):
5529 y = _div_nearest((M*y) << 1,
5530 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5531 R += 1
5532
5533 # Taylor series with T terms
5534 T = -int(-10*len(str(M))//(3*L))
5535 yshift = _rshift_nearest(y, R)
5536 w = _div_nearest(M, T)
5537 for k in range(T-1, 0, -1):
5538 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5539
5540 return _div_nearest(w*y, M)
5541
5542def _dlog10(c, e, p):
5543 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5544 approximation to 10**p * log10(c*10**e), with an absolute error of
5545 at most 1. Assumes that c*10**e is not exactly 1."""
5546
5547 # increase precision by 2; compensate for this by dividing
5548 # final result by 100
5549 p += 2
5550
5551 # write c*10**e as d*10**f with either:
5552 # f >= 0 and 1 <= d <= 10, or
5553 # f <= 0 and 0.1 <= d <= 1.
5554 # Thus for c*10**e close to 1, f = 0
5555 l = len(str(c))
5556 f = e+l - (e+l >= 1)
5557
5558 if p > 0:
5559 M = 10**p
5560 k = e+p-f
5561 if k >= 0:
5562 c *= 10**k
5563 else:
5564 c = _div_nearest(c, 10**-k)
5565
5566 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005567 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005568 log_d = _div_nearest(log_d*M, log_10)
5569 log_tenpower = f*M # exact
5570 else:
5571 log_d = 0 # error < 2.31
Neal Norwitz2f99b242008-08-24 05:48:10 +00005572 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005573
5574 return _div_nearest(log_tenpower+log_d, 100)
5575
5576def _dlog(c, e, p):
5577 """Given integers c, e and p with c > 0, compute an integer
5578 approximation to 10**p * log(c*10**e), with an absolute error of
5579 at most 1. Assumes that c*10**e is not exactly 1."""
5580
5581 # Increase precision by 2. The precision increase is compensated
5582 # for at the end with a division by 100.
5583 p += 2
5584
5585 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5586 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5587 # as 10**p * log(d) + 10**p*f * log(10).
5588 l = len(str(c))
5589 f = e+l - (e+l >= 1)
5590
5591 # compute approximation to 10**p*log(d), with error < 27
5592 if p > 0:
5593 k = e+p-f
5594 if k >= 0:
5595 c *= 10**k
5596 else:
5597 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5598
5599 # _ilog magnifies existing error in c by a factor of at most 10
5600 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5601 else:
5602 # p <= 0: just approximate the whole thing by 0; error < 2.31
5603 log_d = 0
5604
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005605 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005606 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005607 extra = len(str(abs(f)))-1
5608 if p + extra >= 0:
5609 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5610 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5611 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005612 else:
5613 f_log_ten = 0
5614 else:
5615 f_log_ten = 0
5616
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005617 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005618 return _div_nearest(f_log_ten + log_d, 100)
5619
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005620class _Log10Memoize(object):
5621 """Class to compute, store, and allow retrieval of, digits of the
5622 constant log(10) = 2.302585.... This constant is needed by
5623 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5624 def __init__(self):
5625 self.digits = "23025850929940456840179914546843642076011014886"
5626
5627 def getdigits(self, p):
5628 """Given an integer p >= 0, return floor(10**p)*log(10).
5629
5630 For example, self.getdigits(3) returns 2302.
5631 """
5632 # digits are stored as a string, for quick conversion to
5633 # integer in the case that we've already computed enough
5634 # digits; the stored digits should always be correct
5635 # (truncated, not rounded to nearest).
5636 if p < 0:
5637 raise ValueError("p should be nonnegative")
5638
5639 if p >= len(self.digits):
5640 # compute p+3, p+6, p+9, ... digits; continue until at
5641 # least one of the extra digits is nonzero
5642 extra = 3
5643 while True:
5644 # compute p+extra digits, correct to within 1ulp
5645 M = 10**(p+extra+2)
5646 digits = str(_div_nearest(_ilog(10*M, M), 100))
5647 if digits[-extra:] != '0'*extra:
5648 break
5649 extra += 3
5650 # keep all reliable digits so far; remove trailing zeros
5651 # and next nonzero digit
5652 self.digits = digits.rstrip('0')[:-1]
5653 return int(self.digits[:p+1])
5654
5655_log10_digits = _Log10Memoize().getdigits
5656
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005657def _iexp(x, M, L=8):
5658 """Given integers x and M, M > 0, such that x/M is small in absolute
5659 value, compute an integer approximation to M*exp(x/M). For 0 <=
5660 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5661 is usually much smaller)."""
5662
5663 # Algorithm: to compute exp(z) for a real number z, first divide z
5664 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5665 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5666 # series
5667 #
5668 # expm1(x) = x + x**2/2! + x**3/3! + ...
5669 #
5670 # Now use the identity
5671 #
5672 # expm1(2x) = expm1(x)*(expm1(x)+2)
5673 #
5674 # R times to compute the sequence expm1(z/2**R),
5675 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5676
5677 # Find R such that x/2**R/M <= 2**-L
5678 R = _nbits((x<<L)//M)
5679
5680 # Taylor series. (2**L)**T > M
5681 T = -int(-10*len(str(M))//(3*L))
5682 y = _div_nearest(x, T)
5683 Mshift = M<<R
5684 for i in range(T-1, 0, -1):
5685 y = _div_nearest(x*(Mshift + y), Mshift * i)
5686
5687 # Expansion
5688 for k in range(R-1, -1, -1):
5689 Mshift = M<<(k+2)
5690 y = _div_nearest(y*(y+Mshift), Mshift)
5691
5692 return M+y
5693
5694def _dexp(c, e, p):
5695 """Compute an approximation to exp(c*10**e), with p decimal places of
5696 precision.
5697
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005698 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005699
5700 10**(p-1) <= d <= 10**p, and
5701 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5702
5703 In other words, d*10**f is an approximation to exp(c*10**e) with p
5704 digits of precision, and with an error in d of at most 1. This is
5705 almost, but not quite, the same as the error being < 1ulp: when d
5706 = 10**(p-1) the error could be up to 10 ulp."""
5707
5708 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5709 p += 2
5710
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005711 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005712 extra = max(0, e + len(str(c)) - 1)
5713 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005714
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005715 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005716 # rounding down
5717 shift = e+q
5718 if shift >= 0:
5719 cshift = c*10**shift
5720 else:
5721 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005722 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005723
5724 # reduce remainder back to original precision
5725 rem = _div_nearest(rem, 10**extra)
5726
5727 # error in result of _iexp < 120; error after division < 0.62
5728 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5729
5730def _dpower(xc, xe, yc, ye, p):
5731 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5732 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5733
5734 10**(p-1) <= c <= 10**p, and
5735 (c-1)*10**e < x**y < (c+1)*10**e
5736
5737 in other words, c*10**e is an approximation to x**y with p digits
5738 of precision, and with an error in c of at most 1. (This is
5739 almost, but not quite, the same as the error being < 1ulp: when c
5740 == 10**(p-1) we can only guarantee error < 10ulp.)
5741
5742 We assume that: x is positive and not equal to 1, and y is nonzero.
5743 """
5744
5745 # Find b such that 10**(b-1) <= |y| <= 10**b
5746 b = len(str(abs(yc))) + ye
5747
5748 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5749 lxc = _dlog(xc, xe, p+b+1)
5750
5751 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5752 shift = ye-b
5753 if shift >= 0:
5754 pc = lxc*yc*10**shift
5755 else:
5756 pc = _div_nearest(lxc*yc, 10**-shift)
5757
5758 if pc == 0:
5759 # we prefer a result that isn't exactly 1; this makes it
5760 # easier to compute a correctly rounded result in __pow__
5761 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5762 coeff, exp = 10**(p-1)+1, 1-p
5763 else:
5764 coeff, exp = 10**p-1, -p
5765 else:
5766 coeff, exp = _dexp(pc, -(p+1), p+1)
5767 coeff = _div_nearest(coeff, 10)
5768 exp += 1
5769
5770 return coeff, exp
5771
5772def _log10_lb(c, correction = {
5773 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5774 '6': 23, '7': 16, '8': 10, '9': 5}):
5775 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5776 if c <= 0:
5777 raise ValueError("The argument to _log10_lb should be nonnegative.")
5778 str_c = str(c)
5779 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005780
Guido van Rossumd8faa362007-04-27 19:54:29 +00005781##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005782
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005783def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005784 """Convert other to Decimal.
5785
5786 Verifies that it's ok to use in an implicit construction.
5787 """
5788 if isinstance(other, Decimal):
5789 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005790 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005791 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005792 if raiseit:
5793 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005794 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005795
Guido van Rossumd8faa362007-04-27 19:54:29 +00005796##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005797
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005798# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005799# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005800
5801DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005802 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005803 traps=[DivisionByZero, Overflow, InvalidOperation],
5804 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005805 Emax=999999999,
5806 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005807 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005808)
5809
5810# Pre-made alternate contexts offered by the specification
5811# Don't change these; the user should be able to select these
5812# contexts and be able to reproduce results from other implementations
5813# of the spec.
5814
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005815BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005816 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005817 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5818 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005819)
5820
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005821ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005822 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005823 traps=[],
5824 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005825)
5826
5827
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005828##### crud for parsing strings #############################################
Christian Heimes23daade2008-02-25 12:39:23 +00005829#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005830# Regular expression used for parsing numeric strings. Additional
5831# comments:
5832#
5833# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5834# whitespace. But note that the specification disallows whitespace in
5835# a numeric string.
5836#
5837# 2. For finite numbers (not infinities and NaNs) the body of the
5838# number between the optional sign and the optional exponent must have
5839# at least one decimal digit, possibly after the decimal point. The
Mark Dickinson345adc42009-08-02 10:14:23 +00005840# lookahead expression '(?=\d|\.\d)' checks this.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005841
5842import re
Benjamin Peterson41181742008-07-02 20:22:54 +00005843_parser = re.compile(r""" # A numeric string consists of:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005844# \s*
Benjamin Peterson41181742008-07-02 20:22:54 +00005845 (?P<sign>[-+])? # an optional sign, followed by either...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005846 (
Mark Dickinson345adc42009-08-02 10:14:23 +00005847 (?=\d|\.\d) # ...a number (with at least one digit)
5848 (?P<int>\d*) # having a (possibly empty) integer part
5849 (\.(?P<frac>\d*))? # followed by an optional fractional part
5850 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005851 |
Benjamin Peterson41181742008-07-02 20:22:54 +00005852 Inf(inity)? # ...an infinity, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005853 |
Benjamin Peterson41181742008-07-02 20:22:54 +00005854 (?P<signal>s)? # ...an (optionally signaling)
5855 NaN # NaN
Mark Dickinson345adc42009-08-02 10:14:23 +00005856 (?P<diag>\d*) # with (possibly empty) diagnostic info.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005857 )
5858# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00005859 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005860""", re.VERBOSE | re.IGNORECASE).match
5861
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005862_all_zeros = re.compile('0*$').match
5863_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00005864
5865##### PEP3101 support functions ##############################################
Mark Dickinson79f52032009-03-17 23:12:51 +00005866# The functions in this section have little to do with the Decimal
5867# class, and could potentially be reused or adapted for other pure
Christian Heimesf16baeb2008-02-29 14:57:44 +00005868# Python numeric classes that want to implement __format__
5869#
5870# A format specifier for Decimal looks like:
5871#
Mark Dickinson79f52032009-03-17 23:12:51 +00005872# [[fill]align][sign][0][minimumwidth][,][.precision][type]
Christian Heimesf16baeb2008-02-29 14:57:44 +00005873
5874_parse_format_specifier_regex = re.compile(r"""\A
5875(?:
5876 (?P<fill>.)?
5877 (?P<align>[<>=^])
5878)?
5879(?P<sign>[-+ ])?
5880(?P<zeropad>0)?
5881(?P<minimumwidth>(?!0)\d+)?
Mark Dickinson79f52032009-03-17 23:12:51 +00005882(?P<thousands_sep>,)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00005883(?:\.(?P<precision>0|(?!0)\d+))?
Mark Dickinson79f52032009-03-17 23:12:51 +00005884(?P<type>[eEfFgGn%])?
Christian Heimesf16baeb2008-02-29 14:57:44 +00005885\Z
5886""", re.VERBOSE)
5887
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005888del re
5889
Mark Dickinson79f52032009-03-17 23:12:51 +00005890# The locale module is only needed for the 'n' format specifier. The
5891# rest of the PEP 3101 code functions quite happily without it, so we
5892# don't care too much if locale isn't present.
5893try:
5894 import locale as _locale
5895except ImportError:
5896 pass
5897
5898def _parse_format_specifier(format_spec, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00005899 """Parse and validate a format specifier.
5900
5901 Turns a standard numeric format specifier into a dict, with the
5902 following entries:
5903
5904 fill: fill character to pad field to minimum width
5905 align: alignment type, either '<', '>', '=' or '^'
5906 sign: either '+', '-' or ' '
5907 minimumwidth: nonnegative integer giving minimum width
Mark Dickinson79f52032009-03-17 23:12:51 +00005908 zeropad: boolean, indicating whether to pad with zeros
5909 thousands_sep: string to use as thousands separator, or ''
5910 grouping: grouping for thousands separators, in format
5911 used by localeconv
5912 decimal_point: string to use for decimal point
Christian Heimesf16baeb2008-02-29 14:57:44 +00005913 precision: nonnegative integer giving precision, or None
5914 type: one of the characters 'eEfFgG%', or None
Christian Heimesf16baeb2008-02-29 14:57:44 +00005915
5916 """
5917 m = _parse_format_specifier_regex.match(format_spec)
5918 if m is None:
5919 raise ValueError("Invalid format specifier: " + format_spec)
5920
5921 # get the dictionary
5922 format_dict = m.groupdict()
5923
Mark Dickinson79f52032009-03-17 23:12:51 +00005924 # zeropad; defaults for fill and alignment. If zero padding
5925 # is requested, the fill and align fields should be absent.
Christian Heimesf16baeb2008-02-29 14:57:44 +00005926 fill = format_dict['fill']
5927 align = format_dict['align']
Mark Dickinson79f52032009-03-17 23:12:51 +00005928 format_dict['zeropad'] = (format_dict['zeropad'] is not None)
5929 if format_dict['zeropad']:
5930 if fill is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00005931 raise ValueError("Fill character conflicts with '0'"
5932 " in format specifier: " + format_spec)
Mark Dickinson79f52032009-03-17 23:12:51 +00005933 if align is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00005934 raise ValueError("Alignment conflicts with '0' in "
5935 "format specifier: " + format_spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00005936 format_dict['fill'] = fill or ' '
Mark Dickinson46ab5d02009-09-08 20:22:46 +00005937 # PEP 3101 originally specified that the default alignment should
5938 # be left; it was later agreed that right-aligned makes more sense
5939 # for numeric types. See http://bugs.python.org/issue6857.
5940 format_dict['align'] = align or '>'
Christian Heimesf16baeb2008-02-29 14:57:44 +00005941
Mark Dickinson79f52032009-03-17 23:12:51 +00005942 # default sign handling: '-' for negative, '' for positive
Christian Heimesf16baeb2008-02-29 14:57:44 +00005943 if format_dict['sign'] is None:
5944 format_dict['sign'] = '-'
5945
Christian Heimesf16baeb2008-02-29 14:57:44 +00005946 # minimumwidth defaults to 0; precision remains None if not given
5947 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5948 if format_dict['precision'] is not None:
5949 format_dict['precision'] = int(format_dict['precision'])
5950
5951 # if format type is 'g' or 'G' then a precision of 0 makes little
5952 # sense; convert it to 1. Same if format type is unspecified.
5953 if format_dict['precision'] == 0:
Mark Dickinson7718d2b2009-09-07 16:21:56 +00005954 if format_dict['type'] is None or format_dict['type'] in 'gG':
Christian Heimesf16baeb2008-02-29 14:57:44 +00005955 format_dict['precision'] = 1
5956
Mark Dickinson79f52032009-03-17 23:12:51 +00005957 # determine thousands separator, grouping, and decimal separator, and
5958 # add appropriate entries to format_dict
5959 if format_dict['type'] == 'n':
5960 # apart from separators, 'n' behaves just like 'g'
5961 format_dict['type'] = 'g'
5962 if _localeconv is None:
5963 _localeconv = _locale.localeconv()
5964 if format_dict['thousands_sep'] is not None:
5965 raise ValueError("Explicit thousands separator conflicts with "
5966 "'n' type in format specifier: " + format_spec)
5967 format_dict['thousands_sep'] = _localeconv['thousands_sep']
5968 format_dict['grouping'] = _localeconv['grouping']
5969 format_dict['decimal_point'] = _localeconv['decimal_point']
5970 else:
5971 if format_dict['thousands_sep'] is None:
5972 format_dict['thousands_sep'] = ''
5973 format_dict['grouping'] = [3, 0]
5974 format_dict['decimal_point'] = '.'
Christian Heimesf16baeb2008-02-29 14:57:44 +00005975
5976 return format_dict
5977
Mark Dickinson79f52032009-03-17 23:12:51 +00005978def _format_align(sign, body, spec):
5979 """Given an unpadded, non-aligned numeric string 'body' and sign
5980 string 'sign', add padding and aligment conforming to the given
5981 format specifier dictionary 'spec' (as produced by
5982 parse_format_specifier).
Christian Heimesf16baeb2008-02-29 14:57:44 +00005983
5984 """
Christian Heimesf16baeb2008-02-29 14:57:44 +00005985 # how much extra space do we have to play with?
Mark Dickinson79f52032009-03-17 23:12:51 +00005986 minimumwidth = spec['minimumwidth']
5987 fill = spec['fill']
5988 padding = fill*(minimumwidth - len(sign) - len(body))
Christian Heimesf16baeb2008-02-29 14:57:44 +00005989
Mark Dickinson79f52032009-03-17 23:12:51 +00005990 align = spec['align']
Christian Heimesf16baeb2008-02-29 14:57:44 +00005991 if align == '<':
Christian Heimesf16baeb2008-02-29 14:57:44 +00005992 result = sign + body + padding
Mark Dickinsonad416342009-03-17 18:10:15 +00005993 elif align == '>':
5994 result = padding + sign + body
Christian Heimesf16baeb2008-02-29 14:57:44 +00005995 elif align == '=':
5996 result = sign + padding + body
Mark Dickinson79f52032009-03-17 23:12:51 +00005997 elif align == '^':
Christian Heimesf16baeb2008-02-29 14:57:44 +00005998 half = len(padding)//2
5999 result = padding[:half] + sign + body + padding[half:]
Mark Dickinson79f52032009-03-17 23:12:51 +00006000 else:
6001 raise ValueError('Unrecognised alignment field')
Christian Heimesf16baeb2008-02-29 14:57:44 +00006002
Christian Heimesf16baeb2008-02-29 14:57:44 +00006003 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006004
Mark Dickinson79f52032009-03-17 23:12:51 +00006005def _group_lengths(grouping):
6006 """Convert a localeconv-style grouping into a (possibly infinite)
6007 iterable of integers representing group lengths.
6008
6009 """
6010 # The result from localeconv()['grouping'], and the input to this
6011 # function, should be a list of integers in one of the
6012 # following three forms:
6013 #
6014 # (1) an empty list, or
6015 # (2) nonempty list of positive integers + [0]
6016 # (3) list of positive integers + [locale.CHAR_MAX], or
6017
6018 from itertools import chain, repeat
6019 if not grouping:
6020 return []
6021 elif grouping[-1] == 0 and len(grouping) >= 2:
6022 return chain(grouping[:-1], repeat(grouping[-2]))
6023 elif grouping[-1] == _locale.CHAR_MAX:
6024 return grouping[:-1]
6025 else:
6026 raise ValueError('unrecognised format for grouping')
6027
6028def _insert_thousands_sep(digits, spec, min_width=1):
6029 """Insert thousands separators into a digit string.
6030
6031 spec is a dictionary whose keys should include 'thousands_sep' and
6032 'grouping'; typically it's the result of parsing the format
6033 specifier using _parse_format_specifier.
6034
6035 The min_width keyword argument gives the minimum length of the
6036 result, which will be padded on the left with zeros if necessary.
6037
6038 If necessary, the zero padding adds an extra '0' on the left to
6039 avoid a leading thousands separator. For example, inserting
6040 commas every three digits in '123456', with min_width=8, gives
6041 '0,123,456', even though that has length 9.
6042
6043 """
6044
6045 sep = spec['thousands_sep']
6046 grouping = spec['grouping']
6047
6048 groups = []
6049 for l in _group_lengths(grouping):
Mark Dickinson79f52032009-03-17 23:12:51 +00006050 if l <= 0:
6051 raise ValueError("group length should be positive")
6052 # max(..., 1) forces at least 1 digit to the left of a separator
6053 l = min(max(len(digits), min_width, 1), l)
6054 groups.append('0'*(l - len(digits)) + digits[-l:])
6055 digits = digits[:-l]
6056 min_width -= l
6057 if not digits and min_width <= 0:
6058 break
Mark Dickinson7303b592009-03-18 08:25:36 +00006059 min_width -= len(sep)
Mark Dickinson79f52032009-03-17 23:12:51 +00006060 else:
6061 l = max(len(digits), min_width, 1)
6062 groups.append('0'*(l - len(digits)) + digits[-l:])
6063 return sep.join(reversed(groups))
6064
6065def _format_sign(is_negative, spec):
6066 """Determine sign character."""
6067
6068 if is_negative:
6069 return '-'
6070 elif spec['sign'] in ' +':
6071 return spec['sign']
6072 else:
6073 return ''
6074
6075def _format_number(is_negative, intpart, fracpart, exp, spec):
6076 """Format a number, given the following data:
6077
6078 is_negative: true if the number is negative, else false
6079 intpart: string of digits that must appear before the decimal point
6080 fracpart: string of digits that must come after the point
6081 exp: exponent, as an integer
6082 spec: dictionary resulting from parsing the format specifier
6083
6084 This function uses the information in spec to:
6085 insert separators (decimal separator and thousands separators)
6086 format the sign
6087 format the exponent
6088 add trailing '%' for the '%' type
6089 zero-pad if necessary
6090 fill and align if necessary
6091 """
6092
6093 sign = _format_sign(is_negative, spec)
6094
6095 if fracpart:
6096 fracpart = spec['decimal_point'] + fracpart
6097
6098 if exp != 0 or spec['type'] in 'eE':
6099 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
6100 fracpart += "{0}{1:+}".format(echar, exp)
6101 if spec['type'] == '%':
6102 fracpart += '%'
6103
6104 if spec['zeropad']:
6105 min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
6106 else:
6107 min_width = 0
6108 intpart = _insert_thousands_sep(intpart, spec, min_width)
6109
6110 return _format_align(sign, intpart+fracpart, spec)
6111
6112
Guido van Rossumd8faa362007-04-27 19:54:29 +00006113##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006114
Guido van Rossumd8faa362007-04-27 19:54:29 +00006115# Reusable defaults
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006116_Infinity = Decimal('Inf')
6117_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonf9236412009-01-02 23:23:21 +00006118_NaN = Decimal('NaN')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006119_Zero = Decimal(0)
6120_One = Decimal(1)
6121_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006122
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006123# _SignedInfinity[sign] is infinity w/ that sign
6124_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006125
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006126
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006127
6128if __name__ == '__main__':
6129 import doctest, sys
6130 doctest.testmod(sys.modules[__name__])