blob: aac90d7e5cb298a4c025d6adf9eb7c7a0c4131ad [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
557 fracpart = m.group('frac')
558 exp = int(m.group('exp') or '0')
559 if fracpart is not None:
560 self._int = (intpart+fracpart).lstrip('0') or '0'
561 self._exp = exp - len(fracpart)
562 else:
563 self._int = intpart.lstrip('0') or '0'
564 self._exp = exp
565 self._is_special = False
566 else:
567 diag = m.group('diag')
568 if diag is not None:
569 # NaN
570 self._int = diag.lstrip('0')
571 if m.group('signal'):
572 self._exp = 'N'
573 else:
574 self._exp = 'n'
575 else:
576 # infinity
577 self._int = '0'
578 self._exp = 'F'
579 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000580 return self
581
582 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000583 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000584 if value >= 0:
585 self._sign = 0
586 else:
587 self._sign = 1
588 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000589 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000590 self._is_special = False
591 return self
592
593 # From another decimal
594 if isinstance(value, Decimal):
595 self._exp = value._exp
596 self._sign = value._sign
597 self._int = value._int
598 self._is_special = value._is_special
599 return self
600
601 # From an internal working value
602 if isinstance(value, _WorkRep):
603 self._sign = value.sign
604 self._int = str(value.int)
605 self._exp = int(value.exp)
606 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000607 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000608
609 # tuple/list conversion (possibly from as_tuple())
610 if isinstance(value, (list,tuple)):
611 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000612 raise ValueError('Invalid tuple size in creation of Decimal '
613 'from list or tuple. The list or tuple '
614 'should have exactly three elements.')
615 # process sign. The isinstance test rejects floats
616 if not (isinstance(value[0], int) and value[0] in (0,1)):
617 raise ValueError("Invalid sign. The first value in the tuple "
618 "should be an integer; either 0 for a "
619 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000620 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000621 if value[2] == 'F':
622 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000623 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000624 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000625 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000626 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000627 # process and validate the digits in value[1]
628 digits = []
629 for digit in value[1]:
630 if isinstance(digit, int) and 0 <= digit <= 9:
631 # skip leading zeros
632 if digits or digit != 0:
633 digits.append(digit)
634 else:
635 raise ValueError("The second value in the tuple must "
636 "be composed of integers in the range "
637 "0 through 9.")
638 if value[2] in ('n', 'N'):
639 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000640 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000641 self._exp = value[2]
642 self._is_special = True
643 elif isinstance(value[2], int):
644 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000645 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000646 self._exp = value[2]
647 self._is_special = False
648 else:
649 raise ValueError("The third value in the tuple must "
650 "be an integer, or one of the "
651 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000652 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000653
Raymond Hettingerbf440692004-07-10 14:14:37 +0000654 if isinstance(value, float):
655 raise TypeError("Cannot convert float to Decimal. " +
656 "First convert the float to a string")
657
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():
1560 context = getcontext()
1561 return context._raise_error(InvalidContext)
1562 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001563 raise OverflowError("Cannot convert infinity to int")
1564 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001565 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001566 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001567 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001568 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001569
Christian Heimes969fe572008-01-25 11:23:10 +00001570 __trunc__ = __int__
1571
Christian Heimes0bd4e112008-02-12 22:59:25 +00001572 def real(self):
1573 return self
Mark Dickinson315a20a2009-01-04 21:34:18 +00001574 real = property(real)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001575
Christian Heimes0bd4e112008-02-12 22:59:25 +00001576 def imag(self):
1577 return Decimal(0)
Mark Dickinson315a20a2009-01-04 21:34:18 +00001578 imag = property(imag)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001579
1580 def conjugate(self):
1581 return self
1582
1583 def __complex__(self):
1584 return complex(float(self))
1585
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001586 def _fix_nan(self, context):
1587 """Decapitate the payload of a NaN to fit the context"""
1588 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001589
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001590 # maximum length of payload is precision if _clamp=0,
1591 # precision-1 if _clamp=1.
1592 max_payload_len = context.prec - context._clamp
1593 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001594 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1595 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001596 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001597
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001598 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001599 """Round if it is necessary to keep self within prec precision.
1600
1601 Rounds and fixes the exponent. Does not raise on a sNaN.
1602
1603 Arguments:
1604 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001605 context - context used.
1606 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001607
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001608 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001609 if self._isnan():
1610 # decapitate payload if necessary
1611 return self._fix_nan(context)
1612 else:
1613 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001614 return Decimal(self)
1615
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001616 # if self is zero then exponent should be between Etiny and
1617 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1618 Etiny = context.Etiny()
1619 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001620 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001621 exp_max = [context.Emax, Etop][context._clamp]
1622 new_exp = min(max(self._exp, Etiny), exp_max)
1623 if new_exp != self._exp:
1624 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001625 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001626 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001627 return Decimal(self)
1628
1629 # exp_min is the smallest allowable exponent of the result,
1630 # equal to max(self.adjusted()-context.prec+1, Etiny)
1631 exp_min = len(self._int) + self._exp - context.prec
1632 if exp_min > Etop:
1633 # overflow: exp_min > Etop iff self.adjusted() > Emax
1634 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001635 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001636 return context._raise_error(Overflow, 'above Emax', self._sign)
1637 self_is_subnormal = exp_min < Etiny
1638 if self_is_subnormal:
1639 context._raise_error(Subnormal)
1640 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001641
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001642 # round if self has too many digits
1643 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001644 context._raise_error(Rounded)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001645 digits = len(self._int) + self._exp - exp_min
1646 if digits < 0:
1647 self = _dec_from_triple(self._sign, '1', exp_min-1)
1648 digits = 0
1649 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1650 changed = this_function(digits)
1651 coeff = self._int[:digits] or '0'
1652 if changed == 1:
1653 coeff = str(int(coeff)+1)
1654 ans = _dec_from_triple(self._sign, coeff, exp_min)
1655
1656 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001657 context._raise_error(Inexact)
1658 if self_is_subnormal:
1659 context._raise_error(Underflow)
1660 if not ans:
1661 # raise Clamped on underflow to 0
1662 context._raise_error(Clamped)
1663 elif len(ans._int) == context.prec+1:
1664 # we get here only if rescaling rounds the
1665 # cofficient up to exactly 10**context.prec
1666 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001667 ans = _dec_from_triple(ans._sign,
1668 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001669 else:
1670 # Inexact and Rounded have already been raised
1671 ans = context._raise_error(Overflow, 'above Emax',
1672 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001673 return ans
1674
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001675 # fold down if _clamp == 1 and self has too few digits
1676 if context._clamp == 1 and self._exp > Etop:
1677 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001678 self_padded = self._int + '0'*(self._exp - Etop)
1679 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001680
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001681 # here self was representable to begin with; return unchanged
1682 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001683
1684 _pick_rounding_function = {}
1685
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001686 # for each of the rounding functions below:
1687 # self is a finite, nonzero Decimal
1688 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001689 #
1690 # each function returns either -1, 0, or 1, as follows:
1691 # 1 indicates that self should be rounded up (away from zero)
1692 # 0 indicates that self should be truncated, and that all the
1693 # digits to be truncated are zeros (so the value is unchanged)
1694 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001695
1696 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001697 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001698 if _all_zeros(self._int, prec):
1699 return 0
1700 else:
1701 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001702
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001703 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001704 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001705 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001706
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001707 def _round_half_up(self, prec):
1708 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001709 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001710 return 1
1711 elif _all_zeros(self._int, prec):
1712 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001713 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001714 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001715
1716 def _round_half_down(self, prec):
1717 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001718 if _exact_half(self._int, prec):
1719 return -1
1720 else:
1721 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001722
1723 def _round_half_even(self, prec):
1724 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001725 if _exact_half(self._int, prec) and \
1726 (prec == 0 or self._int[prec-1] in '02468'):
1727 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001728 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001729 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001730
1731 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001732 """Rounds up (not away from 0 if negative.)"""
1733 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001734 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001735 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001736 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001737
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001738 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001739 """Rounds down (not towards 0 if negative)"""
1740 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001741 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001742 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001743 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001744
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001745 def _round_05up(self, prec):
1746 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001747 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001748 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001749 else:
1750 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001751
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001752 def __round__(self, n=None):
1753 """Round self to the nearest integer, or to a given precision.
1754
1755 If only one argument is supplied, round a finite Decimal
1756 instance self to the nearest integer. If self is infinite or
1757 a NaN then a Python exception is raised. If self is finite
1758 and lies exactly halfway between two integers then it is
1759 rounded to the integer with even last digit.
1760
1761 >>> round(Decimal('123.456'))
1762 123
1763 >>> round(Decimal('-456.789'))
1764 -457
1765 >>> round(Decimal('-3.0'))
1766 -3
1767 >>> round(Decimal('2.5'))
1768 2
1769 >>> round(Decimal('3.5'))
1770 4
1771 >>> round(Decimal('Inf'))
1772 Traceback (most recent call last):
1773 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001774 OverflowError: cannot round an infinity
1775 >>> round(Decimal('NaN'))
1776 Traceback (most recent call last):
1777 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001778 ValueError: cannot round a NaN
1779
1780 If a second argument n is supplied, self is rounded to n
1781 decimal places using the rounding mode for the current
1782 context.
1783
1784 For an integer n, round(self, -n) is exactly equivalent to
1785 self.quantize(Decimal('1En')).
1786
1787 >>> round(Decimal('123.456'), 0)
1788 Decimal('123')
1789 >>> round(Decimal('123.456'), 2)
1790 Decimal('123.46')
1791 >>> round(Decimal('123.456'), -2)
1792 Decimal('1E+2')
1793 >>> round(Decimal('-Infinity'), 37)
1794 Decimal('NaN')
1795 >>> round(Decimal('sNaN123'), 0)
1796 Decimal('NaN123')
1797
1798 """
1799 if n is not None:
1800 # two-argument form: use the equivalent quantize call
1801 if not isinstance(n, int):
1802 raise TypeError('Second argument to round should be integral')
1803 exp = _dec_from_triple(0, '1', -n)
1804 return self.quantize(exp)
1805
1806 # one-argument form
1807 if self._is_special:
1808 if self.is_nan():
1809 raise ValueError("cannot round a NaN")
1810 else:
1811 raise OverflowError("cannot round an infinity")
1812 return int(self._rescale(0, ROUND_HALF_EVEN))
1813
1814 def __floor__(self):
1815 """Return the floor of self, as an integer.
1816
1817 For a finite Decimal instance self, return the greatest
1818 integer n such that n <= self. If self is infinite or a NaN
1819 then a Python exception is raised.
1820
1821 """
1822 if self._is_special:
1823 if self.is_nan():
1824 raise ValueError("cannot round a NaN")
1825 else:
1826 raise OverflowError("cannot round an infinity")
1827 return int(self._rescale(0, ROUND_FLOOR))
1828
1829 def __ceil__(self):
1830 """Return the ceiling of self, as an integer.
1831
1832 For a finite Decimal instance self, return the least integer n
1833 such that n >= self. If self is infinite or a NaN then a
1834 Python exception is raised.
1835
1836 """
1837 if self._is_special:
1838 if self.is_nan():
1839 raise ValueError("cannot round a NaN")
1840 else:
1841 raise OverflowError("cannot round an infinity")
1842 return int(self._rescale(0, ROUND_CEILING))
1843
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001844 def fma(self, other, third, context=None):
1845 """Fused multiply-add.
1846
1847 Returns self*other+third with no rounding of the intermediate
1848 product self*other.
1849
1850 self and other are multiplied together, with no rounding of
1851 the result. The third operand is then added to the result,
1852 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001853 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001854
1855 other = _convert_other(other, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001856
1857 # compute product; raise InvalidOperation if either operand is
1858 # a signaling NaN or if the product is zero times infinity.
1859 if self._is_special or other._is_special:
1860 if context is None:
1861 context = getcontext()
1862 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001863 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001864 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001865 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001866 if self._exp == 'n':
1867 product = self
1868 elif other._exp == 'n':
1869 product = other
1870 elif self._exp == 'F':
1871 if not other:
1872 return context._raise_error(InvalidOperation,
1873 'INF * 0 in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001874 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001875 elif other._exp == 'F':
1876 if not self:
1877 return context._raise_error(InvalidOperation,
1878 '0 * INF in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001879 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001880 else:
1881 product = _dec_from_triple(self._sign ^ other._sign,
1882 str(int(self._int) * int(other._int)),
1883 self._exp + other._exp)
1884
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001885 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001886 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001887
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001888 def _power_modulo(self, other, modulo, context=None):
1889 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001890
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001891 # if can't convert other and modulo to Decimal, raise
1892 # TypeError; there's no point returning NotImplemented (no
1893 # equivalent of __rpow__ for three argument pow)
1894 other = _convert_other(other, raiseit=True)
1895 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001896
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001897 if context is None:
1898 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001899
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001900 # deal with NaNs: if there are any sNaNs then first one wins,
1901 # (i.e. behaviour for NaNs is identical to that of fma)
1902 self_is_nan = self._isnan()
1903 other_is_nan = other._isnan()
1904 modulo_is_nan = modulo._isnan()
1905 if self_is_nan or other_is_nan or modulo_is_nan:
1906 if self_is_nan == 2:
1907 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001908 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001909 if other_is_nan == 2:
1910 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001911 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001912 if modulo_is_nan == 2:
1913 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001914 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001915 if self_is_nan:
1916 return self._fix_nan(context)
1917 if other_is_nan:
1918 return other._fix_nan(context)
1919 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001920
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001921 # check inputs: we apply same restrictions as Python's pow()
1922 if not (self._isinteger() and
1923 other._isinteger() and
1924 modulo._isinteger()):
1925 return context._raise_error(InvalidOperation,
1926 'pow() 3rd argument not allowed '
1927 'unless all arguments are integers')
1928 if other < 0:
1929 return context._raise_error(InvalidOperation,
1930 'pow() 2nd argument cannot be '
1931 'negative when 3rd argument specified')
1932 if not modulo:
1933 return context._raise_error(InvalidOperation,
1934 'pow() 3rd argument cannot be 0')
1935
1936 # additional restriction for decimal: the modulus must be less
1937 # than 10**prec in absolute value
1938 if modulo.adjusted() >= context.prec:
1939 return context._raise_error(InvalidOperation,
1940 'insufficient precision: pow() 3rd '
1941 'argument must not have more than '
1942 'precision digits')
1943
1944 # define 0**0 == NaN, for consistency with two-argument pow
1945 # (even though it hurts!)
1946 if not other and not self:
1947 return context._raise_error(InvalidOperation,
1948 'at least one of pow() 1st argument '
1949 'and 2nd argument must be nonzero ;'
1950 '0**0 is not defined')
1951
1952 # compute sign of result
1953 if other._iseven():
1954 sign = 0
1955 else:
1956 sign = self._sign
1957
1958 # convert modulo to a Python integer, and self and other to
1959 # Decimal integers (i.e. force their exponents to be >= 0)
1960 modulo = abs(int(modulo))
1961 base = _WorkRep(self.to_integral_value())
1962 exponent = _WorkRep(other.to_integral_value())
1963
1964 # compute result using integer pow()
1965 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1966 for i in range(exponent.exp):
1967 base = pow(base, 10, modulo)
1968 base = pow(base, exponent.int, modulo)
1969
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001970 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001971
1972 def _power_exact(self, other, p):
1973 """Attempt to compute self**other exactly.
1974
1975 Given Decimals self and other and an integer p, attempt to
1976 compute an exact result for the power self**other, with p
1977 digits of precision. Return None if self**other is not
1978 exactly representable in p digits.
1979
1980 Assumes that elimination of special cases has already been
1981 performed: self and other must both be nonspecial; self must
1982 be positive and not numerically equal to 1; other must be
1983 nonzero. For efficiency, other._exp should not be too large,
1984 so that 10**abs(other._exp) is a feasible calculation."""
1985
1986 # In the comments below, we write x for the value of self and
1987 # y for the value of other. Write x = xc*10**xe and y =
1988 # yc*10**ye.
1989
1990 # The main purpose of this method is to identify the *failure*
1991 # of x**y to be exactly representable with as little effort as
1992 # possible. So we look for cheap and easy tests that
1993 # eliminate the possibility of x**y being exact. Only if all
1994 # these tests are passed do we go on to actually compute x**y.
1995
1996 # Here's the main idea. First normalize both x and y. We
1997 # express y as a rational m/n, with m and n relatively prime
1998 # and n>0. Then for x**y to be exactly representable (at
1999 # *any* precision), xc must be the nth power of a positive
2000 # integer and xe must be divisible by n. If m is negative
2001 # then additionally xc must be a power of either 2 or 5, hence
2002 # a power of 2**n or 5**n.
2003 #
2004 # There's a limit to how small |y| can be: if y=m/n as above
2005 # then:
2006 #
2007 # (1) if xc != 1 then for the result to be representable we
2008 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
2009 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
2010 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
2011 # representable.
2012 #
2013 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
2014 # |y| < 1/|xe| then the result is not representable.
2015 #
2016 # Note that since x is not equal to 1, at least one of (1) and
2017 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2018 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2019 #
2020 # There's also a limit to how large y can be, at least if it's
2021 # positive: the normalized result will have coefficient xc**y,
2022 # so if it's representable then xc**y < 10**p, and y <
2023 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
2024 # not exactly representable.
2025
2026 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2027 # so |y| < 1/xe and the result is not representable.
2028 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2029 # < 1/nbits(xc).
2030
2031 x = _WorkRep(self)
2032 xc, xe = x.int, x.exp
2033 while xc % 10 == 0:
2034 xc //= 10
2035 xe += 1
2036
2037 y = _WorkRep(other)
2038 yc, ye = y.int, y.exp
2039 while yc % 10 == 0:
2040 yc //= 10
2041 ye += 1
2042
2043 # case where xc == 1: result is 10**(xe*y), with xe*y
2044 # required to be an integer
2045 if xc == 1:
2046 if ye >= 0:
2047 exponent = xe*yc*10**ye
2048 else:
2049 exponent, remainder = divmod(xe*yc, 10**-ye)
2050 if remainder:
2051 return None
2052 if y.sign == 1:
2053 exponent = -exponent
2054 # if other is a nonnegative integer, use ideal exponent
2055 if other._isinteger() and other._sign == 0:
2056 ideal_exponent = self._exp*int(other)
2057 zeros = min(exponent-ideal_exponent, p-1)
2058 else:
2059 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002060 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002061
2062 # case where y is negative: xc must be either a power
2063 # of 2 or a power of 5.
2064 if y.sign == 1:
2065 last_digit = xc % 10
2066 if last_digit in (2,4,6,8):
2067 # quick test for power of 2
2068 if xc & -xc != xc:
2069 return None
2070 # now xc is a power of 2; e is its exponent
2071 e = _nbits(xc)-1
2072 # find e*y and xe*y; both must be integers
2073 if ye >= 0:
2074 y_as_int = yc*10**ye
2075 e = e*y_as_int
2076 xe = xe*y_as_int
2077 else:
2078 ten_pow = 10**-ye
2079 e, remainder = divmod(e*yc, ten_pow)
2080 if remainder:
2081 return None
2082 xe, remainder = divmod(xe*yc, ten_pow)
2083 if remainder:
2084 return None
2085
2086 if e*65 >= p*93: # 93/65 > log(10)/log(5)
2087 return None
2088 xc = 5**e
2089
2090 elif last_digit == 5:
2091 # e >= log_5(xc) if xc is a power of 5; we have
2092 # equality all the way up to xc=5**2658
2093 e = _nbits(xc)*28//65
2094 xc, remainder = divmod(5**e, xc)
2095 if remainder:
2096 return None
2097 while xc % 5 == 0:
2098 xc //= 5
2099 e -= 1
2100 if ye >= 0:
2101 y_as_integer = yc*10**ye
2102 e = e*y_as_integer
2103 xe = xe*y_as_integer
2104 else:
2105 ten_pow = 10**-ye
2106 e, remainder = divmod(e*yc, ten_pow)
2107 if remainder:
2108 return None
2109 xe, remainder = divmod(xe*yc, ten_pow)
2110 if remainder:
2111 return None
2112 if e*3 >= p*10: # 10/3 > log(10)/log(2)
2113 return None
2114 xc = 2**e
2115 else:
2116 return None
2117
2118 if xc >= 10**p:
2119 return None
2120 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002121 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002122
2123 # now y is positive; find m and n such that y = m/n
2124 if ye >= 0:
2125 m, n = yc*10**ye, 1
2126 else:
2127 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2128 return None
2129 xc_bits = _nbits(xc)
2130 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2131 return None
2132 m, n = yc, 10**(-ye)
2133 while m % 2 == n % 2 == 0:
2134 m //= 2
2135 n //= 2
2136 while m % 5 == n % 5 == 0:
2137 m //= 5
2138 n //= 5
2139
2140 # compute nth root of xc*10**xe
2141 if n > 1:
2142 # if 1 < xc < 2**n then xc isn't an nth power
2143 if xc != 1 and xc_bits <= n:
2144 return None
2145
2146 xe, rem = divmod(xe, n)
2147 if rem != 0:
2148 return None
2149
2150 # compute nth root of xc using Newton's method
2151 a = 1 << -(-_nbits(xc)//n) # initial estimate
2152 while True:
2153 q, r = divmod(xc, a**(n-1))
2154 if a <= q:
2155 break
2156 else:
2157 a = (a*(n-1) + q)//n
2158 if not (a == q and r == 0):
2159 return None
2160 xc = a
2161
2162 # now xc*10**xe is the nth root of the original xc*10**xe
2163 # compute mth power of xc*10**xe
2164
2165 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2166 # 10**p and the result is not representable.
2167 if xc > 1 and m > p*100//_log10_lb(xc):
2168 return None
2169 xc = xc**m
2170 xe *= m
2171 if xc > 10**p:
2172 return None
2173
2174 # by this point the result *is* exactly representable
2175 # adjust the exponent to get as close as possible to the ideal
2176 # exponent, if necessary
2177 str_xc = str(xc)
2178 if other._isinteger() and other._sign == 0:
2179 ideal_exponent = self._exp*int(other)
2180 zeros = min(xe-ideal_exponent, p-len(str_xc))
2181 else:
2182 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002183 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002184
2185 def __pow__(self, other, modulo=None, context=None):
2186 """Return self ** other [ % modulo].
2187
2188 With two arguments, compute self**other.
2189
2190 With three arguments, compute (self**other) % modulo. For the
2191 three argument form, the following restrictions on the
2192 arguments hold:
2193
2194 - all three arguments must be integral
2195 - other must be nonnegative
2196 - either self or other (or both) must be nonzero
2197 - modulo must be nonzero and must have at most p digits,
2198 where p is the context precision.
2199
2200 If any of these restrictions is violated the InvalidOperation
2201 flag is raised.
2202
2203 The result of pow(self, other, modulo) is identical to the
2204 result that would be obtained by computing (self**other) %
2205 modulo with unbounded precision, but is computed more
2206 efficiently. It is always exact.
2207 """
2208
2209 if modulo is not None:
2210 return self._power_modulo(other, modulo, context)
2211
2212 other = _convert_other(other)
2213 if other is NotImplemented:
2214 return other
2215
2216 if context is None:
2217 context = getcontext()
2218
2219 # either argument is a NaN => result is NaN
2220 ans = self._check_nans(other, context)
2221 if ans:
2222 return ans
2223
2224 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2225 if not other:
2226 if not self:
2227 return context._raise_error(InvalidOperation, '0 ** 0')
2228 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002229 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002230
2231 # result has sign 1 iff self._sign is 1 and other is an odd integer
2232 result_sign = 0
2233 if self._sign == 1:
2234 if other._isinteger():
2235 if not other._iseven():
2236 result_sign = 1
2237 else:
2238 # -ve**noninteger = NaN
2239 # (-0)**noninteger = 0**noninteger
2240 if self:
2241 return context._raise_error(InvalidOperation,
2242 'x ** y with x negative and y not an integer')
2243 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002244 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002245
2246 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2247 if not self:
2248 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002249 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002250 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002251 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002252
2253 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002254 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002255 if other._sign == 0:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002256 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002257 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002258 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002259
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002260 # 1**other = 1, but the choice of exponent and the flags
2261 # depend on the exponent of self, and on whether other is a
2262 # positive integer, a negative integer, or neither
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002263 if self == _One:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002264 if other._isinteger():
2265 # exp = max(self._exp*max(int(other), 0),
2266 # 1-context.prec) but evaluating int(other) directly
2267 # is dangerous until we know other is small (other
2268 # could be 1e999999999)
2269 if other._sign == 1:
2270 multiplier = 0
2271 elif other > context.prec:
2272 multiplier = context.prec
2273 else:
2274 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002275
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002276 exp = self._exp * multiplier
2277 if exp < 1-context.prec:
2278 exp = 1-context.prec
2279 context._raise_error(Rounded)
2280 else:
2281 context._raise_error(Inexact)
2282 context._raise_error(Rounded)
2283 exp = 1-context.prec
2284
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002285 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002286
2287 # compute adjusted exponent of self
2288 self_adj = self.adjusted()
2289
2290 # self ** infinity is infinity if self > 1, 0 if self < 1
2291 # self ** -infinity is infinity if self < 1, 0 if self > 1
2292 if other._isinfinity():
2293 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002294 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002295 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002296 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002297
2298 # from here on, the result always goes through the call
2299 # to _fix at the end of this function.
2300 ans = None
2301
2302 # crude test to catch cases of extreme overflow/underflow. If
2303 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2304 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2305 # self**other >= 10**(Emax+1), so overflow occurs. The test
2306 # for underflow is similar.
2307 bound = self._log10_exp_bound() + other.adjusted()
2308 if (self_adj >= 0) == (other._sign == 0):
2309 # self > 1 and other +ve, or self < 1 and other -ve
2310 # possibility of overflow
2311 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002312 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002313 else:
2314 # self > 1 and other -ve, or self < 1 and other +ve
2315 # possibility of underflow to 0
2316 Etiny = context.Etiny()
2317 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002318 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002319
2320 # try for an exact result with precision +1
2321 if ans is None:
2322 ans = self._power_exact(other, context.prec + 1)
2323 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002324 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002325
2326 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2327 if ans is None:
2328 p = context.prec
2329 x = _WorkRep(self)
2330 xc, xe = x.int, x.exp
2331 y = _WorkRep(other)
2332 yc, ye = y.int, y.exp
2333 if y.sign == 1:
2334 yc = -yc
2335
2336 # compute correctly rounded result: start with precision +3,
2337 # then increase precision until result is unambiguously roundable
2338 extra = 3
2339 while True:
2340 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2341 if coeff % (5*10**(len(str(coeff))-p-1)):
2342 break
2343 extra += 3
2344
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002345 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002346
2347 # the specification says that for non-integer other we need to
2348 # raise Inexact, even when the result is actually exact. In
2349 # the same way, we need to raise Underflow here if the result
2350 # is subnormal. (The call to _fix will take care of raising
2351 # Rounded and Subnormal, as usual.)
2352 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002353 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002354 # pad with zeros up to length context.prec+1 if necessary
2355 if len(ans._int) <= context.prec:
2356 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002357 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2358 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002359 if ans.adjusted() < context.Emin:
2360 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002361
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002362 # unlike exp, ln and log10, the power function respects the
2363 # rounding mode; no need to use ROUND_HALF_EVEN here
2364 ans = ans._fix(context)
2365 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002366
2367 def __rpow__(self, other, context=None):
2368 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002369 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002370 if other is NotImplemented:
2371 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002372 return other.__pow__(self, context=context)
2373
2374 def normalize(self, context=None):
2375 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002376
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002377 if context is None:
2378 context = getcontext()
2379
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002380 if self._is_special:
2381 ans = self._check_nans(context=context)
2382 if ans:
2383 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002384
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002385 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002386 if dup._isinfinity():
2387 return dup
2388
2389 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002390 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002391 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002392 end = len(dup._int)
2393 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002394 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002395 exp += 1
2396 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002397 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002398
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002399 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002400 """Quantize self so its exponent is the same as that of exp.
2401
2402 Similar to self._rescale(exp._exp) but with error checking.
2403 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002404 exp = _convert_other(exp, raiseit=True)
2405
2406 if context is None:
2407 context = getcontext()
2408 if rounding is None:
2409 rounding = context.rounding
2410
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002411 if self._is_special or exp._is_special:
2412 ans = self._check_nans(exp, context)
2413 if ans:
2414 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002415
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002416 if exp._isinfinity() or self._isinfinity():
2417 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002418 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002419 return context._raise_error(InvalidOperation,
2420 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002421
2422 # if we're not watching exponents, do a simple rescale
2423 if not watchexp:
2424 ans = self._rescale(exp._exp, rounding)
2425 # raise Inexact and Rounded where appropriate
2426 if ans._exp > self._exp:
2427 context._raise_error(Rounded)
2428 if ans != self:
2429 context._raise_error(Inexact)
2430 return ans
2431
2432 # exp._exp should be between Etiny and Emax
2433 if not (context.Etiny() <= exp._exp <= context.Emax):
2434 return context._raise_error(InvalidOperation,
2435 'target exponent out of bounds in quantize')
2436
2437 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002438 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002439 return ans._fix(context)
2440
2441 self_adjusted = self.adjusted()
2442 if self_adjusted > context.Emax:
2443 return context._raise_error(InvalidOperation,
2444 'exponent of quantize result too large for current context')
2445 if self_adjusted - exp._exp + 1 > context.prec:
2446 return context._raise_error(InvalidOperation,
2447 'quantize result has too many digits for current context')
2448
2449 ans = self._rescale(exp._exp, rounding)
2450 if ans.adjusted() > context.Emax:
2451 return context._raise_error(InvalidOperation,
2452 'exponent of quantize result too large for current context')
2453 if len(ans._int) > context.prec:
2454 return context._raise_error(InvalidOperation,
2455 'quantize result has too many digits for current context')
2456
2457 # raise appropriate flags
2458 if ans._exp > self._exp:
2459 context._raise_error(Rounded)
2460 if ans != self:
2461 context._raise_error(Inexact)
2462 if ans and ans.adjusted() < context.Emin:
2463 context._raise_error(Subnormal)
2464
2465 # call to fix takes care of any necessary folddown
2466 ans = ans._fix(context)
2467 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002468
2469 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002470 """Return True if self and other have the same exponent; otherwise
2471 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002472
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002473 If either operand is a special value, the following rules are used:
2474 * return True if both operands are infinities
2475 * return True if both operands are NaNs
2476 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002477 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002478 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002479 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002480 return (self.is_nan() and other.is_nan() or
2481 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002482 return self._exp == other._exp
2483
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002484 def _rescale(self, exp, rounding):
2485 """Rescale self so that the exponent is exp, either by padding with zeros
2486 or by truncating digits, using the given rounding mode.
2487
2488 Specials are returned without change. This operation is
2489 quiet: it raises no flags, and uses no information from the
2490 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002491
2492 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002493 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002494 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002495 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002496 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002497 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002498 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002499
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002500 if self._exp >= exp:
2501 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002502 return _dec_from_triple(self._sign,
2503 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002504
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002505 # too many digits; round and lose data. If self.adjusted() <
2506 # exp-1, replace self by 10**(exp-1) before rounding
2507 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002508 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002509 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002510 digits = 0
2511 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002512 changed = this_function(digits)
2513 coeff = self._int[:digits] or '0'
2514 if changed == 1:
2515 coeff = str(int(coeff)+1)
2516 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002517
Christian Heimesf16baeb2008-02-29 14:57:44 +00002518 def _round(self, places, rounding):
2519 """Round a nonzero, nonspecial Decimal to a fixed number of
2520 significant figures, using the given rounding mode.
2521
2522 Infinities, NaNs and zeros are returned unaltered.
2523
2524 This operation is quiet: it raises no flags, and uses no
2525 information from the context.
2526
2527 """
2528 if places <= 0:
2529 raise ValueError("argument should be at least 1 in _round")
2530 if self._is_special or not self:
2531 return Decimal(self)
2532 ans = self._rescale(self.adjusted()+1-places, rounding)
2533 # it can happen that the rescale alters the adjusted exponent;
2534 # for example when rounding 99.97 to 3 significant figures.
2535 # When this happens we end up with an extra 0 at the end of
2536 # the number; a second rescale fixes this.
2537 if ans.adjusted() != self.adjusted():
2538 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2539 return ans
2540
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002541 def to_integral_exact(self, rounding=None, context=None):
2542 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002543
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002544 If no rounding mode is specified, take the rounding mode from
2545 the context. This method raises the Rounded and Inexact flags
2546 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002547
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002548 See also: to_integral_value, which does exactly the same as
2549 this method except that it doesn't raise Inexact or Rounded.
2550 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002551 if self._is_special:
2552 ans = self._check_nans(context=context)
2553 if ans:
2554 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002555 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002556 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002557 return Decimal(self)
2558 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002559 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002560 if context is None:
2561 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002562 if rounding is None:
2563 rounding = context.rounding
2564 context._raise_error(Rounded)
2565 ans = self._rescale(0, rounding)
2566 if ans != self:
2567 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002568 return ans
2569
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002570 def to_integral_value(self, rounding=None, context=None):
2571 """Rounds to the nearest integer, without raising inexact, rounded."""
2572 if context is None:
2573 context = getcontext()
2574 if rounding is None:
2575 rounding = context.rounding
2576 if self._is_special:
2577 ans = self._check_nans(context=context)
2578 if ans:
2579 return ans
2580 return Decimal(self)
2581 if self._exp >= 0:
2582 return Decimal(self)
2583 else:
2584 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002585
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002586 # the method name changed, but we provide also the old one, for compatibility
2587 to_integral = to_integral_value
2588
2589 def sqrt(self, context=None):
2590 """Return the square root of self."""
Christian Heimes0348fb62008-03-26 12:55:56 +00002591 if context is None:
2592 context = getcontext()
2593
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002594 if self._is_special:
2595 ans = self._check_nans(context=context)
2596 if ans:
2597 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002598
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002599 if self._isinfinity() and self._sign == 0:
2600 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002601
2602 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002603 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002604 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002605 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002606
2607 if self._sign == 1:
2608 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2609
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002610 # At this point self represents a positive number. Let p be
2611 # the desired precision and express self in the form c*100**e
2612 # with c a positive real number and e an integer, c and e
2613 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2614 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2615 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2616 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2617 # the closest integer to sqrt(c) with the even integer chosen
2618 # in the case of a tie.
2619 #
2620 # To ensure correct rounding in all cases, we use the
2621 # following trick: we compute the square root to an extra
2622 # place (precision p+1 instead of precision p), rounding down.
2623 # Then, if the result is inexact and its last digit is 0 or 5,
2624 # we increase the last digit to 1 or 6 respectively; if it's
2625 # exact we leave the last digit alone. Now the final round to
2626 # p places (or fewer in the case of underflow) will round
2627 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002628
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002629 # use an extra digit of precision
2630 prec = context.prec+1
2631
2632 # write argument in the form c*100**e where e = self._exp//2
2633 # is the 'ideal' exponent, to be used if the square root is
2634 # exactly representable. l is the number of 'digits' of c in
2635 # base 100, so that 100**(l-1) <= c < 100**l.
2636 op = _WorkRep(self)
2637 e = op.exp >> 1
2638 if op.exp & 1:
2639 c = op.int * 10
2640 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002641 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002642 c = op.int
2643 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002644
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002645 # rescale so that c has exactly prec base 100 'digits'
2646 shift = prec-l
2647 if shift >= 0:
2648 c *= 100**shift
2649 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002650 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002651 c, remainder = divmod(c, 100**-shift)
2652 exact = not remainder
2653 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002654
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002655 # find n = floor(sqrt(c)) using Newton's method
2656 n = 10**prec
2657 while True:
2658 q = c//n
2659 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002660 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002661 else:
2662 n = n + q >> 1
2663 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002664
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002665 if exact:
2666 # result is exact; rescale to use ideal exponent e
2667 if shift >= 0:
2668 # assert n % 10**shift == 0
2669 n //= 10**shift
2670 else:
2671 n *= 10**-shift
2672 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002673 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002674 # result is not exact; fix last digit as described above
2675 if n % 5 == 0:
2676 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002677
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002678 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002679
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002680 # round, and fit to current context
2681 context = context._shallow_copy()
2682 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002683 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002684 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002685
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002686 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002687
2688 def max(self, other, context=None):
2689 """Returns the larger value.
2690
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002691 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002692 NaN (and signals if one is sNaN). Also rounds.
2693 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002694 other = _convert_other(other, raiseit=True)
2695
2696 if context is None:
2697 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002698
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002699 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002700 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002701 # number is always returned
2702 sn = self._isnan()
2703 on = other._isnan()
2704 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002705 if on == 1 and sn == 0:
2706 return self._fix(context)
2707 if sn == 1 and on == 0:
2708 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002709 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002710
Christian Heimes77c02eb2008-02-09 02:18:51 +00002711 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002712 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002713 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002714 # then an ordering is applied:
2715 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002716 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002717 # positive sign and min returns the operand with the negative sign
2718 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002719 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002720 # the result. This is exactly the ordering used in compare_total.
2721 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002722
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002723 if c == -1:
2724 ans = other
2725 else:
2726 ans = self
2727
Christian Heimes2c181612007-12-17 20:04:13 +00002728 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002729
2730 def min(self, other, context=None):
2731 """Returns the smaller value.
2732
Guido van Rossumd8faa362007-04-27 19:54:29 +00002733 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002734 NaN (and signals if one is sNaN). Also rounds.
2735 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002736 other = _convert_other(other, raiseit=True)
2737
2738 if context is None:
2739 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002740
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002741 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002742 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002743 # number is always returned
2744 sn = self._isnan()
2745 on = other._isnan()
2746 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002747 if on == 1 and sn == 0:
2748 return self._fix(context)
2749 if sn == 1 and on == 0:
2750 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002751 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002752
Christian Heimes77c02eb2008-02-09 02:18:51 +00002753 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002754 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002755 c = self.compare_total(other)
2756
2757 if c == -1:
2758 ans = self
2759 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002760 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002761
Christian Heimes2c181612007-12-17 20:04:13 +00002762 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002763
2764 def _isinteger(self):
2765 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002766 if self._is_special:
2767 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002768 if self._exp >= 0:
2769 return True
2770 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002771 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002772
2773 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002774 """Returns True if self is even. Assumes self is an integer."""
2775 if not self or self._exp > 0:
2776 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002777 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002778
2779 def adjusted(self):
2780 """Return the adjusted exponent of self"""
2781 try:
2782 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002783 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002784 except TypeError:
2785 return 0
2786
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002787 def canonical(self, context=None):
2788 """Returns the same Decimal object.
2789
2790 As we do not have different encodings for the same number, the
2791 received object already is in its canonical form.
2792 """
2793 return self
2794
2795 def compare_signal(self, other, context=None):
2796 """Compares self to the other operand numerically.
2797
2798 It's pretty much like compare(), but all NaNs signal, with signaling
2799 NaNs taking precedence over quiet NaNs.
2800 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002801 other = _convert_other(other, raiseit = True)
2802 ans = self._compare_check_nans(other, context)
2803 if ans:
2804 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002805 return self.compare(other, context=context)
2806
2807 def compare_total(self, other):
2808 """Compares self to other using the abstract representations.
2809
2810 This is not like the standard compare, which use their numerical
2811 value. Note that a total ordering is defined for all possible abstract
2812 representations.
2813 """
2814 # if one is negative and the other is positive, it's easy
2815 if self._sign and not other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002816 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002817 if not self._sign and other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002818 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002819 sign = self._sign
2820
2821 # let's handle both NaN types
2822 self_nan = self._isnan()
2823 other_nan = other._isnan()
2824 if self_nan or other_nan:
2825 if self_nan == other_nan:
2826 if self._int < other._int:
2827 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002828 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002829 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002830 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002831 if self._int > other._int:
2832 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002833 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002834 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002835 return _One
2836 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002837
2838 if sign:
2839 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002840 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002841 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002842 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002843 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002844 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002845 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002846 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002847 else:
2848 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002849 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002850 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002851 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002852 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002853 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002854 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002855 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002856
2857 if self < other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002858 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002859 if self > other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002860 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002861
2862 if self._exp < other._exp:
2863 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002864 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002865 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002866 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002867 if self._exp > other._exp:
2868 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002869 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002870 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002871 return _One
2872 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002873
2874
2875 def compare_total_mag(self, other):
2876 """Compares self to other using abstract repr., ignoring sign.
2877
2878 Like compare_total, but with operand's sign ignored and assumed to be 0.
2879 """
2880 s = self.copy_abs()
2881 o = other.copy_abs()
2882 return s.compare_total(o)
2883
2884 def copy_abs(self):
2885 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002886 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002887
2888 def copy_negate(self):
2889 """Returns a copy with the sign inverted."""
2890 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002891 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002892 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002893 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002894
2895 def copy_sign(self, other):
2896 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002897 return _dec_from_triple(other._sign, self._int,
2898 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002899
2900 def exp(self, context=None):
2901 """Returns e ** self."""
2902
2903 if context is None:
2904 context = getcontext()
2905
2906 # exp(NaN) = NaN
2907 ans = self._check_nans(context=context)
2908 if ans:
2909 return ans
2910
2911 # exp(-Infinity) = 0
2912 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002913 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002914
2915 # exp(0) = 1
2916 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002917 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002918
2919 # exp(Infinity) = Infinity
2920 if self._isinfinity() == 1:
2921 return Decimal(self)
2922
2923 # the result is now guaranteed to be inexact (the true
2924 # mathematical result is transcendental). There's no need to
2925 # raise Rounded and Inexact here---they'll always be raised as
2926 # a result of the call to _fix.
2927 p = context.prec
2928 adj = self.adjusted()
2929
2930 # we only need to do any computation for quite a small range
2931 # of adjusted exponents---for example, -29 <= adj <= 10 for
2932 # the default context. For smaller exponent the result is
2933 # indistinguishable from 1 at the given precision, while for
2934 # larger exponent the result either overflows or underflows.
2935 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2936 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002937 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002938 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2939 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002940 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002941 elif self._sign == 0 and adj < -p:
2942 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002943 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002944 elif self._sign == 1 and adj < -p-1:
2945 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002946 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002947 # general case
2948 else:
2949 op = _WorkRep(self)
2950 c, e = op.int, op.exp
2951 if op.sign == 1:
2952 c = -c
2953
2954 # compute correctly rounded result: increase precision by
2955 # 3 digits at a time until we get an unambiguously
2956 # roundable result
2957 extra = 3
2958 while True:
2959 coeff, exp = _dexp(c, e, p+extra)
2960 if coeff % (5*10**(len(str(coeff))-p-1)):
2961 break
2962 extra += 3
2963
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002964 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002965
2966 # at this stage, ans should round correctly with *any*
2967 # rounding mode, not just with ROUND_HALF_EVEN
2968 context = context._shallow_copy()
2969 rounding = context._set_rounding(ROUND_HALF_EVEN)
2970 ans = ans._fix(context)
2971 context.rounding = rounding
2972
2973 return ans
2974
2975 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002976 """Return True if self is canonical; otherwise return False.
2977
2978 Currently, the encoding of a Decimal instance is always
2979 canonical, so this method returns True for any Decimal.
2980 """
2981 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002982
2983 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002984 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002985
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002986 A Decimal instance is considered finite if it is neither
2987 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002988 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002989 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002990
2991 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002992 """Return True if self is infinite; otherwise return False."""
2993 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002994
2995 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002996 """Return True if self is a qNaN or sNaN; otherwise return False."""
2997 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002998
2999 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003000 """Return True if self is a normal number; otherwise return False."""
3001 if self._is_special or not self:
3002 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003003 if context is None:
3004 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003005 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003006
3007 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003008 """Return True if self is a quiet NaN; otherwise return False."""
3009 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003010
3011 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003012 """Return True if self is negative; otherwise return False."""
3013 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003014
3015 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003016 """Return True if self is a signaling NaN; otherwise return False."""
3017 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003018
3019 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003020 """Return True if self is subnormal; otherwise return False."""
3021 if self._is_special or not self:
3022 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003023 if context is None:
3024 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003025 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003026
3027 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003028 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003029 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003030
3031 def _ln_exp_bound(self):
3032 """Compute a lower bound for the adjusted exponent of self.ln().
3033 In other words, compute r such that self.ln() >= 10**r. Assumes
3034 that self is finite and positive and that self != 1.
3035 """
3036
3037 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
3038 adj = self._exp + len(self._int) - 1
3039 if adj >= 1:
3040 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
3041 return len(str(adj*23//10)) - 1
3042 if adj <= -2:
3043 # argument <= 0.1
3044 return len(str((-1-adj)*23//10)) - 1
3045 op = _WorkRep(self)
3046 c, e = op.int, op.exp
3047 if adj == 0:
3048 # 1 < self < 10
3049 num = str(c-10**-e)
3050 den = str(c)
3051 return len(num) - len(den) - (num < den)
3052 # adj == -1, 0.1 <= self < 1
3053 return e + len(str(10**-e - c)) - 1
3054
3055
3056 def ln(self, context=None):
3057 """Returns the natural (base e) logarithm of self."""
3058
3059 if context is None:
3060 context = getcontext()
3061
3062 # ln(NaN) = NaN
3063 ans = self._check_nans(context=context)
3064 if ans:
3065 return ans
3066
3067 # ln(0.0) == -Infinity
3068 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003069 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003070
3071 # ln(Infinity) = Infinity
3072 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003073 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003074
3075 # ln(1.0) == 0.0
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003076 if self == _One:
3077 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003078
3079 # ln(negative) raises InvalidOperation
3080 if self._sign == 1:
3081 return context._raise_error(InvalidOperation,
3082 'ln of a negative value')
3083
3084 # result is irrational, so necessarily inexact
3085 op = _WorkRep(self)
3086 c, e = op.int, op.exp
3087 p = context.prec
3088
3089 # correctly rounded result: repeatedly increase precision by 3
3090 # until we get an unambiguously roundable result
3091 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3092 while True:
3093 coeff = _dlog(c, e, places)
3094 # assert len(str(abs(coeff)))-p >= 1
3095 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3096 break
3097 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003098 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003099
3100 context = context._shallow_copy()
3101 rounding = context._set_rounding(ROUND_HALF_EVEN)
3102 ans = ans._fix(context)
3103 context.rounding = rounding
3104 return ans
3105
3106 def _log10_exp_bound(self):
3107 """Compute a lower bound for the adjusted exponent of self.log10().
3108 In other words, find r such that self.log10() >= 10**r.
3109 Assumes that self is finite and positive and that self != 1.
3110 """
3111
3112 # For x >= 10 or x < 0.1 we only need a bound on the integer
3113 # part of log10(self), and this comes directly from the
3114 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3115 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3116 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3117
3118 adj = self._exp + len(self._int) - 1
3119 if adj >= 1:
3120 # self >= 10
3121 return len(str(adj))-1
3122 if adj <= -2:
3123 # self < 0.1
3124 return len(str(-1-adj))-1
3125 op = _WorkRep(self)
3126 c, e = op.int, op.exp
3127 if adj == 0:
3128 # 1 < self < 10
3129 num = str(c-10**-e)
3130 den = str(231*c)
3131 return len(num) - len(den) - (num < den) + 2
3132 # adj == -1, 0.1 <= self < 1
3133 num = str(10**-e-c)
3134 return len(num) + e - (num < "231") - 1
3135
3136 def log10(self, context=None):
3137 """Returns the base 10 logarithm of self."""
3138
3139 if context is None:
3140 context = getcontext()
3141
3142 # log10(NaN) = NaN
3143 ans = self._check_nans(context=context)
3144 if ans:
3145 return ans
3146
3147 # log10(0.0) == -Infinity
3148 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003149 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003150
3151 # log10(Infinity) = Infinity
3152 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003153 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003154
3155 # log10(negative or -Infinity) raises InvalidOperation
3156 if self._sign == 1:
3157 return context._raise_error(InvalidOperation,
3158 'log10 of a negative value')
3159
3160 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003161 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003162 # answer may need rounding
3163 ans = Decimal(self._exp + len(self._int) - 1)
3164 else:
3165 # result is irrational, so necessarily inexact
3166 op = _WorkRep(self)
3167 c, e = op.int, op.exp
3168 p = context.prec
3169
3170 # correctly rounded result: repeatedly increase precision
3171 # until result is unambiguously roundable
3172 places = p-self._log10_exp_bound()+2
3173 while True:
3174 coeff = _dlog10(c, e, places)
3175 # assert len(str(abs(coeff)))-p >= 1
3176 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3177 break
3178 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003179 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003180
3181 context = context._shallow_copy()
3182 rounding = context._set_rounding(ROUND_HALF_EVEN)
3183 ans = ans._fix(context)
3184 context.rounding = rounding
3185 return ans
3186
3187 def logb(self, context=None):
3188 """ Returns the exponent of the magnitude of self's MSD.
3189
3190 The result is the integer which is the exponent of the magnitude
3191 of the most significant digit of self (as though it were truncated
3192 to a single digit while maintaining the value of that digit and
3193 without limiting the resulting exponent).
3194 """
3195 # logb(NaN) = NaN
3196 ans = self._check_nans(context=context)
3197 if ans:
3198 return ans
3199
3200 if context is None:
3201 context = getcontext()
3202
3203 # logb(+/-Inf) = +Inf
3204 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003205 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003206
3207 # logb(0) = -Inf, DivisionByZero
3208 if not self:
3209 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3210
3211 # otherwise, simply return the adjusted exponent of self, as a
3212 # Decimal. Note that no attempt is made to fit the result
3213 # into the current context.
3214 return Decimal(self.adjusted())
3215
3216 def _islogical(self):
3217 """Return True if self is a logical operand.
3218
Christian Heimes679db4a2008-01-18 09:56:22 +00003219 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003220 an exponent of 0, and a coefficient whose digits must all be
3221 either 0 or 1.
3222 """
3223 if self._sign != 0 or self._exp != 0:
3224 return False
3225 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003226 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003227 return False
3228 return True
3229
3230 def _fill_logical(self, context, opa, opb):
3231 dif = context.prec - len(opa)
3232 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003233 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003234 elif dif < 0:
3235 opa = opa[-context.prec:]
3236 dif = context.prec - len(opb)
3237 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003238 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003239 elif dif < 0:
3240 opb = opb[-context.prec:]
3241 return opa, opb
3242
3243 def logical_and(self, other, context=None):
3244 """Applies an 'and' operation between self and other's digits."""
3245 if context is None:
3246 context = getcontext()
3247 if not self._islogical() or not other._islogical():
3248 return context._raise_error(InvalidOperation)
3249
3250 # fill to context.prec
3251 (opa, opb) = self._fill_logical(context, self._int, other._int)
3252
3253 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003254 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3255 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003256
3257 def logical_invert(self, context=None):
3258 """Invert all its digits."""
3259 if context is None:
3260 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003261 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3262 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003263
3264 def logical_or(self, other, context=None):
3265 """Applies an 'or' operation between self and other's digits."""
3266 if context is None:
3267 context = getcontext()
3268 if not self._islogical() or not other._islogical():
3269 return context._raise_error(InvalidOperation)
3270
3271 # fill to context.prec
3272 (opa, opb) = self._fill_logical(context, self._int, other._int)
3273
3274 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003275 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003276 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003277
3278 def logical_xor(self, other, context=None):
3279 """Applies an 'xor' operation between self and other's digits."""
3280 if context is None:
3281 context = getcontext()
3282 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 max_mag(self, other, context=None):
3293 """Compares the values numerically with their sign ignored."""
3294 other = _convert_other(other, raiseit=True)
3295
3296 if context is None:
3297 context = getcontext()
3298
3299 if self._is_special or other._is_special:
3300 # If one operand is a quiet NaN and the other is number, then the
3301 # number is always returned
3302 sn = self._isnan()
3303 on = other._isnan()
3304 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003305 if on == 1 and sn == 0:
3306 return self._fix(context)
3307 if sn == 1 and on == 0:
3308 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003309 return self._check_nans(other, context)
3310
Christian Heimes77c02eb2008-02-09 02:18:51 +00003311 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003312 if c == 0:
3313 c = self.compare_total(other)
3314
3315 if c == -1:
3316 ans = other
3317 else:
3318 ans = self
3319
Christian Heimes2c181612007-12-17 20:04:13 +00003320 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003321
3322 def min_mag(self, other, context=None):
3323 """Compares the values numerically with their sign ignored."""
3324 other = _convert_other(other, raiseit=True)
3325
3326 if context is None:
3327 context = getcontext()
3328
3329 if self._is_special or other._is_special:
3330 # If one operand is a quiet NaN and the other is number, then the
3331 # number is always returned
3332 sn = self._isnan()
3333 on = other._isnan()
3334 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003335 if on == 1 and sn == 0:
3336 return self._fix(context)
3337 if sn == 1 and on == 0:
3338 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003339 return self._check_nans(other, context)
3340
Christian Heimes77c02eb2008-02-09 02:18:51 +00003341 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003342 if c == 0:
3343 c = self.compare_total(other)
3344
3345 if c == -1:
3346 ans = self
3347 else:
3348 ans = other
3349
Christian Heimes2c181612007-12-17 20:04:13 +00003350 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003351
3352 def next_minus(self, context=None):
3353 """Returns the largest representable number smaller than itself."""
3354 if context is None:
3355 context = getcontext()
3356
3357 ans = self._check_nans(context=context)
3358 if ans:
3359 return ans
3360
3361 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003362 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003363 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003364 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003365
3366 context = context.copy()
3367 context._set_rounding(ROUND_FLOOR)
3368 context._ignore_all_flags()
3369 new_self = self._fix(context)
3370 if new_self != self:
3371 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003372 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3373 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003374
3375 def next_plus(self, context=None):
3376 """Returns the smallest representable number larger than itself."""
3377 if context is None:
3378 context = getcontext()
3379
3380 ans = self._check_nans(context=context)
3381 if ans:
3382 return ans
3383
3384 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003385 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003386 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003387 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003388
3389 context = context.copy()
3390 context._set_rounding(ROUND_CEILING)
3391 context._ignore_all_flags()
3392 new_self = self._fix(context)
3393 if new_self != self:
3394 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003395 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3396 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003397
3398 def next_toward(self, other, context=None):
3399 """Returns the number closest to self, in the direction towards other.
3400
3401 The result is the closest representable number to self
3402 (excluding self) that is in the direction towards other,
3403 unless both have the same value. If the two operands are
3404 numerically equal, then the result is a copy of self with the
3405 sign set to be the same as the sign of other.
3406 """
3407 other = _convert_other(other, raiseit=True)
3408
3409 if context is None:
3410 context = getcontext()
3411
3412 ans = self._check_nans(other, context)
3413 if ans:
3414 return ans
3415
Christian Heimes77c02eb2008-02-09 02:18:51 +00003416 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003417 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003418 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003419
3420 if comparison == -1:
3421 ans = self.next_plus(context)
3422 else: # comparison == 1
3423 ans = self.next_minus(context)
3424
3425 # decide which flags to raise using value of ans
3426 if ans._isinfinity():
3427 context._raise_error(Overflow,
3428 'Infinite result from next_toward',
3429 ans._sign)
3430 context._raise_error(Rounded)
3431 context._raise_error(Inexact)
3432 elif ans.adjusted() < context.Emin:
3433 context._raise_error(Underflow)
3434 context._raise_error(Subnormal)
3435 context._raise_error(Rounded)
3436 context._raise_error(Inexact)
3437 # if precision == 1 then we don't raise Clamped for a
3438 # result 0E-Etiny.
3439 if not ans:
3440 context._raise_error(Clamped)
3441
3442 return ans
3443
3444 def number_class(self, context=None):
3445 """Returns an indication of the class of self.
3446
3447 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003448 sNaN
3449 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003450 -Infinity
3451 -Normal
3452 -Subnormal
3453 -Zero
3454 +Zero
3455 +Subnormal
3456 +Normal
3457 +Infinity
3458 """
3459 if self.is_snan():
3460 return "sNaN"
3461 if self.is_qnan():
3462 return "NaN"
3463 inf = self._isinfinity()
3464 if inf == 1:
3465 return "+Infinity"
3466 if inf == -1:
3467 return "-Infinity"
3468 if self.is_zero():
3469 if self._sign:
3470 return "-Zero"
3471 else:
3472 return "+Zero"
3473 if context is None:
3474 context = getcontext()
3475 if self.is_subnormal(context=context):
3476 if self._sign:
3477 return "-Subnormal"
3478 else:
3479 return "+Subnormal"
3480 # just a normal, regular, boring number, :)
3481 if self._sign:
3482 return "-Normal"
3483 else:
3484 return "+Normal"
3485
3486 def radix(self):
3487 """Just returns 10, as this is Decimal, :)"""
3488 return Decimal(10)
3489
3490 def rotate(self, other, context=None):
3491 """Returns a rotated copy of self, value-of-other times."""
3492 if context is None:
3493 context = getcontext()
3494
3495 ans = self._check_nans(other, context)
3496 if ans:
3497 return ans
3498
3499 if other._exp != 0:
3500 return context._raise_error(InvalidOperation)
3501 if not (-context.prec <= int(other) <= context.prec):
3502 return context._raise_error(InvalidOperation)
3503
3504 if self._isinfinity():
3505 return Decimal(self)
3506
3507 # get values, pad if necessary
3508 torot = int(other)
3509 rotdig = self._int
3510 topad = context.prec - len(rotdig)
3511 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003512 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003513
3514 # let's rotate!
3515 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003516 return _dec_from_triple(self._sign,
3517 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003518
3519 def scaleb (self, other, context=None):
3520 """Returns self operand after adding the second value to its exp."""
3521 if context is None:
3522 context = getcontext()
3523
3524 ans = self._check_nans(other, context)
3525 if ans:
3526 return ans
3527
3528 if other._exp != 0:
3529 return context._raise_error(InvalidOperation)
3530 liminf = -2 * (context.Emax + context.prec)
3531 limsup = 2 * (context.Emax + context.prec)
3532 if not (liminf <= int(other) <= limsup):
3533 return context._raise_error(InvalidOperation)
3534
3535 if self._isinfinity():
3536 return Decimal(self)
3537
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003538 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003539 d = d._fix(context)
3540 return d
3541
3542 def shift(self, other, context=None):
3543 """Returns a shifted copy of self, value-of-other times."""
3544 if context is None:
3545 context = getcontext()
3546
3547 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 if not (-context.prec <= int(other) <= context.prec):
3554 return context._raise_error(InvalidOperation)
3555
3556 if self._isinfinity():
3557 return Decimal(self)
3558
3559 # get values, pad if necessary
3560 torot = int(other)
3561 if not torot:
3562 return Decimal(self)
3563 rotdig = self._int
3564 topad = context.prec - len(rotdig)
3565 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003566 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003567
3568 # let's shift!
3569 if torot < 0:
3570 rotated = rotdig[:torot]
3571 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003572 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003573 rotated = rotated[-context.prec:]
3574
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003575 return _dec_from_triple(self._sign,
3576 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003577
Guido van Rossumd8faa362007-04-27 19:54:29 +00003578 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003579 def __reduce__(self):
3580 return (self.__class__, (str(self),))
3581
3582 def __copy__(self):
3583 if type(self) == Decimal:
3584 return self # I'm immutable; therefore I am my own clone
3585 return self.__class__(str(self))
3586
3587 def __deepcopy__(self, memo):
3588 if type(self) == Decimal:
3589 return self # My components are also immutable
3590 return self.__class__(str(self))
3591
Mark Dickinson79f52032009-03-17 23:12:51 +00003592 # PEP 3101 support. the _localeconv keyword argument should be
3593 # considered private: it's provided for ease of testing only.
3594 def __format__(self, specifier, context=None, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00003595 """Format a Decimal instance according to the given specifier.
3596
3597 The specifier should be a standard format specifier, with the
3598 form described in PEP 3101. Formatting types 'e', 'E', 'f',
Mark Dickinson79f52032009-03-17 23:12:51 +00003599 'F', 'g', 'G', 'n' and '%' are supported. If the formatting
3600 type is omitted it defaults to 'g' or 'G', depending on the
3601 value of context.capitals.
Christian Heimesf16baeb2008-02-29 14:57:44 +00003602 """
3603
3604 # Note: PEP 3101 says that if the type is not present then
3605 # there should be at least one digit after the decimal point.
3606 # We take the liberty of ignoring this requirement for
3607 # Decimal---it's presumably there to make sure that
3608 # format(float, '') behaves similarly to str(float).
3609 if context is None:
3610 context = getcontext()
3611
Mark Dickinson79f52032009-03-17 23:12:51 +00003612 spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003613
Mark Dickinson79f52032009-03-17 23:12:51 +00003614 # special values don't care about the type or precision
Christian Heimesf16baeb2008-02-29 14:57:44 +00003615 if self._is_special:
Mark Dickinson79f52032009-03-17 23:12:51 +00003616 sign = _format_sign(self._sign, spec)
3617 body = str(self.copy_abs())
3618 return _format_align(sign, body, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003619
3620 # a type of None defaults to 'g' or 'G', depending on context
Christian Heimesf16baeb2008-02-29 14:57:44 +00003621 if spec['type'] is None:
3622 spec['type'] = ['g', 'G'][context.capitals]
Mark Dickinson79f52032009-03-17 23:12:51 +00003623
3624 # if type is '%', adjust exponent of self accordingly
3625 if spec['type'] == '%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003626 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3627
3628 # round if necessary, taking rounding mode from the context
3629 rounding = context.rounding
3630 precision = spec['precision']
3631 if precision is not None:
3632 if spec['type'] in 'eE':
3633 self = self._round(precision+1, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003634 elif spec['type'] in 'fF%':
3635 self = self._rescale(-precision, rounding)
Mark Dickinson79f52032009-03-17 23:12:51 +00003636 elif spec['type'] in 'gG' and len(self._int) > precision:
3637 self = self._round(precision, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003638 # special case: zeros with a positive exponent can't be
3639 # represented in fixed point; rescale them to 0e0.
Mark Dickinson79f52032009-03-17 23:12:51 +00003640 if not self and self._exp > 0 and spec['type'] in 'fF%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003641 self = self._rescale(0, rounding)
3642
3643 # figure out placement of the decimal point
3644 leftdigits = self._exp + len(self._int)
Mark Dickinson79f52032009-03-17 23:12:51 +00003645 if spec['type'] in 'eE':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003646 if not self and precision is not None:
3647 dotplace = 1 - precision
3648 else:
3649 dotplace = 1
Mark Dickinson79f52032009-03-17 23:12:51 +00003650 elif spec['type'] in 'fF%':
3651 dotplace = leftdigits
Christian Heimesf16baeb2008-02-29 14:57:44 +00003652 elif spec['type'] in 'gG':
3653 if self._exp <= 0 and leftdigits > -6:
3654 dotplace = leftdigits
3655 else:
3656 dotplace = 1
3657
Mark Dickinson79f52032009-03-17 23:12:51 +00003658 # find digits before and after decimal point, and get exponent
3659 if dotplace < 0:
3660 intpart = '0'
3661 fracpart = '0'*(-dotplace) + self._int
3662 elif dotplace > len(self._int):
3663 intpart = self._int + '0'*(dotplace-len(self._int))
3664 fracpart = ''
Christian Heimesf16baeb2008-02-29 14:57:44 +00003665 else:
Mark Dickinson79f52032009-03-17 23:12:51 +00003666 intpart = self._int[:dotplace] or '0'
3667 fracpart = self._int[dotplace:]
3668 exp = leftdigits-dotplace
Christian Heimesf16baeb2008-02-29 14:57:44 +00003669
Mark Dickinson79f52032009-03-17 23:12:51 +00003670 # done with the decimal-specific stuff; hand over the rest
3671 # of the formatting to the _format_number function
3672 return _format_number(self._sign, intpart, fracpart, exp, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003673
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003674def _dec_from_triple(sign, coefficient, exponent, special=False):
3675 """Create a decimal instance directly, without any validation,
3676 normalization (e.g. removal of leading zeros) or argument
3677 conversion.
3678
3679 This function is for *internal use only*.
3680 """
3681
3682 self = object.__new__(Decimal)
3683 self._sign = sign
3684 self._int = coefficient
3685 self._exp = exponent
3686 self._is_special = special
3687
3688 return self
3689
Raymond Hettinger82417ca2009-02-03 03:54:28 +00003690# Register Decimal as a kind of Number (an abstract base class).
3691# However, do not register it as Real (because Decimals are not
3692# interoperable with floats).
3693_numbers.Number.register(Decimal)
3694
3695
Guido van Rossumd8faa362007-04-27 19:54:29 +00003696##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003697
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003698
3699# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003700rounding_functions = [name for name in Decimal.__dict__.keys()
3701 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003702for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003703 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003704 globalname = name[1:].upper()
3705 val = globals()[globalname]
3706 Decimal._pick_rounding_function[val] = name
3707
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003708del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003709
Thomas Wouters89f507f2006-12-13 04:49:30 +00003710class _ContextManager(object):
3711 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003712
Thomas Wouters89f507f2006-12-13 04:49:30 +00003713 Sets a copy of the supplied context in __enter__() and restores
3714 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003715 """
3716 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003717 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003718 def __enter__(self):
3719 self.saved_context = getcontext()
3720 setcontext(self.new_context)
3721 return self.new_context
3722 def __exit__(self, t, v, tb):
3723 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003724
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003725class Context(object):
3726 """Contains the context for a Decimal instance.
3727
3728 Contains:
3729 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003730 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003731 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003732 raised when it is caused. Otherwise, a value is
3733 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003734 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003735 (Whether or not the trap_enabler is set)
3736 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003737 Emin - Minimum exponent
3738 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003739 capitals - If 1, 1*10^1 is printed as 1E+1.
3740 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003741 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003742 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003743
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003744 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003745 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003746 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003747 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003748 _ignored_flags=None):
3749 if flags is None:
3750 flags = []
3751 if _ignored_flags is None:
3752 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003753 if not isinstance(flags, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003754 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003755 if traps is not None and not isinstance(traps, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003756 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003757 for name, val in locals().items():
3758 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003759 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003760 else:
3761 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003762 del self.self
3763
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003764 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003765 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003766 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003767 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3768 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3769 % vars(self))
3770 names = [f.__name__ for f, v in self.flags.items() if v]
3771 s.append('flags=[' + ', '.join(names) + ']')
3772 names = [t.__name__ for t, v in self.traps.items() if v]
3773 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003774 return ', '.join(s) + ')'
3775
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003776 def clear_flags(self):
3777 """Reset all flags to zero"""
3778 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003779 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003780
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003781 def _shallow_copy(self):
3782 """Returns a shallow copy from self."""
Christian Heimes2c181612007-12-17 20:04:13 +00003783 nc = Context(self.prec, self.rounding, self.traps,
3784 self.flags, self.Emin, self.Emax,
3785 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003786 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003787
3788 def copy(self):
3789 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003790 nc = Context(self.prec, self.rounding, self.traps.copy(),
Christian Heimes2c181612007-12-17 20:04:13 +00003791 self.flags.copy(), self.Emin, self.Emax,
3792 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003793 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003794 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003795
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003796 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003797 """Handles an error
3798
3799 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003800 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003801 trap_enabler is set, it reaises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00003802 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003803 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003804 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003805 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003806 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003807 return error().handle(self, *args)
3808
Raymond Hettinger86173da2008-02-01 20:38:12 +00003809 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003810 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003811 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003812 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003813
3814 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003815 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003816 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003817
3818 def _ignore_all_flags(self):
3819 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003820 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003821
3822 def _ignore_flags(self, *flags):
3823 """Ignore the flags, if they are raised"""
3824 # Do not mutate-- This way, copies of a context leave the original
3825 # alone.
3826 self._ignored_flags = (self._ignored_flags + list(flags))
3827 return list(flags)
3828
3829 def _regard_flags(self, *flags):
3830 """Stop ignoring the flags, if they are raised"""
3831 if flags and isinstance(flags[0], (tuple,list)):
3832 flags = flags[0]
3833 for flag in flags:
3834 self._ignored_flags.remove(flag)
3835
Nick Coghland1abd252008-07-15 15:46:38 +00003836 # We inherit object.__hash__, so we must deny this explicitly
3837 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003838
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003839 def Etiny(self):
3840 """Returns Etiny (= Emin - prec + 1)"""
3841 return int(self.Emin - self.prec + 1)
3842
3843 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003844 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003845 return int(self.Emax - self.prec + 1)
3846
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003847 def _set_rounding(self, type):
3848 """Sets the rounding type.
3849
3850 Sets the rounding type, and returns the current (previous)
3851 rounding type. Often used like:
3852
3853 context = context.copy()
3854 # so you don't change the calling context
3855 # if an error occurs in the middle.
3856 rounding = context._set_rounding(ROUND_UP)
3857 val = self.__sub__(other, context=context)
3858 context._set_rounding(rounding)
3859
3860 This will make it round up for that operation.
3861 """
3862 rounding = self.rounding
3863 self.rounding= type
3864 return rounding
3865
Raymond Hettingerfed52962004-07-14 15:41:57 +00003866 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00003867 """Creates a new Decimal instance but using self as context.
3868
3869 This method implements the to-number operation of the
3870 IBM Decimal specification."""
3871
3872 if isinstance(num, str) and num != num.strip():
3873 return self._raise_error(ConversionSyntax,
3874 "no trailing or leading whitespace is "
3875 "permitted.")
3876
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003877 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003878 if d._isnan() and len(d._int) > self.prec - self._clamp:
3879 return self._raise_error(ConversionSyntax,
3880 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003881 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003882
Raymond Hettinger771ed762009-01-03 19:20:32 +00003883 def create_decimal_from_float(self, f):
3884 """Creates a new Decimal instance from a float but rounding using self
3885 as the context.
3886
3887 >>> context = Context(prec=5, rounding=ROUND_DOWN)
3888 >>> context.create_decimal_from_float(3.1415926535897932)
3889 Decimal('3.1415')
3890 >>> context = Context(prec=5, traps=[Inexact])
3891 >>> context.create_decimal_from_float(3.1415926535897932)
3892 Traceback (most recent call last):
3893 ...
3894 decimal.Inexact: None
3895
3896 """
3897 d = Decimal.from_float(f) # An exact conversion
3898 return d._fix(self) # Apply the context rounding
3899
Guido van Rossumd8faa362007-04-27 19:54:29 +00003900 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003901 def abs(self, a):
3902 """Returns the absolute value of the operand.
3903
3904 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003905 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003906 the plus operation on the operand.
3907
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003908 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003909 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003910 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003911 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003912 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003913 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003914 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003915 Decimal('101.5')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003916 """
3917 return a.__abs__(context=self)
3918
3919 def add(self, a, b):
3920 """Return the sum of the two operands.
3921
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003922 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003923 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003924 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003925 Decimal('1.02E+4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003926 """
3927 return a.__add__(b, context=self)
3928
3929 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003930 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003931
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003932 def canonical(self, a):
3933 """Returns the same Decimal object.
3934
3935 As we do not have different encodings for the same number, the
3936 received object already is in its canonical form.
3937
3938 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003939 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003940 """
3941 return a.canonical(context=self)
3942
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003943 def compare(self, a, b):
3944 """Compares values numerically.
3945
3946 If the signs of the operands differ, a value representing each operand
3947 ('-1' if the operand is less than zero, '0' if the operand is zero or
3948 negative zero, or '1' if the operand is greater than zero) is used in
3949 place of that operand for the comparison instead of the actual
3950 operand.
3951
3952 The comparison is then effected by subtracting the second operand from
3953 the first and then returning a value according to the result of the
3954 subtraction: '-1' if the result is less than zero, '0' if the result is
3955 zero or negative zero, or '1' if the result is greater than zero.
3956
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003957 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003958 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003959 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003960 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003961 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003962 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003963 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003964 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003965 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003966 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003967 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003968 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003969 """
3970 return a.compare(b, context=self)
3971
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003972 def compare_signal(self, a, b):
3973 """Compares the values of the two operands numerically.
3974
3975 It's pretty much like compare(), but all NaNs signal, with signaling
3976 NaNs taking precedence over quiet NaNs.
3977
3978 >>> c = ExtendedContext
3979 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003980 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003981 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003982 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003983 >>> c.flags[InvalidOperation] = 0
3984 >>> print(c.flags[InvalidOperation])
3985 0
3986 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003987 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003988 >>> print(c.flags[InvalidOperation])
3989 1
3990 >>> c.flags[InvalidOperation] = 0
3991 >>> print(c.flags[InvalidOperation])
3992 0
3993 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003994 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003995 >>> print(c.flags[InvalidOperation])
3996 1
3997 """
3998 return a.compare_signal(b, context=self)
3999
4000 def compare_total(self, a, b):
4001 """Compares two operands using their abstract representation.
4002
4003 This is not like the standard compare, which use their numerical
4004 value. Note that a total ordering is defined for all possible abstract
4005 representations.
4006
4007 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004008 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004009 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004010 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004011 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004012 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004013 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004014 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004015 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004016 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004017 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004018 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004019 """
4020 return a.compare_total(b)
4021
4022 def compare_total_mag(self, a, b):
4023 """Compares two operands using their abstract representation ignoring sign.
4024
4025 Like compare_total, but with operand's sign ignored and assumed to be 0.
4026 """
4027 return a.compare_total_mag(b)
4028
4029 def copy_abs(self, a):
4030 """Returns a copy of the operand with the sign set to 0.
4031
4032 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004033 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004034 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004035 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004036 """
4037 return a.copy_abs()
4038
4039 def copy_decimal(self, a):
4040 """Returns a copy of the decimal objet.
4041
4042 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004043 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004044 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004045 Decimal('-1.00')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004046 """
4047 return Decimal(a)
4048
4049 def copy_negate(self, a):
4050 """Returns a copy of the operand with the sign inverted.
4051
4052 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004053 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004054 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004055 Decimal('101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004056 """
4057 return a.copy_negate()
4058
4059 def copy_sign(self, a, b):
4060 """Copies the second operand's sign to the first one.
4061
4062 In detail, it returns a copy of the first operand with the sign
4063 equal to the sign of the second operand.
4064
4065 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004066 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004067 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004068 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004069 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004070 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004071 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004072 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004073 """
4074 return a.copy_sign(b)
4075
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004076 def divide(self, a, b):
4077 """Decimal division in a specified context.
4078
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004079 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004080 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004081 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004082 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004083 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004084 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004085 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004086 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004087 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004088 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004089 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004090 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004091 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004092 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004093 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004094 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004095 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004096 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004097 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004098 Decimal('1.20E+6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004099 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00004100 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004101
4102 def divide_int(self, a, b):
4103 """Divides two numbers and returns the integer part of the result.
4104
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004105 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004106 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004107 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004108 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004109 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004110 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004111 """
4112 return a.__floordiv__(b, context=self)
4113
4114 def divmod(self, a, b):
4115 return a.__divmod__(b, context=self)
4116
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004117 def exp(self, a):
4118 """Returns e ** a.
4119
4120 >>> c = ExtendedContext.copy()
4121 >>> c.Emin = -999
4122 >>> c.Emax = 999
4123 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004124 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004125 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004126 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004127 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004128 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004129 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004130 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004131 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004132 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004133 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004134 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004135 """
4136 return a.exp(context=self)
4137
4138 def fma(self, a, b, c):
4139 """Returns a multiplied by b, plus c.
4140
4141 The first two operands are multiplied together, using multiply,
4142 the third operand is then added to the result of that
4143 multiplication, using add, all with only one final rounding.
4144
4145 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004146 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004147 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004148 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004149 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004150 Decimal('1.38435736E+12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004151 """
4152 return a.fma(b, c, context=self)
4153
4154 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004155 """Return True if the operand is canonical; otherwise return False.
4156
4157 Currently, the encoding of a Decimal instance is always
4158 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004159
4160 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004161 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004162 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004163 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004164
4165 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004166 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004167
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004168 A Decimal instance is considered finite if it is neither
4169 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004170
4171 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004172 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004173 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004174 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004175 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004176 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004177 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004178 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004179 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004180 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004181 """
4182 return a.is_finite()
4183
4184 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004185 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004186
4187 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004188 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004189 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004190 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004191 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004192 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004193 """
4194 return a.is_infinite()
4195
4196 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004197 """Return True if the operand is a qNaN or sNaN;
4198 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004199
4200 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004201 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004202 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004203 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004204 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004205 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004206 """
4207 return a.is_nan()
4208
4209 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004210 """Return True if the operand is a normal number;
4211 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004212
4213 >>> c = ExtendedContext.copy()
4214 >>> c.Emin = -999
4215 >>> c.Emax = 999
4216 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004217 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004218 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004219 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004220 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004221 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004222 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004223 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004224 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004225 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004226 """
4227 return a.is_normal(context=self)
4228
4229 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004230 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004231
4232 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004233 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004234 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004235 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004236 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004237 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004238 """
4239 return a.is_qnan()
4240
4241 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004242 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004243
4244 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004245 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004246 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004247 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004248 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004249 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004250 """
4251 return a.is_signed()
4252
4253 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004254 """Return True if the operand is a signaling NaN;
4255 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004256
4257 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004258 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004259 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004260 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004261 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004262 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004263 """
4264 return a.is_snan()
4265
4266 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004267 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004268
4269 >>> c = ExtendedContext.copy()
4270 >>> c.Emin = -999
4271 >>> c.Emax = 999
4272 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004273 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004274 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004275 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004276 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004277 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004278 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004279 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004280 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004281 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004282 """
4283 return a.is_subnormal(context=self)
4284
4285 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004286 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004287
4288 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004289 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004290 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004291 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004292 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004293 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004294 """
4295 return a.is_zero()
4296
4297 def ln(self, a):
4298 """Returns the natural (base e) logarithm of the operand.
4299
4300 >>> c = ExtendedContext.copy()
4301 >>> c.Emin = -999
4302 >>> c.Emax = 999
4303 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004304 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004305 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004306 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004307 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004308 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004309 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004310 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004311 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004312 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004313 """
4314 return a.ln(context=self)
4315
4316 def log10(self, a):
4317 """Returns the base 10 logarithm of the operand.
4318
4319 >>> c = ExtendedContext.copy()
4320 >>> c.Emin = -999
4321 >>> c.Emax = 999
4322 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004323 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004324 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004325 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004326 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004327 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004328 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004329 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004330 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004331 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004332 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004333 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004334 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004335 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004336 """
4337 return a.log10(context=self)
4338
4339 def logb(self, a):
4340 """ Returns the exponent of the magnitude of the operand's MSD.
4341
4342 The result is the integer which is the exponent of the magnitude
4343 of the most significant digit of the operand (as though the
4344 operand were truncated to a single digit while maintaining the
4345 value of that digit and without limiting the resulting exponent).
4346
4347 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004348 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004349 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004350 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004351 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004352 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004353 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004354 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004355 """
4356 return a.logb(context=self)
4357
4358 def logical_and(self, a, b):
4359 """Applies the logical operation 'and' between each operand's digits.
4360
4361 The operands must be both logical numbers.
4362
4363 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004364 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004365 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004366 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004367 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004368 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004369 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004370 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004371 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004372 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004373 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004374 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004375 """
4376 return a.logical_and(b, context=self)
4377
4378 def logical_invert(self, a):
4379 """Invert all the digits in the operand.
4380
4381 The operand must be a logical number.
4382
4383 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004384 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004385 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004386 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004387 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004388 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004389 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004390 Decimal('10101010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004391 """
4392 return a.logical_invert(context=self)
4393
4394 def logical_or(self, a, b):
4395 """Applies the logical operation 'or' between each operand's digits.
4396
4397 The operands must be both logical numbers.
4398
4399 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004400 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004401 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004402 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004403 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004404 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004405 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004406 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004407 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004408 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004409 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004410 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004411 """
4412 return a.logical_or(b, context=self)
4413
4414 def logical_xor(self, a, b):
4415 """Applies the logical operation 'xor' between each operand's digits.
4416
4417 The operands must be both logical numbers.
4418
4419 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004420 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004421 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004422 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004423 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004424 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004425 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004426 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004427 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004428 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004429 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004430 Decimal('1101')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004431 """
4432 return a.logical_xor(b, context=self)
4433
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004434 def max(self, a,b):
4435 """max compares two values numerically and returns the maximum.
4436
4437 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004438 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004439 operation. If they are numerically equal then the left-hand operand
4440 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004441 infinity) of the two operands is chosen as the result.
4442
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004443 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004444 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004445 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004446 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004447 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004448 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004449 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004450 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004451 """
4452 return a.max(b, context=self)
4453
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004454 def max_mag(self, a, b):
4455 """Compares the values numerically with their sign ignored."""
4456 return a.max_mag(b, context=self)
4457
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004458 def min(self, a,b):
4459 """min compares two values numerically and returns the minimum.
4460
4461 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004462 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004463 operation. If they are numerically equal then the left-hand operand
4464 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004465 infinity) of the two operands is chosen as the result.
4466
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004467 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004468 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004469 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004470 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004471 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004472 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004473 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004474 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004475 """
4476 return a.min(b, context=self)
4477
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004478 def min_mag(self, a, b):
4479 """Compares the values numerically with their sign ignored."""
4480 return a.min_mag(b, context=self)
4481
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004482 def minus(self, a):
4483 """Minus corresponds to unary prefix minus in Python.
4484
4485 The operation is evaluated using the same rules as subtract; the
4486 operation minus(a) is calculated as subtract('0', a) where the '0'
4487 has the same exponent as the operand.
4488
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004489 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004490 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004491 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004492 Decimal('1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004493 """
4494 return a.__neg__(context=self)
4495
4496 def multiply(self, a, b):
4497 """multiply multiplies two operands.
4498
4499 If either operand is a special value then the general rules apply.
4500 Otherwise, the operands are multiplied together ('long multiplication'),
4501 resulting in a number which may be as long as the sum of the lengths
4502 of the two operands.
4503
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004504 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004505 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004506 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004507 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004508 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004509 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004510 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004511 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004512 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004513 Decimal('4.28135971E+11')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004514 """
4515 return a.__mul__(b, context=self)
4516
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004517 def next_minus(self, a):
4518 """Returns the largest representable number smaller than a.
4519
4520 >>> c = ExtendedContext.copy()
4521 >>> c.Emin = -999
4522 >>> c.Emax = 999
4523 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004524 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004525 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004526 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004527 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004528 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004529 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004530 Decimal('9.99999999E+999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004531 """
4532 return a.next_minus(context=self)
4533
4534 def next_plus(self, a):
4535 """Returns the smallest representable number larger than a.
4536
4537 >>> c = ExtendedContext.copy()
4538 >>> c.Emin = -999
4539 >>> c.Emax = 999
4540 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004541 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004542 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004543 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004544 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004545 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004546 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004547 Decimal('-9.99999999E+999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004548 """
4549 return a.next_plus(context=self)
4550
4551 def next_toward(self, a, b):
4552 """Returns the number closest to a, in direction towards b.
4553
4554 The result is the closest representable number from the first
4555 operand (but not the first operand) that is in the direction
4556 towards the second operand, unless the operands have the same
4557 value.
4558
4559 >>> c = ExtendedContext.copy()
4560 >>> c.Emin = -999
4561 >>> c.Emax = 999
4562 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004563 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004564 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004565 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004566 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004567 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004568 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004569 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004570 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004571 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004572 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004573 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004574 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004575 Decimal('-0.00')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004576 """
4577 return a.next_toward(b, context=self)
4578
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004579 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004580 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004581
4582 Essentially a plus operation with all trailing zeros removed from the
4583 result.
4584
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004585 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004586 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004587 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004588 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004589 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004590 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004591 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004592 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004593 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004594 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004595 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004596 Decimal('0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004597 """
4598 return a.normalize(context=self)
4599
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004600 def number_class(self, a):
4601 """Returns an indication of the class of the operand.
4602
4603 The class is one of the following strings:
4604 -sNaN
4605 -NaN
4606 -Infinity
4607 -Normal
4608 -Subnormal
4609 -Zero
4610 +Zero
4611 +Subnormal
4612 +Normal
4613 +Infinity
4614
4615 >>> c = Context(ExtendedContext)
4616 >>> c.Emin = -999
4617 >>> c.Emax = 999
4618 >>> c.number_class(Decimal('Infinity'))
4619 '+Infinity'
4620 >>> c.number_class(Decimal('1E-10'))
4621 '+Normal'
4622 >>> c.number_class(Decimal('2.50'))
4623 '+Normal'
4624 >>> c.number_class(Decimal('0.1E-999'))
4625 '+Subnormal'
4626 >>> c.number_class(Decimal('0'))
4627 '+Zero'
4628 >>> c.number_class(Decimal('-0'))
4629 '-Zero'
4630 >>> c.number_class(Decimal('-0.1E-999'))
4631 '-Subnormal'
4632 >>> c.number_class(Decimal('-1E-10'))
4633 '-Normal'
4634 >>> c.number_class(Decimal('-2.50'))
4635 '-Normal'
4636 >>> c.number_class(Decimal('-Infinity'))
4637 '-Infinity'
4638 >>> c.number_class(Decimal('NaN'))
4639 'NaN'
4640 >>> c.number_class(Decimal('-NaN'))
4641 'NaN'
4642 >>> c.number_class(Decimal('sNaN'))
4643 'sNaN'
4644 """
4645 return a.number_class(context=self)
4646
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004647 def plus(self, a):
4648 """Plus corresponds to unary prefix plus in Python.
4649
4650 The operation is evaluated using the same rules as add; the
4651 operation plus(a) is calculated as add('0', a) where the '0'
4652 has the same exponent as the operand.
4653
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004654 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004655 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004656 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004657 Decimal('-1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004658 """
4659 return a.__pos__(context=self)
4660
4661 def power(self, a, b, modulo=None):
4662 """Raises a to the power of b, to modulo if given.
4663
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004664 With two arguments, compute a**b. If a is negative then b
4665 must be integral. The result will be inexact unless b is
4666 integral and the result is finite and can be expressed exactly
4667 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004668
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004669 With three arguments, compute (a**b) % modulo. For the
4670 three argument form, the following restrictions on the
4671 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004672
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004673 - all three arguments must be integral
4674 - b must be nonnegative
4675 - at least one of a or b must be nonzero
4676 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004677
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004678 The result of pow(a, b, modulo) is identical to the result
4679 that would be obtained by computing (a**b) % modulo with
4680 unbounded precision, but is computed more efficiently. It is
4681 always exact.
4682
4683 >>> c = ExtendedContext.copy()
4684 >>> c.Emin = -999
4685 >>> c.Emax = 999
4686 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004687 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004688 >>> c.power(Decimal('-2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004689 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004690 >>> c.power(Decimal('2'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004691 Decimal('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004692 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004693 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004694 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004695 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004696 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004697 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004698 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004699 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004700 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004701 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004702 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004703 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004704 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004705 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004706 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004707 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004708 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004709 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004710 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004711 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004712
4713 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004714 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004715 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004716 Decimal('-11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004717 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004718 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004719 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004720 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004721 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004722 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004723 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004724 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004725 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004726 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004727 """
4728 return a.__pow__(b, modulo, context=self)
4729
4730 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004731 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004732
4733 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004734 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004735 exponent is being increased), multiplied by a positive power of ten (if
4736 the exponent is being decreased), or is unchanged (if the exponent is
4737 already equal to that of the right-hand operand).
4738
4739 Unlike other operations, if the length of the coefficient after the
4740 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004741 operation condition is raised. This guarantees that, unless there is
4742 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004743 equal to that of the right-hand operand.
4744
4745 Also unlike other operations, quantize will never raise Underflow, even
4746 if the result is subnormal and inexact.
4747
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004748 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004749 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004750 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004751 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004752 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004753 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004754 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004755 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004756 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004757 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004758 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004759 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004760 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004761 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004762 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004763 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004764 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004765 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004766 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004767 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004768 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004769 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004770 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004771 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004772 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004773 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004774 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004775 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004776 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004777 Decimal('2E+2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004778 """
4779 return a.quantize(b, context=self)
4780
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004781 def radix(self):
4782 """Just returns 10, as this is Decimal, :)
4783
4784 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004785 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004786 """
4787 return Decimal(10)
4788
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004789 def remainder(self, a, b):
4790 """Returns the remainder from integer division.
4791
4792 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004793 calculating integer division as described for divide-integer, rounded
4794 to precision digits if necessary. The sign of the result, if
4795 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004796
4797 This operation will fail under the same conditions as integer division
4798 (that is, if integer division on the same two operands would fail, the
4799 remainder cannot be calculated).
4800
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004801 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004802 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004803 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004804 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004805 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004806 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004807 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004808 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004809 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004810 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004811 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004812 Decimal('1.0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004813 """
4814 return a.__mod__(b, context=self)
4815
4816 def remainder_near(self, a, b):
4817 """Returns to be "a - b * n", where n is the integer nearest the exact
4818 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004819 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004820 sign of a.
4821
4822 This operation will fail under the same conditions as integer division
4823 (that is, if integer division on the same two operands would fail, the
4824 remainder cannot be calculated).
4825
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004826 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004827 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004828 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004829 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004830 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004831 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004832 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004833 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004834 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004835 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004836 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004837 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004838 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004839 Decimal('-0.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004840 """
4841 return a.remainder_near(b, context=self)
4842
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004843 def rotate(self, a, b):
4844 """Returns a rotated copy of a, b times.
4845
4846 The coefficient of the result is a rotated copy of the digits in
4847 the coefficient of the first operand. The number of places of
4848 rotation is taken from the absolute value of the second operand,
4849 with the rotation being to the left if the second operand is
4850 positive or to the right otherwise.
4851
4852 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004853 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004854 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004855 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004856 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004857 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004858 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004859 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004860 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004861 Decimal('345678912')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004862 """
4863 return a.rotate(b, context=self)
4864
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004865 def same_quantum(self, a, b):
4866 """Returns True if the two operands have the same exponent.
4867
4868 The result is never affected by either the sign or the coefficient of
4869 either operand.
4870
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004871 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004872 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004873 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004874 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004875 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004876 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004877 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004878 True
4879 """
4880 return a.same_quantum(b)
4881
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004882 def scaleb (self, a, b):
4883 """Returns the first operand after adding the second value its exp.
4884
4885 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004886 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004887 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004888 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004889 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004890 Decimal('7.50E+3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004891 """
4892 return a.scaleb (b, context=self)
4893
4894 def shift(self, a, b):
4895 """Returns a shifted copy of a, b times.
4896
4897 The coefficient of the result is a shifted copy of the digits
4898 in the coefficient of the first operand. The number of places
4899 to shift is taken from the absolute value of the second operand,
4900 with the shift being to the left if the second operand is
4901 positive or to the right otherwise. Digits shifted into the
4902 coefficient are zeros.
4903
4904 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004905 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004906 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004907 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004908 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004909 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004910 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004911 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004912 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004913 Decimal('345678900')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004914 """
4915 return a.shift(b, context=self)
4916
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004917 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004918 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004919
4920 If the result must be inexact, it is rounded using the round-half-even
4921 algorithm.
4922
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004923 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004924 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004925 >>> ExtendedContext.sqrt(Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004926 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004927 >>> ExtendedContext.sqrt(Decimal('0.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004928 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004929 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004930 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004931 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004932 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004933 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004934 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004935 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004936 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004937 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004938 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004939 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004940 Decimal('3.16227766')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004941 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004942 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004943 """
4944 return a.sqrt(context=self)
4945
4946 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004947 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004948
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004949 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004950 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004951 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004952 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004953 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004954 Decimal('-0.77')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004955 """
4956 return a.__sub__(b, context=self)
4957
4958 def to_eng_string(self, a):
4959 """Converts a number to a string, using scientific notation.
4960
4961 The operation is not affected by the context.
4962 """
4963 return a.to_eng_string(context=self)
4964
4965 def to_sci_string(self, a):
4966 """Converts a number to a string, using scientific notation.
4967
4968 The operation is not affected by the context.
4969 """
4970 return a.__str__(context=self)
4971
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004972 def to_integral_exact(self, a):
4973 """Rounds to an integer.
4974
4975 When the operand has a negative exponent, the result is the same
4976 as using the quantize() operation using the given operand as the
4977 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4978 of the operand as the precision setting; Inexact and Rounded flags
4979 are allowed in this operation. The rounding mode is taken from the
4980 context.
4981
4982 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004983 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004984 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004985 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004986 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004987 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004988 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004989 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004990 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004991 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004992 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004993 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004994 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004995 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004996 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004997 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004998 """
4999 return a.to_integral_exact(context=self)
5000
5001 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005002 """Rounds to an integer.
5003
5004 When the operand has a negative exponent, the result is the same
5005 as using the quantize() operation using the given operand as the
5006 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5007 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00005008 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005009
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005010 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005011 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005012 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005013 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005014 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005015 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005016 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005017 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005018 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005019 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005020 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005021 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005022 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005023 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005024 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005025 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005026 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005027 return a.to_integral_value(context=self)
5028
5029 # the method name changed, but we provide also the old one, for compatibility
5030 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005031
5032class _WorkRep(object):
5033 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005034 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005035 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005036 # exp: None, int, or string
5037
5038 def __init__(self, value=None):
5039 if value is None:
5040 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005041 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005042 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005043 elif isinstance(value, Decimal):
5044 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005045 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005046 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005047 else:
5048 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005049 self.sign = value[0]
5050 self.int = value[1]
5051 self.exp = value[2]
5052
5053 def __repr__(self):
5054 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5055
5056 __str__ = __repr__
5057
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005058
5059
Christian Heimes2c181612007-12-17 20:04:13 +00005060def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005061 """Normalizes op1, op2 to have the same exp and length of coefficient.
5062
5063 Done during addition.
5064 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005065 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005066 tmp = op2
5067 other = op1
5068 else:
5069 tmp = op1
5070 other = op2
5071
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005072 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5073 # Then adding 10**exp to tmp has the same effect (after rounding)
5074 # as adding any positive quantity smaller than 10**exp; similarly
5075 # for subtraction. So if other is smaller than 10**exp we replace
5076 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00005077 tmp_len = len(str(tmp.int))
5078 other_len = len(str(other.int))
5079 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5080 if other_len + other.exp - 1 < exp:
5081 other.int = 1
5082 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005083
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005084 tmp.int *= 10 ** (tmp.exp - other.exp)
5085 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005086 return op1, op2
5087
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005088##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005089
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005090# This function from Tim Peters was taken from here:
5091# http://mail.python.org/pipermail/python-list/1999-July/007758.html
5092# The correction being in the function definition is for speed, and
5093# the whole function is not resolved with math.log because of avoiding
5094# the use of floats.
5095def _nbits(n, correction = {
5096 '0': 4, '1': 3, '2': 2, '3': 2,
5097 '4': 1, '5': 1, '6': 1, '7': 1,
5098 '8': 0, '9': 0, 'a': 0, 'b': 0,
5099 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
5100 """Number of bits in binary representation of the positive integer n,
5101 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005102 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005103 if n < 0:
5104 raise ValueError("The argument to _nbits should be nonnegative.")
5105 hex_n = "%x" % n
5106 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005107
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005108def _sqrt_nearest(n, a):
5109 """Closest integer to the square root of the positive integer n. a is
5110 an initial approximation to the square root. Any positive integer
5111 will do for a, but the closer a is to the square root of n the
5112 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005113
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005114 """
5115 if n <= 0 or a <= 0:
5116 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5117
5118 b=0
5119 while a != b:
5120 b, a = a, a--n//a>>1
5121 return a
5122
5123def _rshift_nearest(x, shift):
5124 """Given an integer x and a nonnegative integer shift, return closest
5125 integer to x / 2**shift; use round-to-even in case of a tie.
5126
5127 """
5128 b, q = 1 << shift, x >> shift
5129 return q + (2*(x & (b-1)) + (q&1) > b)
5130
5131def _div_nearest(a, b):
5132 """Closest integer to a/b, a and b positive integers; rounds to even
5133 in the case of a tie.
5134
5135 """
5136 q, r = divmod(a, b)
5137 return q + (2*r + (q&1) > b)
5138
5139def _ilog(x, M, L = 8):
5140 """Integer approximation to M*log(x/M), with absolute error boundable
5141 in terms only of x/M.
5142
5143 Given positive integers x and M, return an integer approximation to
5144 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5145 between the approximation and the exact result is at most 22. For
5146 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5147 both cases these are upper bounds on the error; it will usually be
5148 much smaller."""
5149
5150 # The basic algorithm is the following: let log1p be the function
5151 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5152 # the reduction
5153 #
5154 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5155 #
5156 # repeatedly until the argument to log1p is small (< 2**-L in
5157 # absolute value). For small y we can use the Taylor series
5158 # expansion
5159 #
5160 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5161 #
5162 # truncating at T such that y**T is small enough. The whole
5163 # computation is carried out in a form of fixed-point arithmetic,
5164 # with a real number z being represented by an integer
5165 # approximation to z*M. To avoid loss of precision, the y below
5166 # is actually an integer approximation to 2**R*y*M, where R is the
5167 # number of reductions performed so far.
5168
5169 y = x-M
5170 # argument reduction; R = number of reductions performed
5171 R = 0
5172 while (R <= L and abs(y) << L-R >= M or
5173 R > L and abs(y) >> R-L >= M):
5174 y = _div_nearest((M*y) << 1,
5175 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5176 R += 1
5177
5178 # Taylor series with T terms
5179 T = -int(-10*len(str(M))//(3*L))
5180 yshift = _rshift_nearest(y, R)
5181 w = _div_nearest(M, T)
5182 for k in range(T-1, 0, -1):
5183 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5184
5185 return _div_nearest(w*y, M)
5186
5187def _dlog10(c, e, p):
5188 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5189 approximation to 10**p * log10(c*10**e), with an absolute error of
5190 at most 1. Assumes that c*10**e is not exactly 1."""
5191
5192 # increase precision by 2; compensate for this by dividing
5193 # final result by 100
5194 p += 2
5195
5196 # write c*10**e as d*10**f with either:
5197 # f >= 0 and 1 <= d <= 10, or
5198 # f <= 0 and 0.1 <= d <= 1.
5199 # Thus for c*10**e close to 1, f = 0
5200 l = len(str(c))
5201 f = e+l - (e+l >= 1)
5202
5203 if p > 0:
5204 M = 10**p
5205 k = e+p-f
5206 if k >= 0:
5207 c *= 10**k
5208 else:
5209 c = _div_nearest(c, 10**-k)
5210
5211 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005212 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005213 log_d = _div_nearest(log_d*M, log_10)
5214 log_tenpower = f*M # exact
5215 else:
5216 log_d = 0 # error < 2.31
Neal Norwitz2f99b242008-08-24 05:48:10 +00005217 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005218
5219 return _div_nearest(log_tenpower+log_d, 100)
5220
5221def _dlog(c, e, p):
5222 """Given integers c, e and p with c > 0, compute an integer
5223 approximation to 10**p * log(c*10**e), with an absolute error of
5224 at most 1. Assumes that c*10**e is not exactly 1."""
5225
5226 # Increase precision by 2. The precision increase is compensated
5227 # for at the end with a division by 100.
5228 p += 2
5229
5230 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5231 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5232 # as 10**p * log(d) + 10**p*f * log(10).
5233 l = len(str(c))
5234 f = e+l - (e+l >= 1)
5235
5236 # compute approximation to 10**p*log(d), with error < 27
5237 if p > 0:
5238 k = e+p-f
5239 if k >= 0:
5240 c *= 10**k
5241 else:
5242 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5243
5244 # _ilog magnifies existing error in c by a factor of at most 10
5245 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5246 else:
5247 # p <= 0: just approximate the whole thing by 0; error < 2.31
5248 log_d = 0
5249
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005250 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005251 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005252 extra = len(str(abs(f)))-1
5253 if p + extra >= 0:
5254 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5255 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5256 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005257 else:
5258 f_log_ten = 0
5259 else:
5260 f_log_ten = 0
5261
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005262 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005263 return _div_nearest(f_log_ten + log_d, 100)
5264
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005265class _Log10Memoize(object):
5266 """Class to compute, store, and allow retrieval of, digits of the
5267 constant log(10) = 2.302585.... This constant is needed by
5268 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5269 def __init__(self):
5270 self.digits = "23025850929940456840179914546843642076011014886"
5271
5272 def getdigits(self, p):
5273 """Given an integer p >= 0, return floor(10**p)*log(10).
5274
5275 For example, self.getdigits(3) returns 2302.
5276 """
5277 # digits are stored as a string, for quick conversion to
5278 # integer in the case that we've already computed enough
5279 # digits; the stored digits should always be correct
5280 # (truncated, not rounded to nearest).
5281 if p < 0:
5282 raise ValueError("p should be nonnegative")
5283
5284 if p >= len(self.digits):
5285 # compute p+3, p+6, p+9, ... digits; continue until at
5286 # least one of the extra digits is nonzero
5287 extra = 3
5288 while True:
5289 # compute p+extra digits, correct to within 1ulp
5290 M = 10**(p+extra+2)
5291 digits = str(_div_nearest(_ilog(10*M, M), 100))
5292 if digits[-extra:] != '0'*extra:
5293 break
5294 extra += 3
5295 # keep all reliable digits so far; remove trailing zeros
5296 # and next nonzero digit
5297 self.digits = digits.rstrip('0')[:-1]
5298 return int(self.digits[:p+1])
5299
5300_log10_digits = _Log10Memoize().getdigits
5301
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005302def _iexp(x, M, L=8):
5303 """Given integers x and M, M > 0, such that x/M is small in absolute
5304 value, compute an integer approximation to M*exp(x/M). For 0 <=
5305 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5306 is usually much smaller)."""
5307
5308 # Algorithm: to compute exp(z) for a real number z, first divide z
5309 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5310 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5311 # series
5312 #
5313 # expm1(x) = x + x**2/2! + x**3/3! + ...
5314 #
5315 # Now use the identity
5316 #
5317 # expm1(2x) = expm1(x)*(expm1(x)+2)
5318 #
5319 # R times to compute the sequence expm1(z/2**R),
5320 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5321
5322 # Find R such that x/2**R/M <= 2**-L
5323 R = _nbits((x<<L)//M)
5324
5325 # Taylor series. (2**L)**T > M
5326 T = -int(-10*len(str(M))//(3*L))
5327 y = _div_nearest(x, T)
5328 Mshift = M<<R
5329 for i in range(T-1, 0, -1):
5330 y = _div_nearest(x*(Mshift + y), Mshift * i)
5331
5332 # Expansion
5333 for k in range(R-1, -1, -1):
5334 Mshift = M<<(k+2)
5335 y = _div_nearest(y*(y+Mshift), Mshift)
5336
5337 return M+y
5338
5339def _dexp(c, e, p):
5340 """Compute an approximation to exp(c*10**e), with p decimal places of
5341 precision.
5342
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005343 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005344
5345 10**(p-1) <= d <= 10**p, and
5346 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5347
5348 In other words, d*10**f is an approximation to exp(c*10**e) with p
5349 digits of precision, and with an error in d of at most 1. This is
5350 almost, but not quite, the same as the error being < 1ulp: when d
5351 = 10**(p-1) the error could be up to 10 ulp."""
5352
5353 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5354 p += 2
5355
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005356 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005357 extra = max(0, e + len(str(c)) - 1)
5358 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005359
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005360 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005361 # rounding down
5362 shift = e+q
5363 if shift >= 0:
5364 cshift = c*10**shift
5365 else:
5366 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005367 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005368
5369 # reduce remainder back to original precision
5370 rem = _div_nearest(rem, 10**extra)
5371
5372 # error in result of _iexp < 120; error after division < 0.62
5373 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5374
5375def _dpower(xc, xe, yc, ye, p):
5376 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5377 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5378
5379 10**(p-1) <= c <= 10**p, and
5380 (c-1)*10**e < x**y < (c+1)*10**e
5381
5382 in other words, c*10**e is an approximation to x**y with p digits
5383 of precision, and with an error in c of at most 1. (This is
5384 almost, but not quite, the same as the error being < 1ulp: when c
5385 == 10**(p-1) we can only guarantee error < 10ulp.)
5386
5387 We assume that: x is positive and not equal to 1, and y is nonzero.
5388 """
5389
5390 # Find b such that 10**(b-1) <= |y| <= 10**b
5391 b = len(str(abs(yc))) + ye
5392
5393 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5394 lxc = _dlog(xc, xe, p+b+1)
5395
5396 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5397 shift = ye-b
5398 if shift >= 0:
5399 pc = lxc*yc*10**shift
5400 else:
5401 pc = _div_nearest(lxc*yc, 10**-shift)
5402
5403 if pc == 0:
5404 # we prefer a result that isn't exactly 1; this makes it
5405 # easier to compute a correctly rounded result in __pow__
5406 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5407 coeff, exp = 10**(p-1)+1, 1-p
5408 else:
5409 coeff, exp = 10**p-1, -p
5410 else:
5411 coeff, exp = _dexp(pc, -(p+1), p+1)
5412 coeff = _div_nearest(coeff, 10)
5413 exp += 1
5414
5415 return coeff, exp
5416
5417def _log10_lb(c, correction = {
5418 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5419 '6': 23, '7': 16, '8': 10, '9': 5}):
5420 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5421 if c <= 0:
5422 raise ValueError("The argument to _log10_lb should be nonnegative.")
5423 str_c = str(c)
5424 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005425
Guido van Rossumd8faa362007-04-27 19:54:29 +00005426##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005427
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005428def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005429 """Convert other to Decimal.
5430
5431 Verifies that it's ok to use in an implicit construction.
5432 """
5433 if isinstance(other, Decimal):
5434 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005435 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005436 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005437 if raiseit:
5438 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005439 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005440
Guido van Rossumd8faa362007-04-27 19:54:29 +00005441##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005442
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005443# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005444# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005445
5446DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005447 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005448 traps=[DivisionByZero, Overflow, InvalidOperation],
5449 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005450 Emax=999999999,
5451 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005452 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005453)
5454
5455# Pre-made alternate contexts offered by the specification
5456# Don't change these; the user should be able to select these
5457# contexts and be able to reproduce results from other implementations
5458# of the spec.
5459
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005460BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005461 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005462 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5463 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005464)
5465
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005466ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005467 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005468 traps=[],
5469 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005470)
5471
5472
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005473##### crud for parsing strings #############################################
Christian Heimes23daade02008-02-25 12:39:23 +00005474#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005475# Regular expression used for parsing numeric strings. Additional
5476# comments:
5477#
5478# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5479# whitespace. But note that the specification disallows whitespace in
5480# a numeric string.
5481#
5482# 2. For finite numbers (not infinities and NaNs) the body of the
5483# number between the optional sign and the optional exponent must have
5484# at least one decimal digit, possibly after the decimal point. The
Antoine Pitroufd036452008-08-19 17:56:33 +00005485# lookahead expression '(?=[0-9]|\.[0-9])' checks this.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005486#
5487# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5488# other meaning for \d than the numbers [0-9].
5489
5490import re
Benjamin Peterson41181742008-07-02 20:22:54 +00005491_parser = re.compile(r""" # A numeric string consists of:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005492# \s*
Benjamin Peterson41181742008-07-02 20:22:54 +00005493 (?P<sign>[-+])? # an optional sign, followed by either...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005494 (
Benjamin Peterson41181742008-07-02 20:22:54 +00005495 (?=[0-9]|\.[0-9]) # ...a number (with at least one digit)
5496 (?P<int>[0-9]*) # having a (possibly empty) integer part
5497 (\.(?P<frac>[0-9]*))? # followed by an optional fractional part
5498 (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005499 |
Benjamin Peterson41181742008-07-02 20:22:54 +00005500 Inf(inity)? # ...an infinity, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005501 |
Benjamin Peterson41181742008-07-02 20:22:54 +00005502 (?P<signal>s)? # ...an (optionally signaling)
5503 NaN # NaN
5504 (?P<diag>[0-9]*) # with (possibly empty) diagnostic info.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005505 )
5506# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00005507 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005508""", re.VERBOSE | re.IGNORECASE).match
5509
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005510_all_zeros = re.compile('0*$').match
5511_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00005512
5513##### PEP3101 support functions ##############################################
Mark Dickinson79f52032009-03-17 23:12:51 +00005514# The functions in this section have little to do with the Decimal
5515# class, and could potentially be reused or adapted for other pure
Christian Heimesf16baeb2008-02-29 14:57:44 +00005516# Python numeric classes that want to implement __format__
5517#
5518# A format specifier for Decimal looks like:
5519#
Mark Dickinson79f52032009-03-17 23:12:51 +00005520# [[fill]align][sign][0][minimumwidth][,][.precision][type]
Christian Heimesf16baeb2008-02-29 14:57:44 +00005521
5522_parse_format_specifier_regex = re.compile(r"""\A
5523(?:
5524 (?P<fill>.)?
5525 (?P<align>[<>=^])
5526)?
5527(?P<sign>[-+ ])?
5528(?P<zeropad>0)?
5529(?P<minimumwidth>(?!0)\d+)?
Mark Dickinson79f52032009-03-17 23:12:51 +00005530(?P<thousands_sep>,)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00005531(?:\.(?P<precision>0|(?!0)\d+))?
Mark Dickinson79f52032009-03-17 23:12:51 +00005532(?P<type>[eEfFgGn%])?
Christian Heimesf16baeb2008-02-29 14:57:44 +00005533\Z
5534""", re.VERBOSE)
5535
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005536del re
5537
Mark Dickinson79f52032009-03-17 23:12:51 +00005538# The locale module is only needed for the 'n' format specifier. The
5539# rest of the PEP 3101 code functions quite happily without it, so we
5540# don't care too much if locale isn't present.
5541try:
5542 import locale as _locale
5543except ImportError:
5544 pass
5545
5546def _parse_format_specifier(format_spec, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00005547 """Parse and validate a format specifier.
5548
5549 Turns a standard numeric format specifier into a dict, with the
5550 following entries:
5551
5552 fill: fill character to pad field to minimum width
5553 align: alignment type, either '<', '>', '=' or '^'
5554 sign: either '+', '-' or ' '
5555 minimumwidth: nonnegative integer giving minimum width
Mark Dickinson79f52032009-03-17 23:12:51 +00005556 zeropad: boolean, indicating whether to pad with zeros
5557 thousands_sep: string to use as thousands separator, or ''
5558 grouping: grouping for thousands separators, in format
5559 used by localeconv
5560 decimal_point: string to use for decimal point
Christian Heimesf16baeb2008-02-29 14:57:44 +00005561 precision: nonnegative integer giving precision, or None
5562 type: one of the characters 'eEfFgG%', or None
Christian Heimesf16baeb2008-02-29 14:57:44 +00005563
5564 """
5565 m = _parse_format_specifier_regex.match(format_spec)
5566 if m is None:
5567 raise ValueError("Invalid format specifier: " + format_spec)
5568
5569 # get the dictionary
5570 format_dict = m.groupdict()
5571
Mark Dickinson79f52032009-03-17 23:12:51 +00005572 # zeropad; defaults for fill and alignment. If zero padding
5573 # is requested, the fill and align fields should be absent.
Christian Heimesf16baeb2008-02-29 14:57:44 +00005574 fill = format_dict['fill']
5575 align = format_dict['align']
Mark Dickinson79f52032009-03-17 23:12:51 +00005576 format_dict['zeropad'] = (format_dict['zeropad'] is not None)
5577 if format_dict['zeropad']:
5578 if fill is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00005579 raise ValueError("Fill character conflicts with '0'"
5580 " in format specifier: " + format_spec)
Mark Dickinson79f52032009-03-17 23:12:51 +00005581 if align is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00005582 raise ValueError("Alignment conflicts with '0' in "
5583 "format specifier: " + format_spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00005584 format_dict['fill'] = fill or ' '
5585 format_dict['align'] = align or '<'
5586
Mark Dickinson79f52032009-03-17 23:12:51 +00005587 # default sign handling: '-' for negative, '' for positive
Christian Heimesf16baeb2008-02-29 14:57:44 +00005588 if format_dict['sign'] is None:
5589 format_dict['sign'] = '-'
5590
Christian Heimesf16baeb2008-02-29 14:57:44 +00005591 # minimumwidth defaults to 0; precision remains None if not given
5592 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5593 if format_dict['precision'] is not None:
5594 format_dict['precision'] = int(format_dict['precision'])
5595
5596 # if format type is 'g' or 'G' then a precision of 0 makes little
5597 # sense; convert it to 1. Same if format type is unspecified.
5598 if format_dict['precision'] == 0:
5599 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5600 format_dict['precision'] = 1
5601
Mark Dickinson79f52032009-03-17 23:12:51 +00005602 # determine thousands separator, grouping, and decimal separator, and
5603 # add appropriate entries to format_dict
5604 if format_dict['type'] == 'n':
5605 # apart from separators, 'n' behaves just like 'g'
5606 format_dict['type'] = 'g'
5607 if _localeconv is None:
5608 _localeconv = _locale.localeconv()
5609 if format_dict['thousands_sep'] is not None:
5610 raise ValueError("Explicit thousands separator conflicts with "
5611 "'n' type in format specifier: " + format_spec)
5612 format_dict['thousands_sep'] = _localeconv['thousands_sep']
5613 format_dict['grouping'] = _localeconv['grouping']
5614 format_dict['decimal_point'] = _localeconv['decimal_point']
5615 else:
5616 if format_dict['thousands_sep'] is None:
5617 format_dict['thousands_sep'] = ''
5618 format_dict['grouping'] = [3, 0]
5619 format_dict['decimal_point'] = '.'
Christian Heimesf16baeb2008-02-29 14:57:44 +00005620
5621 return format_dict
5622
Mark Dickinson79f52032009-03-17 23:12:51 +00005623def _format_align(sign, body, spec):
5624 """Given an unpadded, non-aligned numeric string 'body' and sign
5625 string 'sign', add padding and aligment conforming to the given
5626 format specifier dictionary 'spec' (as produced by
5627 parse_format_specifier).
Christian Heimesf16baeb2008-02-29 14:57:44 +00005628
5629 """
Christian Heimesf16baeb2008-02-29 14:57:44 +00005630 # how much extra space do we have to play with?
Mark Dickinson79f52032009-03-17 23:12:51 +00005631 minimumwidth = spec['minimumwidth']
5632 fill = spec['fill']
5633 padding = fill*(minimumwidth - len(sign) - len(body))
Christian Heimesf16baeb2008-02-29 14:57:44 +00005634
Mark Dickinson79f52032009-03-17 23:12:51 +00005635 align = spec['align']
Christian Heimesf16baeb2008-02-29 14:57:44 +00005636 if align == '<':
Christian Heimesf16baeb2008-02-29 14:57:44 +00005637 result = sign + body + padding
Mark Dickinsonad416342009-03-17 18:10:15 +00005638 elif align == '>':
5639 result = padding + sign + body
Christian Heimesf16baeb2008-02-29 14:57:44 +00005640 elif align == '=':
5641 result = sign + padding + body
Mark Dickinson79f52032009-03-17 23:12:51 +00005642 elif align == '^':
Christian Heimesf16baeb2008-02-29 14:57:44 +00005643 half = len(padding)//2
5644 result = padding[:half] + sign + body + padding[half:]
Mark Dickinson79f52032009-03-17 23:12:51 +00005645 else:
5646 raise ValueError('Unrecognised alignment field')
Christian Heimesf16baeb2008-02-29 14:57:44 +00005647
Christian Heimesf16baeb2008-02-29 14:57:44 +00005648 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005649
Mark Dickinson79f52032009-03-17 23:12:51 +00005650def _group_lengths(grouping):
5651 """Convert a localeconv-style grouping into a (possibly infinite)
5652 iterable of integers representing group lengths.
5653
5654 """
5655 # The result from localeconv()['grouping'], and the input to this
5656 # function, should be a list of integers in one of the
5657 # following three forms:
5658 #
5659 # (1) an empty list, or
5660 # (2) nonempty list of positive integers + [0]
5661 # (3) list of positive integers + [locale.CHAR_MAX], or
5662
5663 from itertools import chain, repeat
5664 if not grouping:
5665 return []
5666 elif grouping[-1] == 0 and len(grouping) >= 2:
5667 return chain(grouping[:-1], repeat(grouping[-2]))
5668 elif grouping[-1] == _locale.CHAR_MAX:
5669 return grouping[:-1]
5670 else:
5671 raise ValueError('unrecognised format for grouping')
5672
5673def _insert_thousands_sep(digits, spec, min_width=1):
5674 """Insert thousands separators into a digit string.
5675
5676 spec is a dictionary whose keys should include 'thousands_sep' and
5677 'grouping'; typically it's the result of parsing the format
5678 specifier using _parse_format_specifier.
5679
5680 The min_width keyword argument gives the minimum length of the
5681 result, which will be padded on the left with zeros if necessary.
5682
5683 If necessary, the zero padding adds an extra '0' on the left to
5684 avoid a leading thousands separator. For example, inserting
5685 commas every three digits in '123456', with min_width=8, gives
5686 '0,123,456', even though that has length 9.
5687
5688 """
5689
5690 sep = spec['thousands_sep']
5691 grouping = spec['grouping']
5692
5693 groups = []
5694 for l in _group_lengths(grouping):
Mark Dickinson79f52032009-03-17 23:12:51 +00005695 if l <= 0:
5696 raise ValueError("group length should be positive")
5697 # max(..., 1) forces at least 1 digit to the left of a separator
5698 l = min(max(len(digits), min_width, 1), l)
5699 groups.append('0'*(l - len(digits)) + digits[-l:])
5700 digits = digits[:-l]
5701 min_width -= l
5702 if not digits and min_width <= 0:
5703 break
Mark Dickinson7303b592009-03-18 08:25:36 +00005704 min_width -= len(sep)
Mark Dickinson79f52032009-03-17 23:12:51 +00005705 else:
5706 l = max(len(digits), min_width, 1)
5707 groups.append('0'*(l - len(digits)) + digits[-l:])
5708 return sep.join(reversed(groups))
5709
5710def _format_sign(is_negative, spec):
5711 """Determine sign character."""
5712
5713 if is_negative:
5714 return '-'
5715 elif spec['sign'] in ' +':
5716 return spec['sign']
5717 else:
5718 return ''
5719
5720def _format_number(is_negative, intpart, fracpart, exp, spec):
5721 """Format a number, given the following data:
5722
5723 is_negative: true if the number is negative, else false
5724 intpart: string of digits that must appear before the decimal point
5725 fracpart: string of digits that must come after the point
5726 exp: exponent, as an integer
5727 spec: dictionary resulting from parsing the format specifier
5728
5729 This function uses the information in spec to:
5730 insert separators (decimal separator and thousands separators)
5731 format the sign
5732 format the exponent
5733 add trailing '%' for the '%' type
5734 zero-pad if necessary
5735 fill and align if necessary
5736 """
5737
5738 sign = _format_sign(is_negative, spec)
5739
5740 if fracpart:
5741 fracpart = spec['decimal_point'] + fracpart
5742
5743 if exp != 0 or spec['type'] in 'eE':
5744 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
5745 fracpart += "{0}{1:+}".format(echar, exp)
5746 if spec['type'] == '%':
5747 fracpart += '%'
5748
5749 if spec['zeropad']:
5750 min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
5751 else:
5752 min_width = 0
5753 intpart = _insert_thousands_sep(intpart, spec, min_width)
5754
5755 return _format_align(sign, intpart+fracpart, spec)
5756
5757
Guido van Rossumd8faa362007-04-27 19:54:29 +00005758##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005759
Guido van Rossumd8faa362007-04-27 19:54:29 +00005760# Reusable defaults
Mark Dickinson627cf6a2009-01-03 12:11:47 +00005761_Infinity = Decimal('Inf')
5762_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonf9236412009-01-02 23:23:21 +00005763_NaN = Decimal('NaN')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00005764_Zero = Decimal(0)
5765_One = Decimal(1)
5766_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005767
Mark Dickinson627cf6a2009-01-03 12:11:47 +00005768# _SignedInfinity[sign] is infinity w/ that sign
5769_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005770
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005771
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005772
5773if __name__ == '__main__':
5774 import doctest, sys
5775 doctest.testmod(sys.modules[__name__])