blob: 727aee2f108dbd9882fdd327d341b4cc7290eca0 [file] [log] [blame]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001# Copyright (c) 2004 Python Software Foundation.
2# All rights reserved.
3
4# Written by Eric Price <eprice at tjhsst.edu>
5# and Facundo Batista <facundo at taniquetil.com.ar>
6# and Raymond Hettinger <python at rcn.com>
Fred Drake1f34eb12004-07-01 14:28:36 +00007# and Aahz <aahz at pobox.com>
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00008# and Tim Peters
9
Facundo Batista6ab24792009-02-16 15:41:37 +000010# This module should be kept in sync with the latest updates of the
11# IBM specification as it evolves. Those updates will be treated
Raymond Hettinger27dbcf22004-08-19 22:39:55 +000012# as bug fixes (deviation from the spec is a compatibility, usability
13# bug) and will be backported. At this point the spec is stabilizing
14# and the updates are becoming fewer, smaller, and less significant.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000015
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000016"""
Facundo Batista6ab24792009-02-16 15:41:37 +000017This is an implementation of decimal floating point arithmetic based on
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000018the General Decimal Arithmetic Specification:
19
Raymond Hettinger960dc362009-04-21 03:43:15 +000020 http://speleotrove.com/decimal/decarith.html
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000021
Raymond Hettinger0ea241e2004-07-04 13:53:24 +000022and IEEE standard 854-1987:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000023
24 www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
25
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000026Decimal floating point has finite precision with arbitrarily large bounds.
27
Guido van Rossumd8faa362007-04-27 19:54:29 +000028The purpose of this module is to support arithmetic using familiar
29"schoolhouse" rules and to avoid some of the tricky representation
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000030issues associated with binary floating point. The package is especially
31useful for financial applications or for contexts where users have
32expectations that are at odds with binary floating point (for instance,
33in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
Christian Heimes68f5fbe2008-02-14 08:27:37 +000034of the expected Decimal('0.00') returned by decimal floating point).
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000035
36Here are some examples of using the decimal module:
37
38>>> from decimal import *
Raymond Hettingerbd7f76d2004-07-08 00:49:18 +000039>>> setcontext(ExtendedContext)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000040>>> Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000041Decimal('0')
42>>> Decimal('1')
43Decimal('1')
44>>> Decimal('-.0123')
45Decimal('-0.0123')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000046>>> Decimal(123456)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000047Decimal('123456')
48>>> Decimal('123.45e12345678901234567890')
49Decimal('1.2345E+12345678901234567892')
50>>> Decimal('1.33') + Decimal('1.27')
51Decimal('2.60')
52>>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
53Decimal('-2.20')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000054>>> dig = Decimal(1)
Guido van Rossum7131f842007-02-09 20:13:25 +000055>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000560.333333333
57>>> getcontext().prec = 18
Guido van Rossum7131f842007-02-09 20:13:25 +000058>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000590.333333333333333333
Guido van Rossum7131f842007-02-09 20:13:25 +000060>>> print(dig.sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000611
Guido van Rossum7131f842007-02-09 20:13:25 +000062>>> print(Decimal(3).sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000631.73205080756887729
Guido van Rossum7131f842007-02-09 20:13:25 +000064>>> print(Decimal(3) ** 123)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000654.85192780976896427E+58
66>>> inf = Decimal(1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000067>>> print(inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000068Infinity
69>>> neginf = Decimal(-1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000070>>> print(neginf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000071-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000072>>> print(neginf + inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000073NaN
Guido van Rossum7131f842007-02-09 20:13:25 +000074>>> print(neginf * inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000075-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000076>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000077Infinity
Raymond Hettingerbf440692004-07-10 14:14:37 +000078>>> getcontext().traps[DivisionByZero] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000079>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000080Traceback (most recent call last):
81 ...
82 ...
83 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +000084decimal.DivisionByZero: x / 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000085>>> c = Context()
Raymond Hettingerbf440692004-07-10 14:14:37 +000086>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000087>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000880
89>>> c.divide(Decimal(0), Decimal(0))
Christian Heimes68f5fbe2008-02-14 08:27:37 +000090Decimal('NaN')
Raymond Hettingerbf440692004-07-10 14:14:37 +000091>>> c.traps[InvalidOperation] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000092>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000931
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000094>>> c.flags[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000095>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000960
Guido van Rossum7131f842007-02-09 20:13:25 +000097>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000098Traceback (most recent call last):
99 ...
100 ...
101 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +0000102decimal.InvalidOperation: 0 / 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000103>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001041
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000105>>> c.flags[InvalidOperation] = 0
Raymond Hettingerbf440692004-07-10 14:14:37 +0000106>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000107>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000108NaN
Guido van Rossum7131f842007-02-09 20:13:25 +0000109>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001101
111>>>
112"""
113
114__all__ = [
115 # Two major classes
116 'Decimal', 'Context',
117
118 # Contexts
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +0000119 'DefaultContext', 'BasicContext', 'ExtendedContext',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000120
121 # Exceptions
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +0000122 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
123 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000124
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000125 # Constants for use in setting up contexts
126 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000127 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000128
129 # Functions for manipulating contexts
Thomas Wouters89f507f2006-12-13 04:49:30 +0000130 'setcontext', 'getcontext', 'localcontext'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000131]
132
Raymond Hettinger960dc362009-04-21 03:43:15 +0000133__version__ = '1.70' # Highest version of the spec this complies with
134
Raymond Hettingereb260842005-06-07 18:52:34 +0000135import copy as _copy
Raymond Hettinger771ed762009-01-03 19:20:32 +0000136import math as _math
Raymond Hettinger82417ca2009-02-03 03:54:28 +0000137import numbers as _numbers
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000138
Christian Heimes25bb7832008-01-11 16:17:00 +0000139try:
140 from collections import namedtuple as _namedtuple
141 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
142except ImportError:
143 DecimalTuple = lambda *args: args
144
Guido van Rossumd8faa362007-04-27 19:54:29 +0000145# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000146ROUND_DOWN = 'ROUND_DOWN'
147ROUND_HALF_UP = 'ROUND_HALF_UP'
148ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
149ROUND_CEILING = 'ROUND_CEILING'
150ROUND_FLOOR = 'ROUND_FLOOR'
151ROUND_UP = 'ROUND_UP'
152ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000153ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000154
Guido van Rossumd8faa362007-04-27 19:54:29 +0000155# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000156
157class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000158 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000159
160 Used exceptions derive from this.
161 If an exception derives from another exception besides this (such as
162 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
163 called if the others are present. This isn't actually used for
164 anything, though.
165
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000166 handle -- Called when context._raise_error is called and the
167 trap_enabler is set. First argument is self, second is the
168 context. More arguments can be given, those being after
169 the explanation in _raise_error (For example,
170 context._raise_error(NewError, '(-x)!', self._sign) would
171 call NewError().handle(context, self._sign).)
172
173 To define a new exception, it should be sufficient to have it derive
174 from DecimalException.
175 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000176 def handle(self, context, *args):
177 pass
178
179
180class Clamped(DecimalException):
181 """Exponent of a 0 changed to fit bounds.
182
183 This occurs and signals clamped if the exponent of a result has been
184 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000185 representation. This may occur when the exponent of a zero result would
186 be outside the bounds of a representation, or when a large normal
187 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000188 this latter case, the exponent is reduced to fit and the corresponding
189 number of zero digits are appended to the coefficient ("fold-down").
190 """
191
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000192class InvalidOperation(DecimalException):
193 """An invalid operation was performed.
194
195 Various bad things cause this:
196
197 Something creates a signaling NaN
198 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000199 0 * (+-)INF
200 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000201 x % 0
202 (+-)INF % x
203 x._rescale( non-integer )
204 sqrt(-x) , x > 0
205 0 ** 0
206 x ** (non-integer)
207 x ** (+-)INF
208 An operand is invalid
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000209
210 The result of the operation after these is a quiet positive NaN,
211 except when the cause is a signaling NaN, in which case the result is
212 also a quiet NaN, but with the original sign, and an optional
213 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000214 """
215 def handle(self, context, *args):
216 if args:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000217 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
218 return ans._fix_nan(context)
Mark Dickinsonf9236412009-01-02 23:23:21 +0000219 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000220
221class ConversionSyntax(InvalidOperation):
222 """Trying to convert badly formed string.
223
224 This occurs and signals invalid-operation if an string is being
225 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000226 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000227 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000228 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000229 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000230
231class DivisionByZero(DecimalException, ZeroDivisionError):
232 """Division by 0.
233
234 This occurs and signals division-by-zero if division of a finite number
235 by zero was attempted (during a divide-integer or divide operation, or a
236 power operation with negative right-hand operand), and the dividend was
237 not zero.
238
239 The result of the operation is [sign,inf], where sign is the exclusive
240 or of the signs of the operands for divide, or is 1 for an odd power of
241 -0, for power.
242 """
243
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000244 def handle(self, context, sign, *args):
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000245 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000246
247class DivisionImpossible(InvalidOperation):
248 """Cannot perform the division adequately.
249
250 This occurs and signals invalid-operation if the integer result of a
251 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000252 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000253 """
254
255 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000256 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000257
258class DivisionUndefined(InvalidOperation, ZeroDivisionError):
259 """Undefined result of division.
260
261 This occurs and signals invalid-operation if division by zero was
262 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000263 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000264 """
265
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000266 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000267 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000268
269class Inexact(DecimalException):
270 """Had to round, losing information.
271
272 This occurs and signals inexact whenever the result of an operation is
273 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000274 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000275 result in all cases is unchanged.
276
277 The inexact signal may be tested (or trapped) to determine if a given
278 operation (or sequence of operations) was inexact.
279 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000280
281class InvalidContext(InvalidOperation):
282 """Invalid context. Unknown rounding, for example.
283
284 This occurs and signals invalid-operation if an invalid context was
Guido van Rossumd8faa362007-04-27 19:54:29 +0000285 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000286 on creation and either the precision exceeds the capability of the
287 underlying concrete representation or an unknown or unsupported rounding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000288 was specified. These aspects of the context need only be checked when
289 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000290 """
291
292 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000293 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000294
295class Rounded(DecimalException):
296 """Number got rounded (not necessarily changed during rounding).
297
298 This occurs and signals rounded whenever the result of an operation is
299 rounded (that is, some zero or non-zero digits were discarded from the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000300 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000301 result in all cases is unchanged.
302
303 The rounded signal may be tested (or trapped) to determine if a given
304 operation (or sequence of operations) caused a loss of precision.
305 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000306
307class Subnormal(DecimalException):
308 """Exponent < Emin before rounding.
309
310 This occurs and signals subnormal whenever the result of a conversion or
311 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000312 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000313
314 The subnormal signal may be tested (or trapped) to determine if a given
315 or operation (or sequence of operations) yielded a subnormal result.
316 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000317
318class Overflow(Inexact, Rounded):
319 """Numerical overflow.
320
321 This occurs and signals overflow if the adjusted exponent of a result
322 (from a conversion or from an operation that is not an attempt to divide
323 by zero), after rounding, would be greater than the largest value that
324 can be handled by the implementation (the value Emax).
325
326 The result depends on the rounding mode:
327
328 For round-half-up and round-half-even (and for round-half-down and
329 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000330 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000331 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000332 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000333 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000334 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000335 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000336 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 will also be raised.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000338 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000339
340 def handle(self, context, sign, *args):
341 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000342 ROUND_HALF_DOWN, ROUND_UP):
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000343 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000344 if sign == 0:
345 if context.rounding == ROUND_CEILING:
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000346 return _SignedInfinity[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000347 return _dec_from_triple(sign, '9'*context.prec,
348 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000349 if sign == 1:
350 if context.rounding == ROUND_FLOOR:
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000351 return _SignedInfinity[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000352 return _dec_from_triple(sign, '9'*context.prec,
353 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000354
355
356class Underflow(Inexact, Rounded, Subnormal):
357 """Numerical underflow with result rounded to 0.
358
359 This occurs and signals underflow if a result is inexact and the
360 adjusted exponent of the result would be smaller (more negative) than
361 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000362 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000363
364 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000365 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000366 in 0 with the sign of the intermediate result and an exponent of Etiny.
367
368 In all cases, Inexact, Rounded, and Subnormal will also be raised.
369 """
370
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000371# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000372_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000373 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000374
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000375# Map conditions (per the spec) to signals
376_condition_map = {ConversionSyntax:InvalidOperation,
377 DivisionImpossible:InvalidOperation,
378 DivisionUndefined:InvalidOperation,
379 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000380
Guido van Rossumd8faa362007-04-27 19:54:29 +0000381##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000382
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000383# The getcontext() and setcontext() function manage access to a thread-local
384# current context. Py2.4 offers direct support for thread locals. If that
Georg Brandlf9926402008-06-13 06:32:25 +0000385# is not available, use threading.current_thread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000386# work for older Pythons. If threads are not part of the build, create a
387# mock threading object with threading.local() returning the module namespace.
388
389try:
390 import threading
391except ImportError:
392 # Python was compiled without threads; create a mock object instead
393 import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +0000394 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000395 def local(self, sys=sys):
396 return sys.modules[__name__]
397 threading = MockThreading()
398 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000399
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000400try:
401 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000402
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000403except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000404
Guido van Rossumd8faa362007-04-27 19:54:29 +0000405 # To fix reloading, force it to create a new context
406 # Old contexts have different exceptions in their dicts, making problems.
Georg Brandlf9926402008-06-13 06:32:25 +0000407 if hasattr(threading.current_thread(), '__decimal_context__'):
408 del threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000409
410 def setcontext(context):
411 """Set this thread's context to context."""
412 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000413 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000414 context.clear_flags()
Georg Brandlf9926402008-06-13 06:32:25 +0000415 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000416
417 def getcontext():
418 """Returns this thread's context.
419
420 If this thread does not yet have a context, returns
421 a new context and sets this thread's context.
422 New contexts are copies of DefaultContext.
423 """
424 try:
Georg Brandlf9926402008-06-13 06:32:25 +0000425 return threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000426 except AttributeError:
427 context = Context()
Georg Brandlf9926402008-06-13 06:32:25 +0000428 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000429 return context
430
431else:
432
433 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000434 if hasattr(local, '__decimal_context__'):
435 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000436
437 def getcontext(_local=local):
438 """Returns this thread's context.
439
440 If this thread does not yet have a context, returns
441 a new context and sets this thread's context.
442 New contexts are copies of DefaultContext.
443 """
444 try:
445 return _local.__decimal_context__
446 except AttributeError:
447 context = Context()
448 _local.__decimal_context__ = context
449 return context
450
451 def setcontext(context, _local=local):
452 """Set this thread's context to context."""
453 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000454 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000455 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000456 _local.__decimal_context__ = context
457
458 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000459
Thomas Wouters89f507f2006-12-13 04:49:30 +0000460def localcontext(ctx=None):
461 """Return a context manager for a copy of the supplied context
462
463 Uses a copy of the current context if no context is specified
464 The returned context manager creates a local decimal context
465 in a with statement:
466 def sin(x):
467 with localcontext() as ctx:
468 ctx.prec += 2
469 # Rest of sin calculation algorithm
470 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000471 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000472
473 def sin(x):
474 with localcontext(ExtendedContext):
475 # Rest of sin calculation algorithm
476 # uses the Extended Context from the
477 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000478 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000479
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000480 >>> setcontext(DefaultContext)
Guido van Rossum7131f842007-02-09 20:13:25 +0000481 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000482 28
483 >>> with localcontext():
484 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000485 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000486 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000487 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000488 30
489 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000490 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000491 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000492 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000493 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000494 28
495 """
496 if ctx is None: ctx = getcontext()
497 return _ContextManager(ctx)
498
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000499
Guido van Rossumd8faa362007-04-27 19:54:29 +0000500##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000501
Raymond Hettingera0fd8882009-01-20 07:24:44 +0000502# Do not subclass Decimal from numbers.Real and do not register it as such
503# (because Decimals are not interoperable with floats). See the notes in
504# numbers.py for more detail.
505
506class Decimal(object):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000507 """Floating point class for decimal arithmetic."""
508
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000509 __slots__ = ('_exp','_int','_sign', '_is_special')
510 # Generally, the value of the Decimal instance is given by
511 # (-1)**_sign * _int * 10**_exp
512 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000513
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000514 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000515 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000516 """Create a decimal point instance.
517
518 >>> Decimal('3.14') # string input
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000519 Decimal('3.14')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000520 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000521 Decimal('3.14')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000522 >>> Decimal(314) # int
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000523 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000524 >>> Decimal(Decimal(314)) # another decimal instance
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000525 Decimal('314')
Christian Heimesa62da1d2008-01-12 19:39:10 +0000526 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000527 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000528 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000529
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000530 # Note that the coefficient, self._int, is actually stored as
531 # a string rather than as a tuple of digits. This speeds up
532 # the "digits to integer" and "integer to digits" conversions
533 # that are used in almost every arithmetic operation on
534 # Decimals. This is an internal detail: the as_tuple function
535 # and the Decimal constructor still deal with tuples of
536 # digits.
537
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000538 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000539
Christian Heimesd59c64c2007-11-30 19:27:20 +0000540 # From a string
541 # REs insist on real strings, so we can too.
542 if isinstance(value, str):
Christian Heimesa62da1d2008-01-12 19:39:10 +0000543 m = _parser(value.strip())
Christian Heimesd59c64c2007-11-30 19:27:20 +0000544 if m is None:
545 if context is None:
546 context = getcontext()
547 return context._raise_error(ConversionSyntax,
548 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000549
Christian Heimesd59c64c2007-11-30 19:27:20 +0000550 if m.group('sign') == "-":
551 self._sign = 1
552 else:
553 self._sign = 0
554 intpart = m.group('int')
555 if intpart is not None:
556 # finite number
Mark Dickinson345adc42009-08-02 10:14:23 +0000557 fracpart = m.group('frac') or ''
Christian Heimesd59c64c2007-11-30 19:27:20 +0000558 exp = int(m.group('exp') or '0')
Mark Dickinson345adc42009-08-02 10:14:23 +0000559 self._int = str(int(intpart+fracpart))
560 self._exp = exp - len(fracpart)
Christian Heimesd59c64c2007-11-30 19:27:20 +0000561 self._is_special = False
562 else:
563 diag = m.group('diag')
564 if diag is not None:
565 # NaN
Mark Dickinson345adc42009-08-02 10:14:23 +0000566 self._int = str(int(diag or '0')).lstrip('0')
Christian Heimesd59c64c2007-11-30 19:27:20 +0000567 if m.group('signal'):
568 self._exp = 'N'
569 else:
570 self._exp = 'n'
571 else:
572 # infinity
573 self._int = '0'
574 self._exp = 'F'
575 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000576 return self
577
578 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000579 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000580 if value >= 0:
581 self._sign = 0
582 else:
583 self._sign = 1
584 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000585 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000586 self._is_special = False
587 return self
588
589 # From another decimal
590 if isinstance(value, Decimal):
591 self._exp = value._exp
592 self._sign = value._sign
593 self._int = value._int
594 self._is_special = value._is_special
595 return self
596
597 # From an internal working value
598 if isinstance(value, _WorkRep):
599 self._sign = value.sign
600 self._int = str(value.int)
601 self._exp = int(value.exp)
602 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000603 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000604
605 # tuple/list conversion (possibly from as_tuple())
606 if isinstance(value, (list,tuple)):
607 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000608 raise ValueError('Invalid tuple size in creation of Decimal '
609 'from list or tuple. The list or tuple '
610 'should have exactly three elements.')
611 # process sign. The isinstance test rejects floats
612 if not (isinstance(value[0], int) and value[0] in (0,1)):
613 raise ValueError("Invalid sign. The first value in the tuple "
614 "should be an integer; either 0 for a "
615 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000616 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000617 if value[2] == 'F':
618 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000619 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000620 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000621 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000622 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000623 # process and validate the digits in value[1]
624 digits = []
625 for digit in value[1]:
626 if isinstance(digit, int) and 0 <= digit <= 9:
627 # skip leading zeros
628 if digits or digit != 0:
629 digits.append(digit)
630 else:
631 raise ValueError("The second value in the tuple must "
632 "be composed of integers in the range "
633 "0 through 9.")
634 if value[2] in ('n', 'N'):
635 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000636 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000637 self._exp = value[2]
638 self._is_special = True
639 elif isinstance(value[2], int):
640 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000641 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000642 self._exp = value[2]
643 self._is_special = False
644 else:
645 raise ValueError("The third value in the tuple must "
646 "be an integer, or one of the "
647 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000648 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000649
Raymond Hettingerbf440692004-07-10 14:14:37 +0000650 if isinstance(value, float):
Raymond Hettinger96798592010-04-02 16:58:27 +0000651 value = Decimal.from_float(value)
652 self._exp = value._exp
653 self._sign = value._sign
654 self._int = value._int
655 self._is_special = value._is_special
656 return self
Raymond Hettingerbf440692004-07-10 14:14:37 +0000657
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000658 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000659
Mark Dickinsonba298e42009-01-04 21:17:43 +0000660 # @classmethod, but @decorator is not valid Python 2.3 syntax, so
661 # don't use it (see notes on Py2.3 compatibility at top of file)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000662 def from_float(cls, f):
663 """Converts a float to a decimal number, exactly.
664
665 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
666 Since 0.1 is not exactly representable in binary floating point, the
667 value is stored as the nearest representable value which is
668 0x1.999999999999ap-4. The exact equivalent of the value in decimal
669 is 0.1000000000000000055511151231257827021181583404541015625.
670
671 >>> Decimal.from_float(0.1)
672 Decimal('0.1000000000000000055511151231257827021181583404541015625')
673 >>> Decimal.from_float(float('nan'))
674 Decimal('NaN')
675 >>> Decimal.from_float(float('inf'))
676 Decimal('Infinity')
677 >>> Decimal.from_float(-float('inf'))
678 Decimal('-Infinity')
679 >>> Decimal.from_float(-0.0)
680 Decimal('-0')
681
682 """
683 if isinstance(f, int): # handle integer inputs
684 return cls(f)
685 if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float
686 return cls(repr(f))
Mark Dickinsonba298e42009-01-04 21:17:43 +0000687 if _math.copysign(1.0, f) == 1.0:
688 sign = 0
689 else:
690 sign = 1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000691 n, d = abs(f).as_integer_ratio()
692 k = d.bit_length() - 1
693 result = _dec_from_triple(sign, str(n*5**k), -k)
Mark Dickinsonba298e42009-01-04 21:17:43 +0000694 if cls is Decimal:
695 return result
696 else:
697 return cls(result)
698 from_float = classmethod(from_float)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000699
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000700 def _isnan(self):
701 """Returns whether the number is not actually one.
702
703 0 if a number
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000704 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000705 2 if sNaN
706 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000707 if self._is_special:
708 exp = self._exp
709 if exp == 'n':
710 return 1
711 elif exp == 'N':
712 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000713 return 0
714
715 def _isinfinity(self):
716 """Returns whether the number is infinite
717
718 0 if finite or not a number
719 1 if +INF
720 -1 if -INF
721 """
722 if self._exp == 'F':
723 if self._sign:
724 return -1
725 return 1
726 return 0
727
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000728 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000729 """Returns whether the number is not actually one.
730
731 if self, other are sNaN, signal
732 if self, other are NaN return nan
733 return 0
734
735 Done before operations.
736 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000737
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000738 self_is_nan = self._isnan()
739 if other is None:
740 other_is_nan = False
741 else:
742 other_is_nan = other._isnan()
743
744 if self_is_nan or other_is_nan:
745 if context is None:
746 context = getcontext()
747
748 if self_is_nan == 2:
749 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000750 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000751 if other_is_nan == 2:
752 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000753 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000754 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000755 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000756
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000757 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000758 return 0
759
Christian Heimes77c02eb2008-02-09 02:18:51 +0000760 def _compare_check_nans(self, other, context):
761 """Version of _check_nans used for the signaling comparisons
762 compare_signal, __le__, __lt__, __ge__, __gt__.
763
764 Signal InvalidOperation if either self or other is a (quiet
765 or signaling) NaN. Signaling NaNs take precedence over quiet
766 NaNs.
767
768 Return 0 if neither operand is a NaN.
769
770 """
771 if context is None:
772 context = getcontext()
773
774 if self._is_special or other._is_special:
775 if self.is_snan():
776 return context._raise_error(InvalidOperation,
777 'comparison involving sNaN',
778 self)
779 elif other.is_snan():
780 return context._raise_error(InvalidOperation,
781 'comparison involving sNaN',
782 other)
783 elif self.is_qnan():
784 return context._raise_error(InvalidOperation,
785 'comparison involving NaN',
786 self)
787 elif other.is_qnan():
788 return context._raise_error(InvalidOperation,
789 'comparison involving NaN',
790 other)
791 return 0
792
Jack Diederich4dafcc42006-11-28 19:15:13 +0000793 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000794 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000795
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000796 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000797 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000798 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000799
Christian Heimes77c02eb2008-02-09 02:18:51 +0000800 def _cmp(self, other):
801 """Compare the two non-NaN decimal instances self and other.
802
803 Returns -1 if self < other, 0 if self == other and 1
804 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000805
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000806 if self._is_special or other._is_special:
Mark Dickinsone6aad752009-01-25 10:48:51 +0000807 self_inf = self._isinfinity()
808 other_inf = other._isinfinity()
809 if self_inf == other_inf:
810 return 0
811 elif self_inf < other_inf:
812 return -1
813 else:
814 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000815
Mark Dickinsone6aad752009-01-25 10:48:51 +0000816 # check for zeros; Decimal('0') == Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000817 if not self:
818 if not other:
819 return 0
820 else:
821 return -((-1)**other._sign)
822 if not other:
823 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000824
Guido van Rossumd8faa362007-04-27 19:54:29 +0000825 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000826 if other._sign < self._sign:
827 return -1
828 if self._sign < other._sign:
829 return 1
830
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000831 self_adjusted = self.adjusted()
832 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000833 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000834 self_padded = self._int + '0'*(self._exp - other._exp)
835 other_padded = other._int + '0'*(other._exp - self._exp)
Mark Dickinsone6aad752009-01-25 10:48:51 +0000836 if self_padded == other_padded:
837 return 0
838 elif self_padded < other_padded:
839 return -(-1)**self._sign
840 else:
841 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000842 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000843 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000844 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000845 return -((-1)**self._sign)
846
Christian Heimes77c02eb2008-02-09 02:18:51 +0000847 # Note: The Decimal standard doesn't cover rich comparisons for
848 # Decimals. In particular, the specification is silent on the
849 # subject of what should happen for a comparison involving a NaN.
850 # We take the following approach:
851 #
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000852 # == comparisons involving a quiet NaN always return False
853 # != comparisons involving a quiet NaN always return True
854 # == or != comparisons involving a signaling NaN signal
855 # InvalidOperation, and return False or True as above if the
856 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000857 # <, >, <= and >= comparisons involving a (quiet or signaling)
858 # NaN signal InvalidOperation, and return False if the
Christian Heimes3feef612008-02-11 06:19:17 +0000859 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000860 #
861 # This behavior is designed to conform as closely as possible to
862 # that specified by IEEE 754.
863
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000864 def __eq__(self, other, context=None):
865 other = _convert_other(other, allow_float=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000866 if other is NotImplemented:
867 return other
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000868 if self._check_nans(other, context):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000869 return False
870 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000871
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000872 def __ne__(self, other, context=None):
873 other = _convert_other(other, allow_float=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000874 if other is NotImplemented:
875 return other
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000876 if self._check_nans(other, context):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000877 return True
878 return self._cmp(other) != 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000879
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000880
Christian Heimes77c02eb2008-02-09 02:18:51 +0000881 def __lt__(self, other, context=None):
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000882 other = _convert_other(other, allow_float=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000883 if other is NotImplemented:
884 return other
885 ans = self._compare_check_nans(other, context)
886 if ans:
887 return False
888 return self._cmp(other) < 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000889
Christian Heimes77c02eb2008-02-09 02:18:51 +0000890 def __le__(self, other, context=None):
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000891 other = _convert_other(other, allow_float=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000892 if other is NotImplemented:
893 return other
894 ans = self._compare_check_nans(other, context)
895 if ans:
896 return False
897 return self._cmp(other) <= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000898
Christian Heimes77c02eb2008-02-09 02:18:51 +0000899 def __gt__(self, other, context=None):
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000900 other = _convert_other(other, allow_float=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000901 if other is NotImplemented:
902 return other
903 ans = self._compare_check_nans(other, context)
904 if ans:
905 return False
906 return self._cmp(other) > 0
907
908 def __ge__(self, other, context=None):
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000909 other = _convert_other(other, allow_float=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000910 if other is NotImplemented:
911 return other
912 ans = self._compare_check_nans(other, context)
913 if ans:
914 return False
915 return self._cmp(other) >= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000916
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000917 def compare(self, other, context=None):
918 """Compares one to another.
919
920 -1 => a < b
921 0 => a = b
922 1 => a > b
923 NaN => one is NaN
924 Like __cmp__, but returns Decimal instances.
925 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000926 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000927
Guido van Rossumd8faa362007-04-27 19:54:29 +0000928 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000929 if (self._is_special or other and other._is_special):
930 ans = self._check_nans(other, context)
931 if ans:
932 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000933
Christian Heimes77c02eb2008-02-09 02:18:51 +0000934 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000935
936 def __hash__(self):
937 """x.__hash__() <==> hash(x)"""
938 # Decimal integers must hash the same as the ints
Christian Heimes2380ac72008-01-09 00:17:24 +0000939 #
940 # The hash of a nonspecial noninteger Decimal must depend only
941 # on the value of that Decimal, and not on its representation.
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000942 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000943
944 # Equality comparisons involving signaling nans can raise an
945 # exception; since equality checks are implicitly and
946 # unpredictably used when checking set and dict membership, we
947 # prevent signaling nans from being used as set elements or
948 # dict keys by making __hash__ raise an exception.
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000949 if self._is_special:
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000950 if self.is_snan():
951 raise TypeError('Cannot hash a signaling NaN value.')
952 elif self.is_nan():
953 # 0 to match hash(float('nan'))
954 return 0
955 else:
956 # values chosen to match hash(float('inf')) and
957 # hash(float('-inf')).
958 if self._sign:
959 return -271828
960 else:
961 return 314159
962
963 # In Python 2.7, we're allowing comparisons (but not
964 # arithmetic operations) between floats and Decimals; so if
965 # a Decimal instance is exactly representable as a float then
966 # its hash should match that of the float.
967 self_as_float = float(self)
968 if Decimal.from_float(self_as_float) == self:
969 return hash(self_as_float)
970
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000971 if self._isinteger():
972 op = _WorkRep(self.to_integral_value())
973 # to make computation feasible for Decimals with large
974 # exponent, we use the fact that hash(n) == hash(m) for
975 # any two nonzero integers n and m such that (i) n and m
976 # have the same sign, and (ii) n is congruent to m modulo
977 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
978 # hash((-1)**s*c*pow(10, e, 2**64-1).
979 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Christian Heimes2380ac72008-01-09 00:17:24 +0000980 # The value of a nonzero nonspecial Decimal instance is
981 # faithfully represented by the triple consisting of its sign,
982 # its adjusted exponent, and its coefficient with trailing
983 # zeros removed.
984 return hash((self._sign,
985 self._exp+len(self._int),
986 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000987
988 def as_tuple(self):
989 """Represents the number as a triple tuple.
990
991 To show the internals exactly as they are.
992 """
Christian Heimes25bb7832008-01-11 16:17:00 +0000993 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000994
995 def __repr__(self):
996 """Represents the number as an instance of Decimal."""
997 # Invariant: eval(repr(d)) == d
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000998 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000999
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001000 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001001 """Return string representation of the number in scientific notation.
1002
1003 Captures all of the information in the underlying representation.
1004 """
1005
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001006 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +00001007 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001008 if self._exp == 'F':
1009 return sign + 'Infinity'
1010 elif self._exp == 'n':
1011 return sign + 'NaN' + self._int
1012 else: # self._exp == 'N'
1013 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001014
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001015 # number of digits of self._int to left of decimal point
1016 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001017
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001018 # dotplace is number of digits of self._int to the left of the
1019 # decimal point in the mantissa of the output string (that is,
1020 # after adjusting the exponent)
1021 if self._exp <= 0 and leftdigits > -6:
1022 # no exponent required
1023 dotplace = leftdigits
1024 elif not eng:
1025 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001026 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001027 elif self._int == '0':
1028 # engineering notation, zero
1029 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001030 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001031 # engineering notation, nonzero
1032 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001033
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001034 if dotplace <= 0:
1035 intpart = '0'
1036 fracpart = '.' + '0'*(-dotplace) + self._int
1037 elif dotplace >= len(self._int):
1038 intpart = self._int+'0'*(dotplace-len(self._int))
1039 fracpart = ''
1040 else:
1041 intpart = self._int[:dotplace]
1042 fracpart = '.' + self._int[dotplace:]
1043 if leftdigits == dotplace:
1044 exp = ''
1045 else:
1046 if context is None:
1047 context = getcontext()
1048 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1049
1050 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001051
1052 def to_eng_string(self, context=None):
1053 """Convert to engineering-type string.
1054
1055 Engineering notation has an exponent which is a multiple of 3, so there
1056 are up to 3 digits left of the decimal place.
1057
1058 Same rules for when in exponential and when as a value as in __str__.
1059 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001060 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001061
1062 def __neg__(self, context=None):
1063 """Returns a copy with the sign switched.
1064
1065 Rounds, if it has reason.
1066 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001067 if self._is_special:
1068 ans = self._check_nans(context=context)
1069 if ans:
1070 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001071
1072 if not self:
1073 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001074 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001075 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001076 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001077
1078 if context is None:
1079 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001080 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081
1082 def __pos__(self, context=None):
1083 """Returns a copy, unless it is a sNaN.
1084
1085 Rounds the number (if more then precision digits)
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 not self:
1093 # + (-0) = 0
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001094 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001095 else:
1096 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001097
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001098 if context is None:
1099 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001100 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001101
Christian Heimes2c181612007-12-17 20:04:13 +00001102 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001103 """Returns the absolute value of self.
1104
Christian Heimes2c181612007-12-17 20:04:13 +00001105 If the keyword argument 'round' is false, do not round. The
1106 expression self.__abs__(round=False) is equivalent to
1107 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001108 """
Christian Heimes2c181612007-12-17 20:04:13 +00001109 if not round:
1110 return self.copy_abs()
1111
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001112 if self._is_special:
1113 ans = self._check_nans(context=context)
1114 if ans:
1115 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001116
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001117 if self._sign:
1118 ans = self.__neg__(context=context)
1119 else:
1120 ans = self.__pos__(context=context)
1121
1122 return ans
1123
1124 def __add__(self, other, context=None):
1125 """Returns self + other.
1126
1127 -INF + INF (or the reverse) cause InvalidOperation errors.
1128 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001129 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001130 if other is NotImplemented:
1131 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001132
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001133 if context is None:
1134 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001135
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001136 if self._is_special or other._is_special:
1137 ans = self._check_nans(other, context)
1138 if ans:
1139 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001140
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001141 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001142 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001143 if self._sign != other._sign and other._isinfinity():
1144 return context._raise_error(InvalidOperation, '-INF + INF')
1145 return Decimal(self)
1146 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001147 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001148
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001149 exp = min(self._exp, other._exp)
1150 negativezero = 0
1151 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001152 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001153 negativezero = 1
1154
1155 if not self and not other:
1156 sign = min(self._sign, other._sign)
1157 if negativezero:
1158 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001159 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001160 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001161 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001162 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001163 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001164 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001165 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001166 return ans
1167 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001168 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001169 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001170 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001171 return ans
1172
1173 op1 = _WorkRep(self)
1174 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001175 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001176
1177 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001178 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001179 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001180 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001181 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001182 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001183 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001184 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001185 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001186 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001187 if op1.sign == 1:
1188 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001189 op1.sign, op2.sign = op2.sign, op1.sign
1190 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001191 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001192 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001193 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001194 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001195 op1.sign, op2.sign = (0, 0)
1196 else:
1197 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001198 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001199
Raymond Hettinger17931de2004-10-27 06:21:46 +00001200 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001201 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001202 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001203 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001204
1205 result.exp = op1.exp
1206 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001207 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001208 return ans
1209
1210 __radd__ = __add__
1211
1212 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001213 """Return self - other"""
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 Hettinger7c85fa42004-07-01 11:01:35 +00001217
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001218 if self._is_special or other._is_special:
1219 ans = self._check_nans(other, context=context)
1220 if ans:
1221 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001222
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001223 # self - other is computed as self + other.copy_negate()
1224 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001225
1226 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001227 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001228 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001229 if other is NotImplemented:
1230 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001231
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001232 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001233
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001234 def __mul__(self, other, context=None):
1235 """Return self * other.
1236
1237 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1238 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001239 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001240 if other is NotImplemented:
1241 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001242
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001243 if context is None:
1244 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001245
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001246 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001247
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001248 if self._is_special or other._is_special:
1249 ans = self._check_nans(other, context)
1250 if ans:
1251 return ans
1252
1253 if self._isinfinity():
1254 if not other:
1255 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001256 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001257
1258 if other._isinfinity():
1259 if not self:
1260 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001261 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001262
1263 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001264
1265 # Special case for multiplying by zero
1266 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001267 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001268 # Fixing in case the exponent is out of bounds
1269 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001270 return ans
1271
1272 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001273 if self._int == '1':
1274 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001275 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001276 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001277 if other._int == '1':
1278 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001279 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001280 return ans
1281
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001282 op1 = _WorkRep(self)
1283 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001284
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001285 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001286 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001287
1288 return ans
1289 __rmul__ = __mul__
1290
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001291 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001292 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001293 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001294 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001295 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001296
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001297 if context is None:
1298 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001299
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001300 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001301
1302 if self._is_special or other._is_special:
1303 ans = self._check_nans(other, context)
1304 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001305 return ans
1306
1307 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001308 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001309
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001310 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001311 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001312
1313 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001314 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001315 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001316
1317 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001318 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001319 if not self:
1320 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001321 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001322
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001323 if not self:
1324 exp = self._exp - other._exp
1325 coeff = 0
1326 else:
1327 # OK, so neither = 0, INF or NaN
1328 shift = len(other._int) - len(self._int) + context.prec + 1
1329 exp = self._exp - other._exp - shift
1330 op1 = _WorkRep(self)
1331 op2 = _WorkRep(other)
1332 if shift >= 0:
1333 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1334 else:
1335 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1336 if remainder:
1337 # result is not exact; adjust to ensure correct rounding
1338 if coeff % 5 == 0:
1339 coeff += 1
1340 else:
1341 # result is exact; get as close to ideal exponent as possible
1342 ideal_exp = self._exp - other._exp
1343 while exp < ideal_exp and coeff % 10 == 0:
1344 coeff //= 10
1345 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001346
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001347 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001348 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001349
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001350 def _divide(self, other, context):
1351 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001352
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001353 Assumes that neither self nor other is a NaN, that self is not
1354 infinite and that other is nonzero.
1355 """
1356 sign = self._sign ^ other._sign
1357 if other._isinfinity():
1358 ideal_exp = self._exp
1359 else:
1360 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001361
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001362 expdiff = self.adjusted() - other.adjusted()
1363 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001364 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001365 self._rescale(ideal_exp, context.rounding))
1366 if expdiff <= context.prec:
1367 op1 = _WorkRep(self)
1368 op2 = _WorkRep(other)
1369 if op1.exp >= op2.exp:
1370 op1.int *= 10**(op1.exp - op2.exp)
1371 else:
1372 op2.int *= 10**(op2.exp - op1.exp)
1373 q, r = divmod(op1.int, op2.int)
1374 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001375 return (_dec_from_triple(sign, str(q), 0),
1376 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001377
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001378 # Here the quotient is too large to be representable
1379 ans = context._raise_error(DivisionImpossible,
1380 'quotient too large in //, % or divmod')
1381 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001382
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001383 def __rtruediv__(self, other, context=None):
1384 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001385 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001386 if other is NotImplemented:
1387 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001388 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001389
1390 def __divmod__(self, other, context=None):
1391 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001392 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001393 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001394 other = _convert_other(other)
1395 if other is NotImplemented:
1396 return other
1397
1398 if context is None:
1399 context = getcontext()
1400
1401 ans = self._check_nans(other, context)
1402 if ans:
1403 return (ans, ans)
1404
1405 sign = self._sign ^ other._sign
1406 if self._isinfinity():
1407 if other._isinfinity():
1408 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1409 return ans, ans
1410 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001411 return (_SignedInfinity[sign],
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001412 context._raise_error(InvalidOperation, 'INF % x'))
1413
1414 if not other:
1415 if not self:
1416 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1417 return ans, ans
1418 else:
1419 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1420 context._raise_error(InvalidOperation, 'x % 0'))
1421
1422 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001423 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001424 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001425
1426 def __rdivmod__(self, other, context=None):
1427 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001428 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001429 if other is NotImplemented:
1430 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001431 return other.__divmod__(self, context=context)
1432
1433 def __mod__(self, other, context=None):
1434 """
1435 self % other
1436 """
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
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001441 if context is None:
1442 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001443
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001444 ans = self._check_nans(other, context)
1445 if ans:
1446 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001447
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001448 if self._isinfinity():
1449 return context._raise_error(InvalidOperation, 'INF % x')
1450 elif not other:
1451 if self:
1452 return context._raise_error(InvalidOperation, 'x % 0')
1453 else:
1454 return context._raise_error(DivisionUndefined, '0 % 0')
1455
1456 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001457 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001458 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001459
1460 def __rmod__(self, other, context=None):
1461 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001462 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001463 if other is NotImplemented:
1464 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001465 return other.__mod__(self, context=context)
1466
1467 def remainder_near(self, other, context=None):
1468 """
1469 Remainder nearest to 0- abs(remainder-near) <= other/2
1470 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001471 if context is None:
1472 context = getcontext()
1473
1474 other = _convert_other(other, raiseit=True)
1475
1476 ans = self._check_nans(other, context)
1477 if ans:
1478 return ans
1479
1480 # self == +/-infinity -> InvalidOperation
1481 if self._isinfinity():
1482 return context._raise_error(InvalidOperation,
1483 'remainder_near(infinity, x)')
1484
1485 # other == 0 -> either InvalidOperation or DivisionUndefined
1486 if not other:
1487 if self:
1488 return context._raise_error(InvalidOperation,
1489 'remainder_near(x, 0)')
1490 else:
1491 return context._raise_error(DivisionUndefined,
1492 'remainder_near(0, 0)')
1493
1494 # other = +/-infinity -> remainder = self
1495 if other._isinfinity():
1496 ans = Decimal(self)
1497 return ans._fix(context)
1498
1499 # self = 0 -> remainder = self, with ideal exponent
1500 ideal_exponent = min(self._exp, other._exp)
1501 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001502 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001503 return ans._fix(context)
1504
1505 # catch most cases of large or small quotient
1506 expdiff = self.adjusted() - other.adjusted()
1507 if expdiff >= context.prec + 1:
1508 # expdiff >= prec+1 => abs(self/other) > 10**prec
1509 return context._raise_error(DivisionImpossible)
1510 if expdiff <= -2:
1511 # expdiff <= -2 => abs(self/other) < 0.1
1512 ans = self._rescale(ideal_exponent, context.rounding)
1513 return ans._fix(context)
1514
1515 # adjust both arguments to have the same exponent, then divide
1516 op1 = _WorkRep(self)
1517 op2 = _WorkRep(other)
1518 if op1.exp >= op2.exp:
1519 op1.int *= 10**(op1.exp - op2.exp)
1520 else:
1521 op2.int *= 10**(op2.exp - op1.exp)
1522 q, r = divmod(op1.int, op2.int)
1523 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1524 # 10**ideal_exponent. Apply correction to ensure that
1525 # abs(remainder) <= abs(other)/2
1526 if 2*r + (q&1) > op2.int:
1527 r -= op2.int
1528 q += 1
1529
1530 if q >= 10**context.prec:
1531 return context._raise_error(DivisionImpossible)
1532
1533 # result has same sign as self unless r is negative
1534 sign = self._sign
1535 if r < 0:
1536 sign = 1-sign
1537 r = -r
1538
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001539 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001540 return ans._fix(context)
1541
1542 def __floordiv__(self, other, context=None):
1543 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001544 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001545 if other is NotImplemented:
1546 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001547
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001548 if context is None:
1549 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001550
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001551 ans = self._check_nans(other, context)
1552 if ans:
1553 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001554
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001555 if self._isinfinity():
1556 if other._isinfinity():
1557 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001558 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001559 return _SignedInfinity[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001560
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001561 if not other:
1562 if self:
1563 return context._raise_error(DivisionByZero, 'x // 0',
1564 self._sign ^ other._sign)
1565 else:
1566 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001567
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001568 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001569
1570 def __rfloordiv__(self, other, context=None):
1571 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001572 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001573 if other is NotImplemented:
1574 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001575 return other.__floordiv__(self, context=context)
1576
1577 def __float__(self):
1578 """Float representation."""
1579 return float(str(self))
1580
1581 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001582 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001583 if self._is_special:
1584 if self._isnan():
Mark Dickinson825fce32009-09-07 18:08:12 +00001585 raise ValueError("Cannot convert NaN to integer")
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001586 elif self._isinfinity():
Mark Dickinson825fce32009-09-07 18:08:12 +00001587 raise OverflowError("Cannot convert infinity to integer")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001588 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001589 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001590 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001591 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001592 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001593
Christian Heimes969fe572008-01-25 11:23:10 +00001594 __trunc__ = __int__
1595
Christian Heimes0bd4e112008-02-12 22:59:25 +00001596 def real(self):
1597 return self
Mark Dickinson315a20a2009-01-04 21:34:18 +00001598 real = property(real)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001599
Christian Heimes0bd4e112008-02-12 22:59:25 +00001600 def imag(self):
1601 return Decimal(0)
Mark Dickinson315a20a2009-01-04 21:34:18 +00001602 imag = property(imag)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001603
1604 def conjugate(self):
1605 return self
1606
1607 def __complex__(self):
1608 return complex(float(self))
1609
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001610 def _fix_nan(self, context):
1611 """Decapitate the payload of a NaN to fit the context"""
1612 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001613
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001614 # maximum length of payload is precision if _clamp=0,
1615 # precision-1 if _clamp=1.
1616 max_payload_len = context.prec - context._clamp
1617 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001618 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1619 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001620 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001621
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001622 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001623 """Round if it is necessary to keep self within prec precision.
1624
1625 Rounds and fixes the exponent. Does not raise on a sNaN.
1626
1627 Arguments:
1628 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001629 context - context used.
1630 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001631
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001632 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001633 if self._isnan():
1634 # decapitate payload if necessary
1635 return self._fix_nan(context)
1636 else:
1637 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001638 return Decimal(self)
1639
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001640 # if self is zero then exponent should be between Etiny and
1641 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1642 Etiny = context.Etiny()
1643 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001644 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001645 exp_max = [context.Emax, Etop][context._clamp]
1646 new_exp = min(max(self._exp, Etiny), exp_max)
1647 if new_exp != self._exp:
1648 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001649 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001650 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001651 return Decimal(self)
1652
1653 # exp_min is the smallest allowable exponent of the result,
1654 # equal to max(self.adjusted()-context.prec+1, Etiny)
1655 exp_min = len(self._int) + self._exp - context.prec
1656 if exp_min > Etop:
1657 # overflow: exp_min > Etop iff self.adjusted() > Emax
1658 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001659 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001660 return context._raise_error(Overflow, 'above Emax', self._sign)
1661 self_is_subnormal = exp_min < Etiny
1662 if self_is_subnormal:
1663 context._raise_error(Subnormal)
1664 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001665
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001666 # round if self has too many digits
1667 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001668 context._raise_error(Rounded)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001669 digits = len(self._int) + self._exp - exp_min
1670 if digits < 0:
1671 self = _dec_from_triple(self._sign, '1', exp_min-1)
1672 digits = 0
1673 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1674 changed = this_function(digits)
1675 coeff = self._int[:digits] or '0'
1676 if changed == 1:
1677 coeff = str(int(coeff)+1)
1678 ans = _dec_from_triple(self._sign, coeff, exp_min)
1679
1680 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001681 context._raise_error(Inexact)
1682 if self_is_subnormal:
1683 context._raise_error(Underflow)
1684 if not ans:
1685 # raise Clamped on underflow to 0
1686 context._raise_error(Clamped)
1687 elif len(ans._int) == context.prec+1:
1688 # we get here only if rescaling rounds the
1689 # cofficient up to exactly 10**context.prec
1690 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001691 ans = _dec_from_triple(ans._sign,
1692 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001693 else:
1694 # Inexact and Rounded have already been raised
1695 ans = context._raise_error(Overflow, 'above Emax',
1696 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001697 return ans
1698
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001699 # fold down if _clamp == 1 and self has too few digits
1700 if context._clamp == 1 and self._exp > Etop:
1701 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001702 self_padded = self._int + '0'*(self._exp - Etop)
1703 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001704
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001705 # here self was representable to begin with; return unchanged
1706 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001707
1708 _pick_rounding_function = {}
1709
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001710 # for each of the rounding functions below:
1711 # self is a finite, nonzero Decimal
1712 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001713 #
1714 # each function returns either -1, 0, or 1, as follows:
1715 # 1 indicates that self should be rounded up (away from zero)
1716 # 0 indicates that self should be truncated, and that all the
1717 # digits to be truncated are zeros (so the value is unchanged)
1718 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001719
1720 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001721 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001722 if _all_zeros(self._int, prec):
1723 return 0
1724 else:
1725 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001726
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001727 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001728 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001729 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001730
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001731 def _round_half_up(self, prec):
1732 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001733 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001734 return 1
1735 elif _all_zeros(self._int, prec):
1736 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001737 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001738 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001739
1740 def _round_half_down(self, prec):
1741 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001742 if _exact_half(self._int, prec):
1743 return -1
1744 else:
1745 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001746
1747 def _round_half_even(self, prec):
1748 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001749 if _exact_half(self._int, prec) and \
1750 (prec == 0 or self._int[prec-1] in '02468'):
1751 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001752 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001753 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001754
1755 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001756 """Rounds up (not away from 0 if negative.)"""
1757 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001758 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001759 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001760 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001761
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001762 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001763 """Rounds down (not towards 0 if negative)"""
1764 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001765 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001766 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001767 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001768
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001769 def _round_05up(self, prec):
1770 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001771 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001772 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001773 else:
1774 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001775
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001776 def __round__(self, n=None):
1777 """Round self to the nearest integer, or to a given precision.
1778
1779 If only one argument is supplied, round a finite Decimal
1780 instance self to the nearest integer. If self is infinite or
1781 a NaN then a Python exception is raised. If self is finite
1782 and lies exactly halfway between two integers then it is
1783 rounded to the integer with even last digit.
1784
1785 >>> round(Decimal('123.456'))
1786 123
1787 >>> round(Decimal('-456.789'))
1788 -457
1789 >>> round(Decimal('-3.0'))
1790 -3
1791 >>> round(Decimal('2.5'))
1792 2
1793 >>> round(Decimal('3.5'))
1794 4
1795 >>> round(Decimal('Inf'))
1796 Traceback (most recent call last):
1797 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001798 OverflowError: cannot round an infinity
1799 >>> round(Decimal('NaN'))
1800 Traceback (most recent call last):
1801 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001802 ValueError: cannot round a NaN
1803
1804 If a second argument n is supplied, self is rounded to n
1805 decimal places using the rounding mode for the current
1806 context.
1807
1808 For an integer n, round(self, -n) is exactly equivalent to
1809 self.quantize(Decimal('1En')).
1810
1811 >>> round(Decimal('123.456'), 0)
1812 Decimal('123')
1813 >>> round(Decimal('123.456'), 2)
1814 Decimal('123.46')
1815 >>> round(Decimal('123.456'), -2)
1816 Decimal('1E+2')
1817 >>> round(Decimal('-Infinity'), 37)
1818 Decimal('NaN')
1819 >>> round(Decimal('sNaN123'), 0)
1820 Decimal('NaN123')
1821
1822 """
1823 if n is not None:
1824 # two-argument form: use the equivalent quantize call
1825 if not isinstance(n, int):
1826 raise TypeError('Second argument to round should be integral')
1827 exp = _dec_from_triple(0, '1', -n)
1828 return self.quantize(exp)
1829
1830 # one-argument form
1831 if self._is_special:
1832 if self.is_nan():
1833 raise ValueError("cannot round a NaN")
1834 else:
1835 raise OverflowError("cannot round an infinity")
1836 return int(self._rescale(0, ROUND_HALF_EVEN))
1837
1838 def __floor__(self):
1839 """Return the floor of self, as an integer.
1840
1841 For a finite Decimal instance self, return the greatest
1842 integer n such that n <= self. If self is infinite or a NaN
1843 then a Python exception is raised.
1844
1845 """
1846 if self._is_special:
1847 if self.is_nan():
1848 raise ValueError("cannot round a NaN")
1849 else:
1850 raise OverflowError("cannot round an infinity")
1851 return int(self._rescale(0, ROUND_FLOOR))
1852
1853 def __ceil__(self):
1854 """Return the ceiling of self, as an integer.
1855
1856 For a finite Decimal instance self, return the least integer n
1857 such that n >= self. If self is infinite or a NaN then a
1858 Python exception is raised.
1859
1860 """
1861 if self._is_special:
1862 if self.is_nan():
1863 raise ValueError("cannot round a NaN")
1864 else:
1865 raise OverflowError("cannot round an infinity")
1866 return int(self._rescale(0, ROUND_CEILING))
1867
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001868 def fma(self, other, third, context=None):
1869 """Fused multiply-add.
1870
1871 Returns self*other+third with no rounding of the intermediate
1872 product self*other.
1873
1874 self and other are multiplied together, with no rounding of
1875 the result. The third operand is then added to the result,
1876 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001877 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001878
1879 other = _convert_other(other, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001880
1881 # compute product; raise InvalidOperation if either operand is
1882 # a signaling NaN or if the product is zero times infinity.
1883 if self._is_special or other._is_special:
1884 if context is None:
1885 context = getcontext()
1886 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001887 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001888 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001889 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001890 if self._exp == 'n':
1891 product = self
1892 elif other._exp == 'n':
1893 product = other
1894 elif self._exp == 'F':
1895 if not other:
1896 return context._raise_error(InvalidOperation,
1897 'INF * 0 in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001898 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001899 elif other._exp == 'F':
1900 if not self:
1901 return context._raise_error(InvalidOperation,
1902 '0 * INF in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001903 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001904 else:
1905 product = _dec_from_triple(self._sign ^ other._sign,
1906 str(int(self._int) * int(other._int)),
1907 self._exp + other._exp)
1908
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001909 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001910 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001911
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001912 def _power_modulo(self, other, modulo, context=None):
1913 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001914
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001915 # if can't convert other and modulo to Decimal, raise
1916 # TypeError; there's no point returning NotImplemented (no
1917 # equivalent of __rpow__ for three argument pow)
1918 other = _convert_other(other, raiseit=True)
1919 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001920
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001921 if context is None:
1922 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001923
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001924 # deal with NaNs: if there are any sNaNs then first one wins,
1925 # (i.e. behaviour for NaNs is identical to that of fma)
1926 self_is_nan = self._isnan()
1927 other_is_nan = other._isnan()
1928 modulo_is_nan = modulo._isnan()
1929 if self_is_nan or other_is_nan or modulo_is_nan:
1930 if self_is_nan == 2:
1931 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001932 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001933 if other_is_nan == 2:
1934 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001935 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001936 if modulo_is_nan == 2:
1937 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001938 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001939 if self_is_nan:
1940 return self._fix_nan(context)
1941 if other_is_nan:
1942 return other._fix_nan(context)
1943 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001944
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001945 # check inputs: we apply same restrictions as Python's pow()
1946 if not (self._isinteger() and
1947 other._isinteger() and
1948 modulo._isinteger()):
1949 return context._raise_error(InvalidOperation,
1950 'pow() 3rd argument not allowed '
1951 'unless all arguments are integers')
1952 if other < 0:
1953 return context._raise_error(InvalidOperation,
1954 'pow() 2nd argument cannot be '
1955 'negative when 3rd argument specified')
1956 if not modulo:
1957 return context._raise_error(InvalidOperation,
1958 'pow() 3rd argument cannot be 0')
1959
1960 # additional restriction for decimal: the modulus must be less
1961 # than 10**prec in absolute value
1962 if modulo.adjusted() >= context.prec:
1963 return context._raise_error(InvalidOperation,
1964 'insufficient precision: pow() 3rd '
1965 'argument must not have more than '
1966 'precision digits')
1967
1968 # define 0**0 == NaN, for consistency with two-argument pow
1969 # (even though it hurts!)
1970 if not other and not self:
1971 return context._raise_error(InvalidOperation,
1972 'at least one of pow() 1st argument '
1973 'and 2nd argument must be nonzero ;'
1974 '0**0 is not defined')
1975
1976 # compute sign of result
1977 if other._iseven():
1978 sign = 0
1979 else:
1980 sign = self._sign
1981
1982 # convert modulo to a Python integer, and self and other to
1983 # Decimal integers (i.e. force their exponents to be >= 0)
1984 modulo = abs(int(modulo))
1985 base = _WorkRep(self.to_integral_value())
1986 exponent = _WorkRep(other.to_integral_value())
1987
1988 # compute result using integer pow()
1989 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1990 for i in range(exponent.exp):
1991 base = pow(base, 10, modulo)
1992 base = pow(base, exponent.int, modulo)
1993
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001994 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001995
1996 def _power_exact(self, other, p):
1997 """Attempt to compute self**other exactly.
1998
1999 Given Decimals self and other and an integer p, attempt to
2000 compute an exact result for the power self**other, with p
2001 digits of precision. Return None if self**other is not
2002 exactly representable in p digits.
2003
2004 Assumes that elimination of special cases has already been
2005 performed: self and other must both be nonspecial; self must
2006 be positive and not numerically equal to 1; other must be
2007 nonzero. For efficiency, other._exp should not be too large,
2008 so that 10**abs(other._exp) is a feasible calculation."""
2009
2010 # In the comments below, we write x for the value of self and
2011 # y for the value of other. Write x = xc*10**xe and y =
2012 # yc*10**ye.
2013
2014 # The main purpose of this method is to identify the *failure*
2015 # of x**y to be exactly representable with as little effort as
2016 # possible. So we look for cheap and easy tests that
2017 # eliminate the possibility of x**y being exact. Only if all
2018 # these tests are passed do we go on to actually compute x**y.
2019
2020 # Here's the main idea. First normalize both x and y. We
2021 # express y as a rational m/n, with m and n relatively prime
2022 # and n>0. Then for x**y to be exactly representable (at
2023 # *any* precision), xc must be the nth power of a positive
2024 # integer and xe must be divisible by n. If m is negative
2025 # then additionally xc must be a power of either 2 or 5, hence
2026 # a power of 2**n or 5**n.
2027 #
2028 # There's a limit to how small |y| can be: if y=m/n as above
2029 # then:
2030 #
2031 # (1) if xc != 1 then for the result to be representable we
2032 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
2033 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
2034 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
2035 # representable.
2036 #
2037 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
2038 # |y| < 1/|xe| then the result is not representable.
2039 #
2040 # Note that since x is not equal to 1, at least one of (1) and
2041 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2042 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2043 #
2044 # There's also a limit to how large y can be, at least if it's
2045 # positive: the normalized result will have coefficient xc**y,
2046 # so if it's representable then xc**y < 10**p, and y <
2047 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
2048 # not exactly representable.
2049
2050 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2051 # so |y| < 1/xe and the result is not representable.
2052 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2053 # < 1/nbits(xc).
2054
2055 x = _WorkRep(self)
2056 xc, xe = x.int, x.exp
2057 while xc % 10 == 0:
2058 xc //= 10
2059 xe += 1
2060
2061 y = _WorkRep(other)
2062 yc, ye = y.int, y.exp
2063 while yc % 10 == 0:
2064 yc //= 10
2065 ye += 1
2066
2067 # case where xc == 1: result is 10**(xe*y), with xe*y
2068 # required to be an integer
2069 if xc == 1:
2070 if ye >= 0:
2071 exponent = xe*yc*10**ye
2072 else:
2073 exponent, remainder = divmod(xe*yc, 10**-ye)
2074 if remainder:
2075 return None
2076 if y.sign == 1:
2077 exponent = -exponent
2078 # if other is a nonnegative integer, use ideal exponent
2079 if other._isinteger() and other._sign == 0:
2080 ideal_exponent = self._exp*int(other)
2081 zeros = min(exponent-ideal_exponent, p-1)
2082 else:
2083 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002084 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002085
2086 # case where y is negative: xc must be either a power
2087 # of 2 or a power of 5.
2088 if y.sign == 1:
2089 last_digit = xc % 10
2090 if last_digit in (2,4,6,8):
2091 # quick test for power of 2
2092 if xc & -xc != xc:
2093 return None
2094 # now xc is a power of 2; e is its exponent
2095 e = _nbits(xc)-1
2096 # find e*y and xe*y; both must be integers
2097 if ye >= 0:
2098 y_as_int = yc*10**ye
2099 e = e*y_as_int
2100 xe = xe*y_as_int
2101 else:
2102 ten_pow = 10**-ye
2103 e, remainder = divmod(e*yc, ten_pow)
2104 if remainder:
2105 return None
2106 xe, remainder = divmod(xe*yc, ten_pow)
2107 if remainder:
2108 return None
2109
2110 if e*65 >= p*93: # 93/65 > log(10)/log(5)
2111 return None
2112 xc = 5**e
2113
2114 elif last_digit == 5:
2115 # e >= log_5(xc) if xc is a power of 5; we have
2116 # equality all the way up to xc=5**2658
2117 e = _nbits(xc)*28//65
2118 xc, remainder = divmod(5**e, xc)
2119 if remainder:
2120 return None
2121 while xc % 5 == 0:
2122 xc //= 5
2123 e -= 1
2124 if ye >= 0:
2125 y_as_integer = yc*10**ye
2126 e = e*y_as_integer
2127 xe = xe*y_as_integer
2128 else:
2129 ten_pow = 10**-ye
2130 e, remainder = divmod(e*yc, ten_pow)
2131 if remainder:
2132 return None
2133 xe, remainder = divmod(xe*yc, ten_pow)
2134 if remainder:
2135 return None
2136 if e*3 >= p*10: # 10/3 > log(10)/log(2)
2137 return None
2138 xc = 2**e
2139 else:
2140 return None
2141
2142 if xc >= 10**p:
2143 return None
2144 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002145 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002146
2147 # now y is positive; find m and n such that y = m/n
2148 if ye >= 0:
2149 m, n = yc*10**ye, 1
2150 else:
2151 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2152 return None
2153 xc_bits = _nbits(xc)
2154 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2155 return None
2156 m, n = yc, 10**(-ye)
2157 while m % 2 == n % 2 == 0:
2158 m //= 2
2159 n //= 2
2160 while m % 5 == n % 5 == 0:
2161 m //= 5
2162 n //= 5
2163
2164 # compute nth root of xc*10**xe
2165 if n > 1:
2166 # if 1 < xc < 2**n then xc isn't an nth power
2167 if xc != 1 and xc_bits <= n:
2168 return None
2169
2170 xe, rem = divmod(xe, n)
2171 if rem != 0:
2172 return None
2173
2174 # compute nth root of xc using Newton's method
2175 a = 1 << -(-_nbits(xc)//n) # initial estimate
2176 while True:
2177 q, r = divmod(xc, a**(n-1))
2178 if a <= q:
2179 break
2180 else:
2181 a = (a*(n-1) + q)//n
2182 if not (a == q and r == 0):
2183 return None
2184 xc = a
2185
2186 # now xc*10**xe is the nth root of the original xc*10**xe
2187 # compute mth power of xc*10**xe
2188
2189 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2190 # 10**p and the result is not representable.
2191 if xc > 1 and m > p*100//_log10_lb(xc):
2192 return None
2193 xc = xc**m
2194 xe *= m
2195 if xc > 10**p:
2196 return None
2197
2198 # by this point the result *is* exactly representable
2199 # adjust the exponent to get as close as possible to the ideal
2200 # exponent, if necessary
2201 str_xc = str(xc)
2202 if other._isinteger() and other._sign == 0:
2203 ideal_exponent = self._exp*int(other)
2204 zeros = min(xe-ideal_exponent, p-len(str_xc))
2205 else:
2206 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002207 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002208
2209 def __pow__(self, other, modulo=None, context=None):
2210 """Return self ** other [ % modulo].
2211
2212 With two arguments, compute self**other.
2213
2214 With three arguments, compute (self**other) % modulo. For the
2215 three argument form, the following restrictions on the
2216 arguments hold:
2217
2218 - all three arguments must be integral
2219 - other must be nonnegative
2220 - either self or other (or both) must be nonzero
2221 - modulo must be nonzero and must have at most p digits,
2222 where p is the context precision.
2223
2224 If any of these restrictions is violated the InvalidOperation
2225 flag is raised.
2226
2227 The result of pow(self, other, modulo) is identical to the
2228 result that would be obtained by computing (self**other) %
2229 modulo with unbounded precision, but is computed more
2230 efficiently. It is always exact.
2231 """
2232
2233 if modulo is not None:
2234 return self._power_modulo(other, modulo, context)
2235
2236 other = _convert_other(other)
2237 if other is NotImplemented:
2238 return other
2239
2240 if context is None:
2241 context = getcontext()
2242
2243 # either argument is a NaN => result is NaN
2244 ans = self._check_nans(other, context)
2245 if ans:
2246 return ans
2247
2248 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2249 if not other:
2250 if not self:
2251 return context._raise_error(InvalidOperation, '0 ** 0')
2252 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002253 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002254
2255 # result has sign 1 iff self._sign is 1 and other is an odd integer
2256 result_sign = 0
2257 if self._sign == 1:
2258 if other._isinteger():
2259 if not other._iseven():
2260 result_sign = 1
2261 else:
2262 # -ve**noninteger = NaN
2263 # (-0)**noninteger = 0**noninteger
2264 if self:
2265 return context._raise_error(InvalidOperation,
2266 'x ** y with x negative and y not an integer')
2267 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002268 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002269
2270 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2271 if not self:
2272 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002273 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002274 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002275 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002276
2277 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002278 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002279 if other._sign == 0:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002280 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002281 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002282 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002283
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002284 # 1**other = 1, but the choice of exponent and the flags
2285 # depend on the exponent of self, and on whether other is a
2286 # positive integer, a negative integer, or neither
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002287 if self == _One:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002288 if other._isinteger():
2289 # exp = max(self._exp*max(int(other), 0),
2290 # 1-context.prec) but evaluating int(other) directly
2291 # is dangerous until we know other is small (other
2292 # could be 1e999999999)
2293 if other._sign == 1:
2294 multiplier = 0
2295 elif other > context.prec:
2296 multiplier = context.prec
2297 else:
2298 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002299
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002300 exp = self._exp * multiplier
2301 if exp < 1-context.prec:
2302 exp = 1-context.prec
2303 context._raise_error(Rounded)
2304 else:
2305 context._raise_error(Inexact)
2306 context._raise_error(Rounded)
2307 exp = 1-context.prec
2308
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002309 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002310
2311 # compute adjusted exponent of self
2312 self_adj = self.adjusted()
2313
2314 # self ** infinity is infinity if self > 1, 0 if self < 1
2315 # self ** -infinity is infinity if self < 1, 0 if self > 1
2316 if other._isinfinity():
2317 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002318 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002319 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002320 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002321
2322 # from here on, the result always goes through the call
2323 # to _fix at the end of this function.
2324 ans = None
2325
2326 # crude test to catch cases of extreme overflow/underflow. If
2327 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2328 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2329 # self**other >= 10**(Emax+1), so overflow occurs. The test
2330 # for underflow is similar.
2331 bound = self._log10_exp_bound() + other.adjusted()
2332 if (self_adj >= 0) == (other._sign == 0):
2333 # self > 1 and other +ve, or self < 1 and other -ve
2334 # possibility of overflow
2335 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002336 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002337 else:
2338 # self > 1 and other -ve, or self < 1 and other +ve
2339 # possibility of underflow to 0
2340 Etiny = context.Etiny()
2341 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002342 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002343
2344 # try for an exact result with precision +1
2345 if ans is None:
2346 ans = self._power_exact(other, context.prec + 1)
2347 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002348 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002349
2350 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2351 if ans is None:
2352 p = context.prec
2353 x = _WorkRep(self)
2354 xc, xe = x.int, x.exp
2355 y = _WorkRep(other)
2356 yc, ye = y.int, y.exp
2357 if y.sign == 1:
2358 yc = -yc
2359
2360 # compute correctly rounded result: start with precision +3,
2361 # then increase precision until result is unambiguously roundable
2362 extra = 3
2363 while True:
2364 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2365 if coeff % (5*10**(len(str(coeff))-p-1)):
2366 break
2367 extra += 3
2368
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002369 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002370
2371 # the specification says that for non-integer other we need to
2372 # raise Inexact, even when the result is actually exact. In
2373 # the same way, we need to raise Underflow here if the result
2374 # is subnormal. (The call to _fix will take care of raising
2375 # Rounded and Subnormal, as usual.)
2376 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002377 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002378 # pad with zeros up to length context.prec+1 if necessary
2379 if len(ans._int) <= context.prec:
2380 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002381 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2382 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002383 if ans.adjusted() < context.Emin:
2384 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002385
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002386 # unlike exp, ln and log10, the power function respects the
2387 # rounding mode; no need to use ROUND_HALF_EVEN here
2388 ans = ans._fix(context)
2389 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002390
2391 def __rpow__(self, other, context=None):
2392 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002393 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002394 if other is NotImplemented:
2395 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002396 return other.__pow__(self, context=context)
2397
2398 def normalize(self, context=None):
2399 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002400
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002401 if context is None:
2402 context = getcontext()
2403
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002404 if self._is_special:
2405 ans = self._check_nans(context=context)
2406 if ans:
2407 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002408
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002409 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002410 if dup._isinfinity():
2411 return dup
2412
2413 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002414 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002415 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002416 end = len(dup._int)
2417 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002418 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002419 exp += 1
2420 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002421 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002422
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002423 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002424 """Quantize self so its exponent is the same as that of exp.
2425
2426 Similar to self._rescale(exp._exp) but with error checking.
2427 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002428 exp = _convert_other(exp, raiseit=True)
2429
2430 if context is None:
2431 context = getcontext()
2432 if rounding is None:
2433 rounding = context.rounding
2434
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002435 if self._is_special or exp._is_special:
2436 ans = self._check_nans(exp, context)
2437 if ans:
2438 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002439
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002440 if exp._isinfinity() or self._isinfinity():
2441 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002442 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002443 return context._raise_error(InvalidOperation,
2444 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002445
2446 # if we're not watching exponents, do a simple rescale
2447 if not watchexp:
2448 ans = self._rescale(exp._exp, rounding)
2449 # raise Inexact and Rounded where appropriate
2450 if ans._exp > self._exp:
2451 context._raise_error(Rounded)
2452 if ans != self:
2453 context._raise_error(Inexact)
2454 return ans
2455
2456 # exp._exp should be between Etiny and Emax
2457 if not (context.Etiny() <= exp._exp <= context.Emax):
2458 return context._raise_error(InvalidOperation,
2459 'target exponent out of bounds in quantize')
2460
2461 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002462 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002463 return ans._fix(context)
2464
2465 self_adjusted = self.adjusted()
2466 if self_adjusted > context.Emax:
2467 return context._raise_error(InvalidOperation,
2468 'exponent of quantize result too large for current context')
2469 if self_adjusted - exp._exp + 1 > context.prec:
2470 return context._raise_error(InvalidOperation,
2471 'quantize result has too many digits for current context')
2472
2473 ans = self._rescale(exp._exp, rounding)
2474 if ans.adjusted() > context.Emax:
2475 return context._raise_error(InvalidOperation,
2476 'exponent of quantize result too large for current context')
2477 if len(ans._int) > context.prec:
2478 return context._raise_error(InvalidOperation,
2479 'quantize result has too many digits for current context')
2480
2481 # raise appropriate flags
2482 if ans._exp > self._exp:
2483 context._raise_error(Rounded)
2484 if ans != self:
2485 context._raise_error(Inexact)
2486 if ans and ans.adjusted() < context.Emin:
2487 context._raise_error(Subnormal)
2488
2489 # call to fix takes care of any necessary folddown
2490 ans = ans._fix(context)
2491 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002492
2493 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002494 """Return True if self and other have the same exponent; otherwise
2495 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002496
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002497 If either operand is a special value, the following rules are used:
2498 * return True if both operands are infinities
2499 * return True if both operands are NaNs
2500 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002501 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002502 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002503 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002504 return (self.is_nan() and other.is_nan() or
2505 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002506 return self._exp == other._exp
2507
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002508 def _rescale(self, exp, rounding):
2509 """Rescale self so that the exponent is exp, either by padding with zeros
2510 or by truncating digits, using the given rounding mode.
2511
2512 Specials are returned without change. This operation is
2513 quiet: it raises no flags, and uses no information from the
2514 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002515
2516 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002517 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002518 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002519 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002520 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002521 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002522 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002523
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002524 if self._exp >= exp:
2525 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002526 return _dec_from_triple(self._sign,
2527 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002528
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002529 # too many digits; round and lose data. If self.adjusted() <
2530 # exp-1, replace self by 10**(exp-1) before rounding
2531 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002532 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002533 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002534 digits = 0
2535 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002536 changed = this_function(digits)
2537 coeff = self._int[:digits] or '0'
2538 if changed == 1:
2539 coeff = str(int(coeff)+1)
2540 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002541
Christian Heimesf16baeb2008-02-29 14:57:44 +00002542 def _round(self, places, rounding):
2543 """Round a nonzero, nonspecial Decimal to a fixed number of
2544 significant figures, using the given rounding mode.
2545
2546 Infinities, NaNs and zeros are returned unaltered.
2547
2548 This operation is quiet: it raises no flags, and uses no
2549 information from the context.
2550
2551 """
2552 if places <= 0:
2553 raise ValueError("argument should be at least 1 in _round")
2554 if self._is_special or not self:
2555 return Decimal(self)
2556 ans = self._rescale(self.adjusted()+1-places, rounding)
2557 # it can happen that the rescale alters the adjusted exponent;
2558 # for example when rounding 99.97 to 3 significant figures.
2559 # When this happens we end up with an extra 0 at the end of
2560 # the number; a second rescale fixes this.
2561 if ans.adjusted() != self.adjusted():
2562 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2563 return ans
2564
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002565 def to_integral_exact(self, rounding=None, context=None):
2566 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002567
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002568 If no rounding mode is specified, take the rounding mode from
2569 the context. This method raises the Rounded and Inexact flags
2570 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002571
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002572 See also: to_integral_value, which does exactly the same as
2573 this method except that it doesn't raise Inexact or Rounded.
2574 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002575 if self._is_special:
2576 ans = self._check_nans(context=context)
2577 if ans:
2578 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002579 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002580 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002581 return Decimal(self)
2582 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002583 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002584 if context is None:
2585 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002586 if rounding is None:
2587 rounding = context.rounding
2588 context._raise_error(Rounded)
2589 ans = self._rescale(0, rounding)
2590 if ans != self:
2591 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002592 return ans
2593
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002594 def to_integral_value(self, rounding=None, context=None):
2595 """Rounds to the nearest integer, without raising inexact, rounded."""
2596 if context is None:
2597 context = getcontext()
2598 if rounding is None:
2599 rounding = context.rounding
2600 if self._is_special:
2601 ans = self._check_nans(context=context)
2602 if ans:
2603 return ans
2604 return Decimal(self)
2605 if self._exp >= 0:
2606 return Decimal(self)
2607 else:
2608 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002609
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002610 # the method name changed, but we provide also the old one, for compatibility
2611 to_integral = to_integral_value
2612
2613 def sqrt(self, context=None):
2614 """Return the square root of self."""
Christian Heimes0348fb62008-03-26 12:55:56 +00002615 if context is None:
2616 context = getcontext()
2617
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002618 if self._is_special:
2619 ans = self._check_nans(context=context)
2620 if ans:
2621 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002622
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002623 if self._isinfinity() and self._sign == 0:
2624 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002625
2626 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002627 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002628 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002629 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002630
2631 if self._sign == 1:
2632 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2633
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002634 # At this point self represents a positive number. Let p be
2635 # the desired precision and express self in the form c*100**e
2636 # with c a positive real number and e an integer, c and e
2637 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2638 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2639 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2640 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2641 # the closest integer to sqrt(c) with the even integer chosen
2642 # in the case of a tie.
2643 #
2644 # To ensure correct rounding in all cases, we use the
2645 # following trick: we compute the square root to an extra
2646 # place (precision p+1 instead of precision p), rounding down.
2647 # Then, if the result is inexact and its last digit is 0 or 5,
2648 # we increase the last digit to 1 or 6 respectively; if it's
2649 # exact we leave the last digit alone. Now the final round to
2650 # p places (or fewer in the case of underflow) will round
2651 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002652
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002653 # use an extra digit of precision
2654 prec = context.prec+1
2655
2656 # write argument in the form c*100**e where e = self._exp//2
2657 # is the 'ideal' exponent, to be used if the square root is
2658 # exactly representable. l is the number of 'digits' of c in
2659 # base 100, so that 100**(l-1) <= c < 100**l.
2660 op = _WorkRep(self)
2661 e = op.exp >> 1
2662 if op.exp & 1:
2663 c = op.int * 10
2664 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002665 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002666 c = op.int
2667 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002668
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002669 # rescale so that c has exactly prec base 100 'digits'
2670 shift = prec-l
2671 if shift >= 0:
2672 c *= 100**shift
2673 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002674 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002675 c, remainder = divmod(c, 100**-shift)
2676 exact = not remainder
2677 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002678
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002679 # find n = floor(sqrt(c)) using Newton's method
2680 n = 10**prec
2681 while True:
2682 q = c//n
2683 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002684 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002685 else:
2686 n = n + q >> 1
2687 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002688
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002689 if exact:
2690 # result is exact; rescale to use ideal exponent e
2691 if shift >= 0:
2692 # assert n % 10**shift == 0
2693 n //= 10**shift
2694 else:
2695 n *= 10**-shift
2696 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002697 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002698 # result is not exact; fix last digit as described above
2699 if n % 5 == 0:
2700 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002701
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002702 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002703
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002704 # round, and fit to current context
2705 context = context._shallow_copy()
2706 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002707 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002708 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002709
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002710 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002711
2712 def max(self, other, context=None):
2713 """Returns the larger value.
2714
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002715 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002716 NaN (and signals if one is sNaN). Also rounds.
2717 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002718 other = _convert_other(other, raiseit=True)
2719
2720 if context is None:
2721 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002722
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002723 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002724 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002725 # number is always returned
2726 sn = self._isnan()
2727 on = other._isnan()
2728 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002729 if on == 1 and sn == 0:
2730 return self._fix(context)
2731 if sn == 1 and on == 0:
2732 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002733 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002734
Christian Heimes77c02eb2008-02-09 02:18:51 +00002735 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002736 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002737 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002738 # then an ordering is applied:
2739 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002740 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002741 # positive sign and min returns the operand with the negative sign
2742 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002743 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002744 # the result. This is exactly the ordering used in compare_total.
2745 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002746
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002747 if c == -1:
2748 ans = other
2749 else:
2750 ans = self
2751
Christian Heimes2c181612007-12-17 20:04:13 +00002752 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002753
2754 def min(self, other, context=None):
2755 """Returns the smaller value.
2756
Guido van Rossumd8faa362007-04-27 19:54:29 +00002757 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002758 NaN (and signals if one is sNaN). Also rounds.
2759 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002760 other = _convert_other(other, raiseit=True)
2761
2762 if context is None:
2763 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002764
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002765 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002766 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002767 # number is always returned
2768 sn = self._isnan()
2769 on = other._isnan()
2770 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002771 if on == 1 and sn == 0:
2772 return self._fix(context)
2773 if sn == 1 and on == 0:
2774 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002775 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002776
Christian Heimes77c02eb2008-02-09 02:18:51 +00002777 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002778 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002779 c = self.compare_total(other)
2780
2781 if c == -1:
2782 ans = self
2783 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002784 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002785
Christian Heimes2c181612007-12-17 20:04:13 +00002786 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002787
2788 def _isinteger(self):
2789 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002790 if self._is_special:
2791 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002792 if self._exp >= 0:
2793 return True
2794 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002795 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002796
2797 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002798 """Returns True if self is even. Assumes self is an integer."""
2799 if not self or self._exp > 0:
2800 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002801 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002802
2803 def adjusted(self):
2804 """Return the adjusted exponent of self"""
2805 try:
2806 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002807 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002808 except TypeError:
2809 return 0
2810
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002811 def canonical(self, context=None):
2812 """Returns the same Decimal object.
2813
2814 As we do not have different encodings for the same number, the
2815 received object already is in its canonical form.
2816 """
2817 return self
2818
2819 def compare_signal(self, other, context=None):
2820 """Compares self to the other operand numerically.
2821
2822 It's pretty much like compare(), but all NaNs signal, with signaling
2823 NaNs taking precedence over quiet NaNs.
2824 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002825 other = _convert_other(other, raiseit = True)
2826 ans = self._compare_check_nans(other, context)
2827 if ans:
2828 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002829 return self.compare(other, context=context)
2830
2831 def compare_total(self, other):
2832 """Compares self to other using the abstract representations.
2833
2834 This is not like the standard compare, which use their numerical
2835 value. Note that a total ordering is defined for all possible abstract
2836 representations.
2837 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00002838 other = _convert_other(other, raiseit=True)
2839
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002840 # if one is negative and the other is positive, it's easy
2841 if self._sign and not other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002842 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002843 if not self._sign and other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002844 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002845 sign = self._sign
2846
2847 # let's handle both NaN types
2848 self_nan = self._isnan()
2849 other_nan = other._isnan()
2850 if self_nan or other_nan:
2851 if self_nan == other_nan:
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002852 # compare payloads as though they're integers
2853 self_key = len(self._int), self._int
2854 other_key = len(other._int), other._int
2855 if self_key < other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002856 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002857 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002858 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002859 return _NegativeOne
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002860 if self_key > other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002861 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002862 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002863 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002864 return _One
2865 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002866
2867 if sign:
2868 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002869 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002870 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002871 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002872 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002873 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002874 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002875 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002876 else:
2877 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002878 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002879 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002880 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002881 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002882 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002883 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002884 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002885
2886 if self < other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002887 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002888 if self > other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002889 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002890
2891 if self._exp < other._exp:
2892 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002893 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002894 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002895 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002896 if self._exp > other._exp:
2897 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002898 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002899 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002900 return _One
2901 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002902
2903
2904 def compare_total_mag(self, other):
2905 """Compares self to other using abstract repr., ignoring sign.
2906
2907 Like compare_total, but with operand's sign ignored and assumed to be 0.
2908 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00002909 other = _convert_other(other, raiseit=True)
2910
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002911 s = self.copy_abs()
2912 o = other.copy_abs()
2913 return s.compare_total(o)
2914
2915 def copy_abs(self):
2916 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002917 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002918
2919 def copy_negate(self):
2920 """Returns a copy with the sign inverted."""
2921 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002922 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002923 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002924 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002925
2926 def copy_sign(self, other):
2927 """Returns self with the sign of other."""
Mark Dickinson84230a12010-02-18 14:49:50 +00002928 other = _convert_other(other, raiseit=True)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002929 return _dec_from_triple(other._sign, self._int,
2930 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002931
2932 def exp(self, context=None):
2933 """Returns e ** self."""
2934
2935 if context is None:
2936 context = getcontext()
2937
2938 # exp(NaN) = NaN
2939 ans = self._check_nans(context=context)
2940 if ans:
2941 return ans
2942
2943 # exp(-Infinity) = 0
2944 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002945 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002946
2947 # exp(0) = 1
2948 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002949 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002950
2951 # exp(Infinity) = Infinity
2952 if self._isinfinity() == 1:
2953 return Decimal(self)
2954
2955 # the result is now guaranteed to be inexact (the true
2956 # mathematical result is transcendental). There's no need to
2957 # raise Rounded and Inexact here---they'll always be raised as
2958 # a result of the call to _fix.
2959 p = context.prec
2960 adj = self.adjusted()
2961
2962 # we only need to do any computation for quite a small range
2963 # of adjusted exponents---for example, -29 <= adj <= 10 for
2964 # the default context. For smaller exponent the result is
2965 # indistinguishable from 1 at the given precision, while for
2966 # larger exponent the result either overflows or underflows.
2967 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2968 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002969 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002970 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2971 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002972 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002973 elif self._sign == 0 and adj < -p:
2974 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002975 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002976 elif self._sign == 1 and adj < -p-1:
2977 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002978 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002979 # general case
2980 else:
2981 op = _WorkRep(self)
2982 c, e = op.int, op.exp
2983 if op.sign == 1:
2984 c = -c
2985
2986 # compute correctly rounded result: increase precision by
2987 # 3 digits at a time until we get an unambiguously
2988 # roundable result
2989 extra = 3
2990 while True:
2991 coeff, exp = _dexp(c, e, p+extra)
2992 if coeff % (5*10**(len(str(coeff))-p-1)):
2993 break
2994 extra += 3
2995
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002996 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002997
2998 # at this stage, ans should round correctly with *any*
2999 # rounding mode, not just with ROUND_HALF_EVEN
3000 context = context._shallow_copy()
3001 rounding = context._set_rounding(ROUND_HALF_EVEN)
3002 ans = ans._fix(context)
3003 context.rounding = rounding
3004
3005 return ans
3006
3007 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003008 """Return True if self is canonical; otherwise return False.
3009
3010 Currently, the encoding of a Decimal instance is always
3011 canonical, so this method returns True for any Decimal.
3012 """
3013 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003014
3015 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003016 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003017
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003018 A Decimal instance is considered finite if it is neither
3019 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003020 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003021 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003022
3023 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003024 """Return True if self is infinite; otherwise return False."""
3025 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003026
3027 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003028 """Return True if self is a qNaN or sNaN; otherwise return False."""
3029 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003030
3031 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003032 """Return True if self is a normal number; otherwise return False."""
3033 if self._is_special or not self:
3034 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003035 if context is None:
3036 context = getcontext()
Mark Dickinson06bb6742009-10-20 13:38:04 +00003037 return context.Emin <= self.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003038
3039 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003040 """Return True if self is a quiet NaN; otherwise return False."""
3041 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003042
3043 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003044 """Return True if self is negative; otherwise return False."""
3045 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003046
3047 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003048 """Return True if self is a signaling NaN; otherwise return False."""
3049 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003050
3051 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003052 """Return True if self is subnormal; otherwise return False."""
3053 if self._is_special or not self:
3054 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003055 if context is None:
3056 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003057 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003058
3059 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003060 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003061 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003062
3063 def _ln_exp_bound(self):
3064 """Compute a lower bound for the adjusted exponent of self.ln().
3065 In other words, compute r such that self.ln() >= 10**r. Assumes
3066 that self is finite and positive and that self != 1.
3067 """
3068
3069 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
3070 adj = self._exp + len(self._int) - 1
3071 if adj >= 1:
3072 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
3073 return len(str(adj*23//10)) - 1
3074 if adj <= -2:
3075 # argument <= 0.1
3076 return len(str((-1-adj)*23//10)) - 1
3077 op = _WorkRep(self)
3078 c, e = op.int, op.exp
3079 if adj == 0:
3080 # 1 < self < 10
3081 num = str(c-10**-e)
3082 den = str(c)
3083 return len(num) - len(den) - (num < den)
3084 # adj == -1, 0.1 <= self < 1
3085 return e + len(str(10**-e - c)) - 1
3086
3087
3088 def ln(self, context=None):
3089 """Returns the natural (base e) logarithm of self."""
3090
3091 if context is None:
3092 context = getcontext()
3093
3094 # ln(NaN) = NaN
3095 ans = self._check_nans(context=context)
3096 if ans:
3097 return ans
3098
3099 # ln(0.0) == -Infinity
3100 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003101 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003102
3103 # ln(Infinity) = Infinity
3104 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003105 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003106
3107 # ln(1.0) == 0.0
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003108 if self == _One:
3109 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003110
3111 # ln(negative) raises InvalidOperation
3112 if self._sign == 1:
3113 return context._raise_error(InvalidOperation,
3114 'ln of a negative value')
3115
3116 # result is irrational, so necessarily inexact
3117 op = _WorkRep(self)
3118 c, e = op.int, op.exp
3119 p = context.prec
3120
3121 # correctly rounded result: repeatedly increase precision by 3
3122 # until we get an unambiguously roundable result
3123 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3124 while True:
3125 coeff = _dlog(c, e, places)
3126 # assert len(str(abs(coeff)))-p >= 1
3127 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3128 break
3129 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003130 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003131
3132 context = context._shallow_copy()
3133 rounding = context._set_rounding(ROUND_HALF_EVEN)
3134 ans = ans._fix(context)
3135 context.rounding = rounding
3136 return ans
3137
3138 def _log10_exp_bound(self):
3139 """Compute a lower bound for the adjusted exponent of self.log10().
3140 In other words, find r such that self.log10() >= 10**r.
3141 Assumes that self is finite and positive and that self != 1.
3142 """
3143
3144 # For x >= 10 or x < 0.1 we only need a bound on the integer
3145 # part of log10(self), and this comes directly from the
3146 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3147 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3148 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3149
3150 adj = self._exp + len(self._int) - 1
3151 if adj >= 1:
3152 # self >= 10
3153 return len(str(adj))-1
3154 if adj <= -2:
3155 # self < 0.1
3156 return len(str(-1-adj))-1
3157 op = _WorkRep(self)
3158 c, e = op.int, op.exp
3159 if adj == 0:
3160 # 1 < self < 10
3161 num = str(c-10**-e)
3162 den = str(231*c)
3163 return len(num) - len(den) - (num < den) + 2
3164 # adj == -1, 0.1 <= self < 1
3165 num = str(10**-e-c)
3166 return len(num) + e - (num < "231") - 1
3167
3168 def log10(self, context=None):
3169 """Returns the base 10 logarithm of self."""
3170
3171 if context is None:
3172 context = getcontext()
3173
3174 # log10(NaN) = NaN
3175 ans = self._check_nans(context=context)
3176 if ans:
3177 return ans
3178
3179 # log10(0.0) == -Infinity
3180 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003181 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003182
3183 # log10(Infinity) = Infinity
3184 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003185 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003186
3187 # log10(negative or -Infinity) raises InvalidOperation
3188 if self._sign == 1:
3189 return context._raise_error(InvalidOperation,
3190 'log10 of a negative value')
3191
3192 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003193 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003194 # answer may need rounding
3195 ans = Decimal(self._exp + len(self._int) - 1)
3196 else:
3197 # result is irrational, so necessarily inexact
3198 op = _WorkRep(self)
3199 c, e = op.int, op.exp
3200 p = context.prec
3201
3202 # correctly rounded result: repeatedly increase precision
3203 # until result is unambiguously roundable
3204 places = p-self._log10_exp_bound()+2
3205 while True:
3206 coeff = _dlog10(c, e, places)
3207 # assert len(str(abs(coeff)))-p >= 1
3208 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3209 break
3210 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003211 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003212
3213 context = context._shallow_copy()
3214 rounding = context._set_rounding(ROUND_HALF_EVEN)
3215 ans = ans._fix(context)
3216 context.rounding = rounding
3217 return ans
3218
3219 def logb(self, context=None):
3220 """ Returns the exponent of the magnitude of self's MSD.
3221
3222 The result is the integer which is the exponent of the magnitude
3223 of the most significant digit of self (as though it were truncated
3224 to a single digit while maintaining the value of that digit and
3225 without limiting the resulting exponent).
3226 """
3227 # logb(NaN) = NaN
3228 ans = self._check_nans(context=context)
3229 if ans:
3230 return ans
3231
3232 if context is None:
3233 context = getcontext()
3234
3235 # logb(+/-Inf) = +Inf
3236 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003237 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003238
3239 # logb(0) = -Inf, DivisionByZero
3240 if not self:
3241 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3242
3243 # otherwise, simply return the adjusted exponent of self, as a
3244 # Decimal. Note that no attempt is made to fit the result
3245 # into the current context.
Mark Dickinson56df8872009-10-07 19:23:50 +00003246 ans = Decimal(self.adjusted())
3247 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003248
3249 def _islogical(self):
3250 """Return True if self is a logical operand.
3251
Christian Heimes679db4a2008-01-18 09:56:22 +00003252 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003253 an exponent of 0, and a coefficient whose digits must all be
3254 either 0 or 1.
3255 """
3256 if self._sign != 0 or self._exp != 0:
3257 return False
3258 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003259 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003260 return False
3261 return True
3262
3263 def _fill_logical(self, context, opa, opb):
3264 dif = context.prec - len(opa)
3265 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003266 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003267 elif dif < 0:
3268 opa = opa[-context.prec:]
3269 dif = context.prec - len(opb)
3270 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003271 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003272 elif dif < 0:
3273 opb = opb[-context.prec:]
3274 return opa, opb
3275
3276 def logical_and(self, other, context=None):
3277 """Applies an 'and' operation between self and other's digits."""
3278 if context is None:
3279 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003280
3281 other = _convert_other(other, raiseit=True)
3282
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003283 if not self._islogical() or not other._islogical():
3284 return context._raise_error(InvalidOperation)
3285
3286 # fill to context.prec
3287 (opa, opb) = self._fill_logical(context, self._int, other._int)
3288
3289 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003290 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3291 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003292
3293 def logical_invert(self, context=None):
3294 """Invert all its digits."""
3295 if context is None:
3296 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003297 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3298 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003299
3300 def logical_or(self, other, context=None):
3301 """Applies an 'or' operation between self and other's digits."""
3302 if context is None:
3303 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003304
3305 other = _convert_other(other, raiseit=True)
3306
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003307 if not self._islogical() or not other._islogical():
3308 return context._raise_error(InvalidOperation)
3309
3310 # fill to context.prec
3311 (opa, opb) = self._fill_logical(context, self._int, other._int)
3312
3313 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003314 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003315 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003316
3317 def logical_xor(self, other, context=None):
3318 """Applies an 'xor' operation between self and other's digits."""
3319 if context is None:
3320 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003321
3322 other = _convert_other(other, raiseit=True)
3323
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003324 if not self._islogical() or not other._islogical():
3325 return context._raise_error(InvalidOperation)
3326
3327 # fill to context.prec
3328 (opa, opb) = self._fill_logical(context, self._int, other._int)
3329
3330 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003331 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003332 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003333
3334 def max_mag(self, other, context=None):
3335 """Compares the values numerically with their sign ignored."""
3336 other = _convert_other(other, raiseit=True)
3337
3338 if context is None:
3339 context = getcontext()
3340
3341 if self._is_special or other._is_special:
3342 # If one operand is a quiet NaN and the other is number, then the
3343 # number is always returned
3344 sn = self._isnan()
3345 on = other._isnan()
3346 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003347 if on == 1 and sn == 0:
3348 return self._fix(context)
3349 if sn == 1 and on == 0:
3350 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003351 return self._check_nans(other, context)
3352
Christian Heimes77c02eb2008-02-09 02:18:51 +00003353 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003354 if c == 0:
3355 c = self.compare_total(other)
3356
3357 if c == -1:
3358 ans = other
3359 else:
3360 ans = self
3361
Christian Heimes2c181612007-12-17 20:04:13 +00003362 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003363
3364 def min_mag(self, other, context=None):
3365 """Compares the values numerically with their sign ignored."""
3366 other = _convert_other(other, raiseit=True)
3367
3368 if context is None:
3369 context = getcontext()
3370
3371 if self._is_special or other._is_special:
3372 # If one operand is a quiet NaN and the other is number, then the
3373 # number is always returned
3374 sn = self._isnan()
3375 on = other._isnan()
3376 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003377 if on == 1 and sn == 0:
3378 return self._fix(context)
3379 if sn == 1 and on == 0:
3380 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003381 return self._check_nans(other, context)
3382
Christian Heimes77c02eb2008-02-09 02:18:51 +00003383 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003384 if c == 0:
3385 c = self.compare_total(other)
3386
3387 if c == -1:
3388 ans = self
3389 else:
3390 ans = other
3391
Christian Heimes2c181612007-12-17 20:04:13 +00003392 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003393
3394 def next_minus(self, context=None):
3395 """Returns the largest representable number smaller than itself."""
3396 if context is None:
3397 context = getcontext()
3398
3399 ans = self._check_nans(context=context)
3400 if ans:
3401 return ans
3402
3403 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003404 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003405 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003406 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003407
3408 context = context.copy()
3409 context._set_rounding(ROUND_FLOOR)
3410 context._ignore_all_flags()
3411 new_self = self._fix(context)
3412 if new_self != self:
3413 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003414 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3415 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003416
3417 def next_plus(self, context=None):
3418 """Returns the smallest representable number larger than itself."""
3419 if context is None:
3420 context = getcontext()
3421
3422 ans = self._check_nans(context=context)
3423 if ans:
3424 return ans
3425
3426 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003427 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003428 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003429 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003430
3431 context = context.copy()
3432 context._set_rounding(ROUND_CEILING)
3433 context._ignore_all_flags()
3434 new_self = self._fix(context)
3435 if new_self != self:
3436 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003437 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3438 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003439
3440 def next_toward(self, other, context=None):
3441 """Returns the number closest to self, in the direction towards other.
3442
3443 The result is the closest representable number to self
3444 (excluding self) that is in the direction towards other,
3445 unless both have the same value. If the two operands are
3446 numerically equal, then the result is a copy of self with the
3447 sign set to be the same as the sign of other.
3448 """
3449 other = _convert_other(other, raiseit=True)
3450
3451 if context is None:
3452 context = getcontext()
3453
3454 ans = self._check_nans(other, context)
3455 if ans:
3456 return ans
3457
Christian Heimes77c02eb2008-02-09 02:18:51 +00003458 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003459 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003460 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003461
3462 if comparison == -1:
3463 ans = self.next_plus(context)
3464 else: # comparison == 1
3465 ans = self.next_minus(context)
3466
3467 # decide which flags to raise using value of ans
3468 if ans._isinfinity():
3469 context._raise_error(Overflow,
3470 'Infinite result from next_toward',
3471 ans._sign)
3472 context._raise_error(Rounded)
3473 context._raise_error(Inexact)
3474 elif ans.adjusted() < context.Emin:
3475 context._raise_error(Underflow)
3476 context._raise_error(Subnormal)
3477 context._raise_error(Rounded)
3478 context._raise_error(Inexact)
3479 # if precision == 1 then we don't raise Clamped for a
3480 # result 0E-Etiny.
3481 if not ans:
3482 context._raise_error(Clamped)
3483
3484 return ans
3485
3486 def number_class(self, context=None):
3487 """Returns an indication of the class of self.
3488
3489 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003490 sNaN
3491 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003492 -Infinity
3493 -Normal
3494 -Subnormal
3495 -Zero
3496 +Zero
3497 +Subnormal
3498 +Normal
3499 +Infinity
3500 """
3501 if self.is_snan():
3502 return "sNaN"
3503 if self.is_qnan():
3504 return "NaN"
3505 inf = self._isinfinity()
3506 if inf == 1:
3507 return "+Infinity"
3508 if inf == -1:
3509 return "-Infinity"
3510 if self.is_zero():
3511 if self._sign:
3512 return "-Zero"
3513 else:
3514 return "+Zero"
3515 if context is None:
3516 context = getcontext()
3517 if self.is_subnormal(context=context):
3518 if self._sign:
3519 return "-Subnormal"
3520 else:
3521 return "+Subnormal"
3522 # just a normal, regular, boring number, :)
3523 if self._sign:
3524 return "-Normal"
3525 else:
3526 return "+Normal"
3527
3528 def radix(self):
3529 """Just returns 10, as this is Decimal, :)"""
3530 return Decimal(10)
3531
3532 def rotate(self, other, context=None):
3533 """Returns a rotated copy of self, value-of-other times."""
3534 if context is None:
3535 context = getcontext()
3536
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003537 other = _convert_other(other, raiseit=True)
3538
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003539 ans = self._check_nans(other, context)
3540 if ans:
3541 return ans
3542
3543 if other._exp != 0:
3544 return context._raise_error(InvalidOperation)
3545 if not (-context.prec <= int(other) <= context.prec):
3546 return context._raise_error(InvalidOperation)
3547
3548 if self._isinfinity():
3549 return Decimal(self)
3550
3551 # get values, pad if necessary
3552 torot = int(other)
3553 rotdig = self._int
3554 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003555 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003556 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003557 elif topad < 0:
3558 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003559
3560 # let's rotate!
3561 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003562 return _dec_from_triple(self._sign,
3563 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003564
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003565 def scaleb(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003566 """Returns self operand after adding the second value to its exp."""
3567 if context is None:
3568 context = getcontext()
3569
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003570 other = _convert_other(other, raiseit=True)
3571
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003572 ans = self._check_nans(other, context)
3573 if ans:
3574 return ans
3575
3576 if other._exp != 0:
3577 return context._raise_error(InvalidOperation)
3578 liminf = -2 * (context.Emax + context.prec)
3579 limsup = 2 * (context.Emax + context.prec)
3580 if not (liminf <= int(other) <= limsup):
3581 return context._raise_error(InvalidOperation)
3582
3583 if self._isinfinity():
3584 return Decimal(self)
3585
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003586 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003587 d = d._fix(context)
3588 return d
3589
3590 def shift(self, other, context=None):
3591 """Returns a shifted copy of self, value-of-other times."""
3592 if context is None:
3593 context = getcontext()
3594
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003595 other = _convert_other(other, raiseit=True)
3596
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003597 ans = self._check_nans(other, context)
3598 if ans:
3599 return ans
3600
3601 if other._exp != 0:
3602 return context._raise_error(InvalidOperation)
3603 if not (-context.prec <= int(other) <= context.prec):
3604 return context._raise_error(InvalidOperation)
3605
3606 if self._isinfinity():
3607 return Decimal(self)
3608
3609 # get values, pad if necessary
3610 torot = int(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003611 rotdig = self._int
3612 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003613 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003614 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003615 elif topad < 0:
3616 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003617
3618 # let's shift!
3619 if torot < 0:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003620 shifted = rotdig[:torot]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003621 else:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003622 shifted = rotdig + '0'*torot
3623 shifted = shifted[-context.prec:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003624
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003625 return _dec_from_triple(self._sign,
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003626 shifted.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003627
Guido van Rossumd8faa362007-04-27 19:54:29 +00003628 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003629 def __reduce__(self):
3630 return (self.__class__, (str(self),))
3631
3632 def __copy__(self):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003633 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003634 return self # I'm immutable; therefore I am my own clone
3635 return self.__class__(str(self))
3636
3637 def __deepcopy__(self, memo):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003638 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003639 return self # My components are also immutable
3640 return self.__class__(str(self))
3641
Mark Dickinson79f52032009-03-17 23:12:51 +00003642 # PEP 3101 support. the _localeconv keyword argument should be
3643 # considered private: it's provided for ease of testing only.
3644 def __format__(self, specifier, context=None, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00003645 """Format a Decimal instance according to the given specifier.
3646
3647 The specifier should be a standard format specifier, with the
3648 form described in PEP 3101. Formatting types 'e', 'E', 'f',
Mark Dickinson79f52032009-03-17 23:12:51 +00003649 'F', 'g', 'G', 'n' and '%' are supported. If the formatting
3650 type is omitted it defaults to 'g' or 'G', depending on the
3651 value of context.capitals.
Christian Heimesf16baeb2008-02-29 14:57:44 +00003652 """
3653
3654 # Note: PEP 3101 says that if the type is not present then
3655 # there should be at least one digit after the decimal point.
3656 # We take the liberty of ignoring this requirement for
3657 # Decimal---it's presumably there to make sure that
3658 # format(float, '') behaves similarly to str(float).
3659 if context is None:
3660 context = getcontext()
3661
Mark Dickinson79f52032009-03-17 23:12:51 +00003662 spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003663
Mark Dickinson79f52032009-03-17 23:12:51 +00003664 # special values don't care about the type or precision
Christian Heimesf16baeb2008-02-29 14:57:44 +00003665 if self._is_special:
Mark Dickinson79f52032009-03-17 23:12:51 +00003666 sign = _format_sign(self._sign, spec)
3667 body = str(self.copy_abs())
3668 return _format_align(sign, body, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003669
3670 # a type of None defaults to 'g' or 'G', depending on context
Christian Heimesf16baeb2008-02-29 14:57:44 +00003671 if spec['type'] is None:
3672 spec['type'] = ['g', 'G'][context.capitals]
Mark Dickinson79f52032009-03-17 23:12:51 +00003673
3674 # if type is '%', adjust exponent of self accordingly
3675 if spec['type'] == '%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003676 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3677
3678 # round if necessary, taking rounding mode from the context
3679 rounding = context.rounding
3680 precision = spec['precision']
3681 if precision is not None:
3682 if spec['type'] in 'eE':
3683 self = self._round(precision+1, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003684 elif spec['type'] in 'fF%':
3685 self = self._rescale(-precision, rounding)
Mark Dickinson79f52032009-03-17 23:12:51 +00003686 elif spec['type'] in 'gG' and len(self._int) > precision:
3687 self = self._round(precision, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003688 # special case: zeros with a positive exponent can't be
3689 # represented in fixed point; rescale them to 0e0.
Mark Dickinson79f52032009-03-17 23:12:51 +00003690 if not self and self._exp > 0 and spec['type'] in 'fF%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003691 self = self._rescale(0, rounding)
3692
3693 # figure out placement of the decimal point
3694 leftdigits = self._exp + len(self._int)
Mark Dickinson79f52032009-03-17 23:12:51 +00003695 if spec['type'] in 'eE':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003696 if not self and precision is not None:
3697 dotplace = 1 - precision
3698 else:
3699 dotplace = 1
Mark Dickinson79f52032009-03-17 23:12:51 +00003700 elif spec['type'] in 'fF%':
3701 dotplace = leftdigits
Christian Heimesf16baeb2008-02-29 14:57:44 +00003702 elif spec['type'] in 'gG':
3703 if self._exp <= 0 and leftdigits > -6:
3704 dotplace = leftdigits
3705 else:
3706 dotplace = 1
3707
Mark Dickinson79f52032009-03-17 23:12:51 +00003708 # find digits before and after decimal point, and get exponent
3709 if dotplace < 0:
3710 intpart = '0'
3711 fracpart = '0'*(-dotplace) + self._int
3712 elif dotplace > len(self._int):
3713 intpart = self._int + '0'*(dotplace-len(self._int))
3714 fracpart = ''
Christian Heimesf16baeb2008-02-29 14:57:44 +00003715 else:
Mark Dickinson79f52032009-03-17 23:12:51 +00003716 intpart = self._int[:dotplace] or '0'
3717 fracpart = self._int[dotplace:]
3718 exp = leftdigits-dotplace
Christian Heimesf16baeb2008-02-29 14:57:44 +00003719
Mark Dickinson79f52032009-03-17 23:12:51 +00003720 # done with the decimal-specific stuff; hand over the rest
3721 # of the formatting to the _format_number function
3722 return _format_number(self._sign, intpart, fracpart, exp, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003723
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003724def _dec_from_triple(sign, coefficient, exponent, special=False):
3725 """Create a decimal instance directly, without any validation,
3726 normalization (e.g. removal of leading zeros) or argument
3727 conversion.
3728
3729 This function is for *internal use only*.
3730 """
3731
3732 self = object.__new__(Decimal)
3733 self._sign = sign
3734 self._int = coefficient
3735 self._exp = exponent
3736 self._is_special = special
3737
3738 return self
3739
Raymond Hettinger82417ca2009-02-03 03:54:28 +00003740# Register Decimal as a kind of Number (an abstract base class).
3741# However, do not register it as Real (because Decimals are not
3742# interoperable with floats).
3743_numbers.Number.register(Decimal)
3744
3745
Guido van Rossumd8faa362007-04-27 19:54:29 +00003746##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003747
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003748
3749# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003750rounding_functions = [name for name in Decimal.__dict__.keys()
3751 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003752for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003753 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003754 globalname = name[1:].upper()
3755 val = globals()[globalname]
3756 Decimal._pick_rounding_function[val] = name
3757
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003758del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003759
Thomas Wouters89f507f2006-12-13 04:49:30 +00003760class _ContextManager(object):
3761 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003762
Thomas Wouters89f507f2006-12-13 04:49:30 +00003763 Sets a copy of the supplied context in __enter__() and restores
3764 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003765 """
3766 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003767 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003768 def __enter__(self):
3769 self.saved_context = getcontext()
3770 setcontext(self.new_context)
3771 return self.new_context
3772 def __exit__(self, t, v, tb):
3773 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003774
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003775class Context(object):
3776 """Contains the context for a Decimal instance.
3777
3778 Contains:
3779 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003780 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003781 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003782 raised when it is caused. Otherwise, a value is
3783 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003784 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003785 (Whether or not the trap_enabler is set)
3786 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003787 Emin - Minimum exponent
3788 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003789 capitals - If 1, 1*10^1 is printed as 1E+1.
3790 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003791 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003792 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003793
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003794 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003795 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003796 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003797 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003798 _ignored_flags=None):
3799 if flags is None:
3800 flags = []
3801 if _ignored_flags is None:
3802 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003803 if not isinstance(flags, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003804 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003805 if traps is not None and not isinstance(traps, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003806 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003807 for name, val in locals().items():
3808 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003809 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003810 else:
3811 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003812 del self.self
3813
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003814 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003815 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003816 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003817 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3818 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3819 % vars(self))
3820 names = [f.__name__ for f, v in self.flags.items() if v]
3821 s.append('flags=[' + ', '.join(names) + ']')
3822 names = [t.__name__ for t, v in self.traps.items() if v]
3823 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003824 return ', '.join(s) + ')'
3825
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003826 def clear_flags(self):
3827 """Reset all flags to zero"""
3828 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003829 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003830
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003831 def _shallow_copy(self):
3832 """Returns a shallow copy from self."""
Christian Heimes2c181612007-12-17 20:04:13 +00003833 nc = Context(self.prec, self.rounding, self.traps,
3834 self.flags, self.Emin, self.Emax,
3835 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003836 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003837
3838 def copy(self):
3839 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003840 nc = Context(self.prec, self.rounding, self.traps.copy(),
Christian Heimes2c181612007-12-17 20:04:13 +00003841 self.flags.copy(), self.Emin, self.Emax,
3842 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003843 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003844 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003845
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003846 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003847 """Handles an error
3848
3849 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003850 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003851 trap_enabler is set, it reaises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00003852 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003853 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003854 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003855 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003856 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003857 return error().handle(self, *args)
3858
Raymond Hettinger86173da2008-02-01 20:38:12 +00003859 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003860 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003861 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003862 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003863
3864 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003865 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003866 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003867
3868 def _ignore_all_flags(self):
3869 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003870 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003871
3872 def _ignore_flags(self, *flags):
3873 """Ignore the flags, if they are raised"""
3874 # Do not mutate-- This way, copies of a context leave the original
3875 # alone.
3876 self._ignored_flags = (self._ignored_flags + list(flags))
3877 return list(flags)
3878
3879 def _regard_flags(self, *flags):
3880 """Stop ignoring the flags, if they are raised"""
3881 if flags and isinstance(flags[0], (tuple,list)):
3882 flags = flags[0]
3883 for flag in flags:
3884 self._ignored_flags.remove(flag)
3885
Nick Coghland1abd252008-07-15 15:46:38 +00003886 # We inherit object.__hash__, so we must deny this explicitly
3887 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003888
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003889 def Etiny(self):
3890 """Returns Etiny (= Emin - prec + 1)"""
3891 return int(self.Emin - self.prec + 1)
3892
3893 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003894 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003895 return int(self.Emax - self.prec + 1)
3896
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003897 def _set_rounding(self, type):
3898 """Sets the rounding type.
3899
3900 Sets the rounding type, and returns the current (previous)
3901 rounding type. Often used like:
3902
3903 context = context.copy()
3904 # so you don't change the calling context
3905 # if an error occurs in the middle.
3906 rounding = context._set_rounding(ROUND_UP)
3907 val = self.__sub__(other, context=context)
3908 context._set_rounding(rounding)
3909
3910 This will make it round up for that operation.
3911 """
3912 rounding = self.rounding
3913 self.rounding= type
3914 return rounding
3915
Raymond Hettingerfed52962004-07-14 15:41:57 +00003916 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00003917 """Creates a new Decimal instance but using self as context.
3918
3919 This method implements the to-number operation of the
3920 IBM Decimal specification."""
3921
3922 if isinstance(num, str) and num != num.strip():
3923 return self._raise_error(ConversionSyntax,
3924 "no trailing or leading whitespace is "
3925 "permitted.")
3926
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003927 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003928 if d._isnan() and len(d._int) > self.prec - self._clamp:
3929 return self._raise_error(ConversionSyntax,
3930 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003931 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003932
Raymond Hettinger771ed762009-01-03 19:20:32 +00003933 def create_decimal_from_float(self, f):
3934 """Creates a new Decimal instance from a float but rounding using self
3935 as the context.
3936
3937 >>> context = Context(prec=5, rounding=ROUND_DOWN)
3938 >>> context.create_decimal_from_float(3.1415926535897932)
3939 Decimal('3.1415')
3940 >>> context = Context(prec=5, traps=[Inexact])
3941 >>> context.create_decimal_from_float(3.1415926535897932)
3942 Traceback (most recent call last):
3943 ...
3944 decimal.Inexact: None
3945
3946 """
3947 d = Decimal.from_float(f) # An exact conversion
3948 return d._fix(self) # Apply the context rounding
3949
Guido van Rossumd8faa362007-04-27 19:54:29 +00003950 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003951 def abs(self, a):
3952 """Returns the absolute value of the operand.
3953
3954 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003955 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003956 the plus operation on the operand.
3957
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003958 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003959 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003960 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003961 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003962 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003963 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003964 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003965 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00003966 >>> ExtendedContext.abs(-1)
3967 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003968 """
Mark Dickinson84230a12010-02-18 14:49:50 +00003969 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003970 return a.__abs__(context=self)
3971
3972 def add(self, a, b):
3973 """Return the sum of the two operands.
3974
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003975 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003976 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003977 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003978 Decimal('1.02E+4')
Mark Dickinson84230a12010-02-18 14:49:50 +00003979 >>> ExtendedContext.add(1, Decimal(2))
3980 Decimal('3')
3981 >>> ExtendedContext.add(Decimal(8), 5)
3982 Decimal('13')
3983 >>> ExtendedContext.add(5, 5)
3984 Decimal('10')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003985 """
Mark Dickinson84230a12010-02-18 14:49:50 +00003986 a = _convert_other(a, raiseit=True)
3987 r = a.__add__(b, context=self)
3988 if r is NotImplemented:
3989 raise TypeError("Unable to convert %s to Decimal" % b)
3990 else:
3991 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003992
3993 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003994 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003995
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003996 def canonical(self, a):
3997 """Returns the same Decimal object.
3998
3999 As we do not have different encodings for the same number, the
4000 received object already is in its canonical form.
4001
4002 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004003 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004004 """
4005 return a.canonical(context=self)
4006
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004007 def compare(self, a, b):
4008 """Compares values numerically.
4009
4010 If the signs of the operands differ, a value representing each operand
4011 ('-1' if the operand is less than zero, '0' if the operand is zero or
4012 negative zero, or '1' if the operand is greater than zero) is used in
4013 place of that operand for the comparison instead of the actual
4014 operand.
4015
4016 The comparison is then effected by subtracting the second operand from
4017 the first and then returning a value according to the result of the
4018 subtraction: '-1' if the result is less than zero, '0' if the result is
4019 zero or negative zero, or '1' if the result is greater than zero.
4020
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004021 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004022 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004023 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004024 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004025 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004026 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004027 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004028 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004029 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004030 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004031 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004032 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004033 >>> ExtendedContext.compare(1, 2)
4034 Decimal('-1')
4035 >>> ExtendedContext.compare(Decimal(1), 2)
4036 Decimal('-1')
4037 >>> ExtendedContext.compare(1, Decimal(2))
4038 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004039 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004040 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004041 return a.compare(b, context=self)
4042
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004043 def compare_signal(self, a, b):
4044 """Compares the values of the two operands numerically.
4045
4046 It's pretty much like compare(), but all NaNs signal, with signaling
4047 NaNs taking precedence over quiet NaNs.
4048
4049 >>> c = ExtendedContext
4050 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004051 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004052 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004053 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004054 >>> c.flags[InvalidOperation] = 0
4055 >>> print(c.flags[InvalidOperation])
4056 0
4057 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004058 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004059 >>> print(c.flags[InvalidOperation])
4060 1
4061 >>> c.flags[InvalidOperation] = 0
4062 >>> print(c.flags[InvalidOperation])
4063 0
4064 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004065 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004066 >>> print(c.flags[InvalidOperation])
4067 1
Mark Dickinson84230a12010-02-18 14:49:50 +00004068 >>> c.compare_signal(-1, 2)
4069 Decimal('-1')
4070 >>> c.compare_signal(Decimal(-1), 2)
4071 Decimal('-1')
4072 >>> c.compare_signal(-1, Decimal(2))
4073 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004074 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004075 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004076 return a.compare_signal(b, context=self)
4077
4078 def compare_total(self, a, b):
4079 """Compares two operands using their abstract representation.
4080
4081 This is not like the standard compare, which use their numerical
4082 value. Note that a total ordering is defined for all possible abstract
4083 representations.
4084
4085 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004086 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004087 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004088 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004089 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004090 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004091 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004092 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004093 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004094 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004095 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004096 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004097 >>> ExtendedContext.compare_total(1, 2)
4098 Decimal('-1')
4099 >>> ExtendedContext.compare_total(Decimal(1), 2)
4100 Decimal('-1')
4101 >>> ExtendedContext.compare_total(1, Decimal(2))
4102 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004103 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004104 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004105 return a.compare_total(b)
4106
4107 def compare_total_mag(self, a, b):
4108 """Compares two operands using their abstract representation ignoring sign.
4109
4110 Like compare_total, but with operand's sign ignored and assumed to be 0.
4111 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004112 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004113 return a.compare_total_mag(b)
4114
4115 def copy_abs(self, a):
4116 """Returns a copy of the operand with the sign set to 0.
4117
4118 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004119 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004120 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004121 Decimal('100')
Mark Dickinson84230a12010-02-18 14:49:50 +00004122 >>> ExtendedContext.copy_abs(-1)
4123 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004124 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004125 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004126 return a.copy_abs()
4127
4128 def copy_decimal(self, a):
Mark Dickinson84230a12010-02-18 14:49:50 +00004129 """Returns a copy of the decimal object.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004130
4131 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004132 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004133 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004134 Decimal('-1.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00004135 >>> ExtendedContext.copy_decimal(1)
4136 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004137 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004138 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004139 return Decimal(a)
4140
4141 def copy_negate(self, a):
4142 """Returns a copy of the operand with the sign inverted.
4143
4144 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004145 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004146 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004147 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00004148 >>> ExtendedContext.copy_negate(1)
4149 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004150 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004151 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004152 return a.copy_negate()
4153
4154 def copy_sign(self, a, b):
4155 """Copies the second operand's sign to the first one.
4156
4157 In detail, it returns a copy of the first operand with the sign
4158 equal to the sign of the second operand.
4159
4160 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004161 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004162 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004163 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004164 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004165 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004166 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004167 Decimal('-1.50')
Mark Dickinson84230a12010-02-18 14:49:50 +00004168 >>> ExtendedContext.copy_sign(1, -2)
4169 Decimal('-1')
4170 >>> ExtendedContext.copy_sign(Decimal(1), -2)
4171 Decimal('-1')
4172 >>> ExtendedContext.copy_sign(1, Decimal(-2))
4173 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004174 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004175 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004176 return a.copy_sign(b)
4177
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004178 def divide(self, a, b):
4179 """Decimal division in a specified context.
4180
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004181 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004182 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004183 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004184 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004185 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004186 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004187 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004188 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004189 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004190 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004191 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004192 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004193 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004194 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004195 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004196 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004197 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004198 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004199 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004200 Decimal('1.20E+6')
Mark Dickinson84230a12010-02-18 14:49:50 +00004201 >>> ExtendedContext.divide(5, 5)
4202 Decimal('1')
4203 >>> ExtendedContext.divide(Decimal(5), 5)
4204 Decimal('1')
4205 >>> ExtendedContext.divide(5, Decimal(5))
4206 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004207 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004208 a = _convert_other(a, raiseit=True)
4209 r = a.__truediv__(b, context=self)
4210 if r is NotImplemented:
4211 raise TypeError("Unable to convert %s to Decimal" % b)
4212 else:
4213 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004214
4215 def divide_int(self, a, b):
4216 """Divides two numbers and returns the integer part of the result.
4217
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004218 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004219 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004220 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004221 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004222 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004223 Decimal('3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004224 >>> ExtendedContext.divide_int(10, 3)
4225 Decimal('3')
4226 >>> ExtendedContext.divide_int(Decimal(10), 3)
4227 Decimal('3')
4228 >>> ExtendedContext.divide_int(10, Decimal(3))
4229 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004230 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004231 a = _convert_other(a, raiseit=True)
4232 r = a.__floordiv__(b, context=self)
4233 if r is NotImplemented:
4234 raise TypeError("Unable to convert %s to Decimal" % b)
4235 else:
4236 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004237
4238 def divmod(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004239 """Return (a // b, a % b).
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004240
4241 >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
4242 (Decimal('2'), Decimal('2'))
4243 >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
4244 (Decimal('2'), Decimal('0'))
Mark Dickinson84230a12010-02-18 14:49:50 +00004245 >>> ExtendedContext.divmod(8, 4)
4246 (Decimal('2'), Decimal('0'))
4247 >>> ExtendedContext.divmod(Decimal(8), 4)
4248 (Decimal('2'), Decimal('0'))
4249 >>> ExtendedContext.divmod(8, Decimal(4))
4250 (Decimal('2'), Decimal('0'))
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004251 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004252 a = _convert_other(a, raiseit=True)
4253 r = a.__divmod__(b, context=self)
4254 if r is NotImplemented:
4255 raise TypeError("Unable to convert %s to Decimal" % b)
4256 else:
4257 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004258
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004259 def exp(self, a):
4260 """Returns e ** a.
4261
4262 >>> c = ExtendedContext.copy()
4263 >>> c.Emin = -999
4264 >>> c.Emax = 999
4265 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004266 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004267 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004268 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004269 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004270 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004271 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004272 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004273 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004274 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004275 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004276 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004277 >>> c.exp(10)
4278 Decimal('22026.4658')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004279 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004280 a =_convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004281 return a.exp(context=self)
4282
4283 def fma(self, a, b, c):
4284 """Returns a multiplied by b, plus c.
4285
4286 The first two operands are multiplied together, using multiply,
4287 the third operand is then added to the result of that
4288 multiplication, using add, all with only one final rounding.
4289
4290 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004291 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004292 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004293 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004294 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004295 Decimal('1.38435736E+12')
Mark Dickinson84230a12010-02-18 14:49:50 +00004296 >>> ExtendedContext.fma(1, 3, 4)
4297 Decimal('7')
4298 >>> ExtendedContext.fma(1, Decimal(3), 4)
4299 Decimal('7')
4300 >>> ExtendedContext.fma(1, 3, Decimal(4))
4301 Decimal('7')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004302 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004303 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004304 return a.fma(b, c, context=self)
4305
4306 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004307 """Return True if the operand is canonical; otherwise return False.
4308
4309 Currently, the encoding of a Decimal instance is always
4310 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004311
4312 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004313 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004314 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004315 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004316
4317 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004318 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004319
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004320 A Decimal instance is considered finite if it is neither
4321 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004322
4323 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004324 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004325 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004326 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004327 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004328 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004329 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004330 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004331 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004332 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004333 >>> ExtendedContext.is_finite(1)
4334 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004335 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004336 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004337 return a.is_finite()
4338
4339 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004340 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004341
4342 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004343 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004344 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004345 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004346 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004347 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004348 >>> ExtendedContext.is_infinite(1)
4349 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004350 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004351 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004352 return a.is_infinite()
4353
4354 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004355 """Return True if the operand is a qNaN or sNaN;
4356 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004357
4358 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004359 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004360 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004361 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004362 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004363 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004364 >>> ExtendedContext.is_nan(1)
4365 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004366 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004367 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004368 return a.is_nan()
4369
4370 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004371 """Return True if the operand is a normal number;
4372 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004373
4374 >>> c = ExtendedContext.copy()
4375 >>> c.Emin = -999
4376 >>> c.Emax = 999
4377 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004378 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004379 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004380 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004381 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004382 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004383 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004384 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004385 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004386 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004387 >>> c.is_normal(1)
4388 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004389 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004390 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004391 return a.is_normal(context=self)
4392
4393 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004394 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004395
4396 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004397 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004398 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004399 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004400 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004401 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004402 >>> ExtendedContext.is_qnan(1)
4403 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004404 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004405 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004406 return a.is_qnan()
4407
4408 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004409 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004410
4411 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004412 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004413 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004414 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004415 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004416 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004417 >>> ExtendedContext.is_signed(8)
4418 False
4419 >>> ExtendedContext.is_signed(-8)
4420 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004421 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004422 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004423 return a.is_signed()
4424
4425 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004426 """Return True if the operand is a signaling NaN;
4427 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004428
4429 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004430 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004431 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004432 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004433 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004434 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004435 >>> ExtendedContext.is_snan(1)
4436 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004437 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004438 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004439 return a.is_snan()
4440
4441 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004442 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004443
4444 >>> c = ExtendedContext.copy()
4445 >>> c.Emin = -999
4446 >>> c.Emax = 999
4447 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004448 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004449 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004450 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004451 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004452 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004453 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004454 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004455 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004456 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004457 >>> c.is_subnormal(1)
4458 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004459 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004460 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004461 return a.is_subnormal(context=self)
4462
4463 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004464 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004465
4466 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004467 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004468 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004469 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004470 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004471 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004472 >>> ExtendedContext.is_zero(1)
4473 False
4474 >>> ExtendedContext.is_zero(0)
4475 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004476 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004477 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004478 return a.is_zero()
4479
4480 def ln(self, a):
4481 """Returns the natural (base e) logarithm of the operand.
4482
4483 >>> c = ExtendedContext.copy()
4484 >>> c.Emin = -999
4485 >>> c.Emax = 999
4486 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004487 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004488 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004489 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004490 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004491 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004492 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004493 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004494 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004495 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004496 >>> c.ln(1)
4497 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004498 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004499 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004500 return a.ln(context=self)
4501
4502 def log10(self, a):
4503 """Returns the base 10 logarithm of the operand.
4504
4505 >>> c = ExtendedContext.copy()
4506 >>> c.Emin = -999
4507 >>> c.Emax = 999
4508 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004509 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004510 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004511 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004512 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004513 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004514 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004515 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004516 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004517 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004518 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004519 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004520 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004521 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004522 >>> c.log10(0)
4523 Decimal('-Infinity')
4524 >>> c.log10(1)
4525 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004526 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004527 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004528 return a.log10(context=self)
4529
4530 def logb(self, a):
4531 """ Returns the exponent of the magnitude of the operand's MSD.
4532
4533 The result is the integer which is the exponent of the magnitude
4534 of the most significant digit of the operand (as though the
4535 operand were truncated to a single digit while maintaining the
4536 value of that digit and without limiting the resulting exponent).
4537
4538 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004539 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004540 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004541 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004542 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004543 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004544 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004545 Decimal('-Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004546 >>> ExtendedContext.logb(1)
4547 Decimal('0')
4548 >>> ExtendedContext.logb(10)
4549 Decimal('1')
4550 >>> ExtendedContext.logb(100)
4551 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004552 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004553 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004554 return a.logb(context=self)
4555
4556 def logical_and(self, a, b):
4557 """Applies the logical operation 'and' between each operand's digits.
4558
4559 The operands must be both logical numbers.
4560
4561 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004562 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004563 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004564 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004565 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004566 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004567 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004568 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004569 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004570 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004571 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004572 Decimal('10')
Mark Dickinson84230a12010-02-18 14:49:50 +00004573 >>> ExtendedContext.logical_and(110, 1101)
4574 Decimal('100')
4575 >>> ExtendedContext.logical_and(Decimal(110), 1101)
4576 Decimal('100')
4577 >>> ExtendedContext.logical_and(110, Decimal(1101))
4578 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004579 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004580 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004581 return a.logical_and(b, context=self)
4582
4583 def logical_invert(self, a):
4584 """Invert all the digits in the operand.
4585
4586 The operand must be a logical number.
4587
4588 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004589 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004590 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004591 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004592 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004593 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004594 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004595 Decimal('10101010')
Mark Dickinson84230a12010-02-18 14:49:50 +00004596 >>> ExtendedContext.logical_invert(1101)
4597 Decimal('111110010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004598 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004599 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004600 return a.logical_invert(context=self)
4601
4602 def logical_or(self, a, b):
4603 """Applies the logical operation 'or' between each operand's digits.
4604
4605 The operands must be both logical numbers.
4606
4607 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004608 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004609 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004610 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004611 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004612 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004613 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004614 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004615 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004616 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004617 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004618 Decimal('1110')
Mark Dickinson84230a12010-02-18 14:49:50 +00004619 >>> ExtendedContext.logical_or(110, 1101)
4620 Decimal('1111')
4621 >>> ExtendedContext.logical_or(Decimal(110), 1101)
4622 Decimal('1111')
4623 >>> ExtendedContext.logical_or(110, Decimal(1101))
4624 Decimal('1111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004625 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004626 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004627 return a.logical_or(b, context=self)
4628
4629 def logical_xor(self, a, b):
4630 """Applies the logical operation 'xor' between each operand's digits.
4631
4632 The operands must be both logical numbers.
4633
4634 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004635 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004636 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004637 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004638 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004639 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004640 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004641 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004642 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004643 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004644 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004645 Decimal('1101')
Mark Dickinson84230a12010-02-18 14:49:50 +00004646 >>> ExtendedContext.logical_xor(110, 1101)
4647 Decimal('1011')
4648 >>> ExtendedContext.logical_xor(Decimal(110), 1101)
4649 Decimal('1011')
4650 >>> ExtendedContext.logical_xor(110, Decimal(1101))
4651 Decimal('1011')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004652 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004653 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004654 return a.logical_xor(b, context=self)
4655
Mark Dickinson84230a12010-02-18 14:49:50 +00004656 def max(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004657 """max compares two values numerically and returns the maximum.
4658
4659 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004660 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004661 operation. If they are numerically equal then the left-hand operand
4662 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004663 infinity) of the two operands is chosen as the result.
4664
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004665 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004666 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004667 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004668 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004669 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004670 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004671 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004672 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004673 >>> ExtendedContext.max(1, 2)
4674 Decimal('2')
4675 >>> ExtendedContext.max(Decimal(1), 2)
4676 Decimal('2')
4677 >>> ExtendedContext.max(1, Decimal(2))
4678 Decimal('2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004679 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004680 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004681 return a.max(b, context=self)
4682
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004683 def max_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004684 """Compares the values numerically with their sign ignored.
4685
4686 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
4687 Decimal('7')
4688 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
4689 Decimal('-10')
4690 >>> ExtendedContext.max_mag(1, -2)
4691 Decimal('-2')
4692 >>> ExtendedContext.max_mag(Decimal(1), -2)
4693 Decimal('-2')
4694 >>> ExtendedContext.max_mag(1, Decimal(-2))
4695 Decimal('-2')
4696 """
4697 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004698 return a.max_mag(b, context=self)
4699
Mark Dickinson84230a12010-02-18 14:49:50 +00004700 def min(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004701 """min compares two values numerically and returns the minimum.
4702
4703 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004704 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004705 operation. If they are numerically equal then the left-hand operand
4706 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004707 infinity) of the two operands is chosen as the result.
4708
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004709 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004710 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004711 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004712 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004713 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004714 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004715 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004716 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004717 >>> ExtendedContext.min(1, 2)
4718 Decimal('1')
4719 >>> ExtendedContext.min(Decimal(1), 2)
4720 Decimal('1')
4721 >>> ExtendedContext.min(1, Decimal(29))
4722 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004723 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004724 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004725 return a.min(b, context=self)
4726
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004727 def min_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004728 """Compares the values numerically with their sign ignored.
4729
4730 >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
4731 Decimal('-2')
4732 >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
4733 Decimal('-3')
4734 >>> ExtendedContext.min_mag(1, -2)
4735 Decimal('1')
4736 >>> ExtendedContext.min_mag(Decimal(1), -2)
4737 Decimal('1')
4738 >>> ExtendedContext.min_mag(1, Decimal(-2))
4739 Decimal('1')
4740 """
4741 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004742 return a.min_mag(b, context=self)
4743
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004744 def minus(self, a):
4745 """Minus corresponds to unary prefix minus in Python.
4746
4747 The operation is evaluated using the same rules as subtract; the
4748 operation minus(a) is calculated as subtract('0', a) where the '0'
4749 has the same exponent as the operand.
4750
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004751 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004752 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004753 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004754 Decimal('1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004755 >>> ExtendedContext.minus(1)
4756 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004757 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004758 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004759 return a.__neg__(context=self)
4760
4761 def multiply(self, a, b):
4762 """multiply multiplies two operands.
4763
4764 If either operand is a special value then the general rules apply.
Mark Dickinson84230a12010-02-18 14:49:50 +00004765 Otherwise, the operands are multiplied together
4766 ('long multiplication'), resulting in a number which may be as long as
4767 the sum of the lengths of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004768
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004769 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004770 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004771 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004772 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004773 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004774 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004775 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004776 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004777 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004778 Decimal('4.28135971E+11')
Mark Dickinson84230a12010-02-18 14:49:50 +00004779 >>> ExtendedContext.multiply(7, 7)
4780 Decimal('49')
4781 >>> ExtendedContext.multiply(Decimal(7), 7)
4782 Decimal('49')
4783 >>> ExtendedContext.multiply(7, Decimal(7))
4784 Decimal('49')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004785 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004786 a = _convert_other(a, raiseit=True)
4787 r = a.__mul__(b, context=self)
4788 if r is NotImplemented:
4789 raise TypeError("Unable to convert %s to Decimal" % b)
4790 else:
4791 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004792
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004793 def next_minus(self, a):
4794 """Returns the largest representable number smaller than a.
4795
4796 >>> c = ExtendedContext.copy()
4797 >>> c.Emin = -999
4798 >>> c.Emax = 999
4799 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004800 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004801 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004802 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004803 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004804 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004805 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004806 Decimal('9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00004807 >>> c.next_minus(1)
4808 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004809 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004810 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004811 return a.next_minus(context=self)
4812
4813 def next_plus(self, a):
4814 """Returns the smallest representable number larger than a.
4815
4816 >>> c = ExtendedContext.copy()
4817 >>> c.Emin = -999
4818 >>> c.Emax = 999
4819 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004820 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004821 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004822 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004823 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004824 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004825 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004826 Decimal('-9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00004827 >>> c.next_plus(1)
4828 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004829 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004830 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004831 return a.next_plus(context=self)
4832
4833 def next_toward(self, a, b):
4834 """Returns the number closest to a, in direction towards b.
4835
4836 The result is the closest representable number from the first
4837 operand (but not the first operand) that is in the direction
4838 towards the second operand, unless the operands have the same
4839 value.
4840
4841 >>> c = ExtendedContext.copy()
4842 >>> c.Emin = -999
4843 >>> c.Emax = 999
4844 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004845 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004846 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004847 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004848 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004849 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004850 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004851 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004852 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004853 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004854 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004855 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004856 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004857 Decimal('-0.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00004858 >>> c.next_toward(0, 1)
4859 Decimal('1E-1007')
4860 >>> c.next_toward(Decimal(0), 1)
4861 Decimal('1E-1007')
4862 >>> c.next_toward(0, Decimal(1))
4863 Decimal('1E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004864 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004865 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004866 return a.next_toward(b, context=self)
4867
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004868 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004869 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004870
4871 Essentially a plus operation with all trailing zeros removed from the
4872 result.
4873
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004874 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004875 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004876 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004877 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004878 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004879 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004880 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004881 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004882 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004883 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004884 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004885 Decimal('0')
Mark Dickinson84230a12010-02-18 14:49:50 +00004886 >>> ExtendedContext.normalize(6)
4887 Decimal('6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004888 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004889 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004890 return a.normalize(context=self)
4891
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004892 def number_class(self, a):
4893 """Returns an indication of the class of the operand.
4894
4895 The class is one of the following strings:
4896 -sNaN
4897 -NaN
4898 -Infinity
4899 -Normal
4900 -Subnormal
4901 -Zero
4902 +Zero
4903 +Subnormal
4904 +Normal
4905 +Infinity
4906
4907 >>> c = Context(ExtendedContext)
4908 >>> c.Emin = -999
4909 >>> c.Emax = 999
4910 >>> c.number_class(Decimal('Infinity'))
4911 '+Infinity'
4912 >>> c.number_class(Decimal('1E-10'))
4913 '+Normal'
4914 >>> c.number_class(Decimal('2.50'))
4915 '+Normal'
4916 >>> c.number_class(Decimal('0.1E-999'))
4917 '+Subnormal'
4918 >>> c.number_class(Decimal('0'))
4919 '+Zero'
4920 >>> c.number_class(Decimal('-0'))
4921 '-Zero'
4922 >>> c.number_class(Decimal('-0.1E-999'))
4923 '-Subnormal'
4924 >>> c.number_class(Decimal('-1E-10'))
4925 '-Normal'
4926 >>> c.number_class(Decimal('-2.50'))
4927 '-Normal'
4928 >>> c.number_class(Decimal('-Infinity'))
4929 '-Infinity'
4930 >>> c.number_class(Decimal('NaN'))
4931 'NaN'
4932 >>> c.number_class(Decimal('-NaN'))
4933 'NaN'
4934 >>> c.number_class(Decimal('sNaN'))
4935 'sNaN'
Mark Dickinson84230a12010-02-18 14:49:50 +00004936 >>> c.number_class(123)
4937 '+Normal'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004938 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004939 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004940 return a.number_class(context=self)
4941
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004942 def plus(self, a):
4943 """Plus corresponds to unary prefix plus in Python.
4944
4945 The operation is evaluated using the same rules as add; the
4946 operation plus(a) is calculated as add('0', a) where the '0'
4947 has the same exponent as the operand.
4948
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004949 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004950 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004951 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004952 Decimal('-1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004953 >>> ExtendedContext.plus(-1)
4954 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004955 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004956 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004957 return a.__pos__(context=self)
4958
4959 def power(self, a, b, modulo=None):
4960 """Raises a to the power of b, to modulo if given.
4961
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004962 With two arguments, compute a**b. If a is negative then b
4963 must be integral. The result will be inexact unless b is
4964 integral and the result is finite and can be expressed exactly
4965 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004966
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004967 With three arguments, compute (a**b) % modulo. For the
4968 three argument form, the following restrictions on the
4969 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004970
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004971 - all three arguments must be integral
4972 - b must be nonnegative
4973 - at least one of a or b must be nonzero
4974 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004975
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004976 The result of pow(a, b, modulo) is identical to the result
4977 that would be obtained by computing (a**b) % modulo with
4978 unbounded precision, but is computed more efficiently. It is
4979 always exact.
4980
4981 >>> c = ExtendedContext.copy()
4982 >>> c.Emin = -999
4983 >>> c.Emax = 999
4984 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004985 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004986 >>> c.power(Decimal('-2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004987 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004988 >>> c.power(Decimal('2'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004989 Decimal('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004990 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004991 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004992 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004993 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004994 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004995 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004996 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004997 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004998 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004999 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005000 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005001 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005002 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005003 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005004 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005005 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005006 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005007 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005008 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005009 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005010
5011 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005012 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005013 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005014 Decimal('-11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005015 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005016 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005017 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005018 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005019 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005020 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005021 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005022 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005023 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005024 Decimal('1')
Mark Dickinson84230a12010-02-18 14:49:50 +00005025 >>> ExtendedContext.power(7, 7)
5026 Decimal('823543')
5027 >>> ExtendedContext.power(Decimal(7), 7)
5028 Decimal('823543')
5029 >>> ExtendedContext.power(7, Decimal(7), 2)
5030 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005031 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005032 a = _convert_other(a, raiseit=True)
5033 r = a.__pow__(b, modulo, context=self)
5034 if r is NotImplemented:
5035 raise TypeError("Unable to convert %s to Decimal" % b)
5036 else:
5037 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005038
5039 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005040 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005041
5042 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00005043 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005044 exponent is being increased), multiplied by a positive power of ten (if
5045 the exponent is being decreased), or is unchanged (if the exponent is
5046 already equal to that of the right-hand operand).
5047
5048 Unlike other operations, if the length of the coefficient after the
5049 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00005050 operation condition is raised. This guarantees that, unless there is
5051 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005052 equal to that of the right-hand operand.
5053
5054 Also unlike other operations, quantize will never raise Underflow, even
5055 if the result is subnormal and inexact.
5056
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005057 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005058 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005059 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005060 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005061 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005062 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005063 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005064 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005065 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005066 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005067 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005068 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005069 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005070 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005071 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005072 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005073 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005074 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005075 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005076 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005077 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005078 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005079 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005080 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005081 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005082 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005083 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005084 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005085 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005086 Decimal('2E+2')
Mark Dickinson84230a12010-02-18 14:49:50 +00005087 >>> ExtendedContext.quantize(1, 2)
5088 Decimal('1')
5089 >>> ExtendedContext.quantize(Decimal(1), 2)
5090 Decimal('1')
5091 >>> ExtendedContext.quantize(1, Decimal(2))
5092 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005093 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005094 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005095 return a.quantize(b, context=self)
5096
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005097 def radix(self):
5098 """Just returns 10, as this is Decimal, :)
5099
5100 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005101 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005102 """
5103 return Decimal(10)
5104
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005105 def remainder(self, a, b):
5106 """Returns the remainder from integer division.
5107
5108 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00005109 calculating integer division as described for divide-integer, rounded
5110 to precision digits if necessary. The sign of the result, if
5111 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005112
5113 This operation will fail under the same conditions as integer division
5114 (that is, if integer division on the same two operands would fail, the
5115 remainder cannot be calculated).
5116
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005117 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005118 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005119 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005120 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005121 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005122 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005123 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005124 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005125 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005126 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005127 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005128 Decimal('1.0')
Mark Dickinson84230a12010-02-18 14:49:50 +00005129 >>> ExtendedContext.remainder(22, 6)
5130 Decimal('4')
5131 >>> ExtendedContext.remainder(Decimal(22), 6)
5132 Decimal('4')
5133 >>> ExtendedContext.remainder(22, Decimal(6))
5134 Decimal('4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005135 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005136 a = _convert_other(a, raiseit=True)
5137 r = a.__mod__(b, context=self)
5138 if r is NotImplemented:
5139 raise TypeError("Unable to convert %s to Decimal" % b)
5140 else:
5141 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005142
5143 def remainder_near(self, a, b):
5144 """Returns to be "a - b * n", where n is the integer nearest the exact
5145 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00005146 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005147 sign of a.
5148
5149 This operation will fail under the same conditions as integer division
5150 (that is, if integer division on the same two operands would fail, the
5151 remainder cannot be calculated).
5152
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005153 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005154 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005155 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005156 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005157 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005158 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005159 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005160 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005161 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005162 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005163 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005164 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005165 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005166 Decimal('-0.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005167 >>> ExtendedContext.remainder_near(3, 11)
5168 Decimal('3')
5169 >>> ExtendedContext.remainder_near(Decimal(3), 11)
5170 Decimal('3')
5171 >>> ExtendedContext.remainder_near(3, Decimal(11))
5172 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005173 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005174 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005175 return a.remainder_near(b, context=self)
5176
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005177 def rotate(self, a, b):
5178 """Returns a rotated copy of a, b times.
5179
5180 The coefficient of the result is a rotated copy of the digits in
5181 the coefficient of the first operand. The number of places of
5182 rotation is taken from the absolute value of the second operand,
5183 with the rotation being to the left if the second operand is
5184 positive or to the right otherwise.
5185
5186 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005187 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005188 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005189 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005190 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005191 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005192 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005193 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005194 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005195 Decimal('345678912')
Mark Dickinson84230a12010-02-18 14:49:50 +00005196 >>> ExtendedContext.rotate(1333333, 1)
5197 Decimal('13333330')
5198 >>> ExtendedContext.rotate(Decimal(1333333), 1)
5199 Decimal('13333330')
5200 >>> ExtendedContext.rotate(1333333, Decimal(1))
5201 Decimal('13333330')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005202 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005203 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005204 return a.rotate(b, context=self)
5205
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005206 def same_quantum(self, a, b):
5207 """Returns True if the two operands have the same exponent.
5208
5209 The result is never affected by either the sign or the coefficient of
5210 either operand.
5211
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005212 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005213 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005214 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005215 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005216 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005217 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005218 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005219 True
Mark Dickinson84230a12010-02-18 14:49:50 +00005220 >>> ExtendedContext.same_quantum(10000, -1)
5221 True
5222 >>> ExtendedContext.same_quantum(Decimal(10000), -1)
5223 True
5224 >>> ExtendedContext.same_quantum(10000, Decimal(-1))
5225 True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005226 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005227 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005228 return a.same_quantum(b)
5229
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005230 def scaleb (self, a, b):
5231 """Returns the first operand after adding the second value its exp.
5232
5233 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005234 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005235 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005236 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005237 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005238 Decimal('7.50E+3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005239 >>> ExtendedContext.scaleb(1, 4)
5240 Decimal('1E+4')
5241 >>> ExtendedContext.scaleb(Decimal(1), 4)
5242 Decimal('1E+4')
5243 >>> ExtendedContext.scaleb(1, Decimal(4))
5244 Decimal('1E+4')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005245 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005246 a = _convert_other(a, raiseit=True)
5247 return a.scaleb(b, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005248
5249 def shift(self, a, b):
5250 """Returns a shifted copy of a, b times.
5251
5252 The coefficient of the result is a shifted copy of the digits
5253 in the coefficient of the first operand. The number of places
5254 to shift is taken from the absolute value of the second operand,
5255 with the shift being to the left if the second operand is
5256 positive or to the right otherwise. Digits shifted into the
5257 coefficient are zeros.
5258
5259 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005260 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005261 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005262 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005263 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005264 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005265 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005266 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005267 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005268 Decimal('345678900')
Mark Dickinson84230a12010-02-18 14:49:50 +00005269 >>> ExtendedContext.shift(88888888, 2)
5270 Decimal('888888800')
5271 >>> ExtendedContext.shift(Decimal(88888888), 2)
5272 Decimal('888888800')
5273 >>> ExtendedContext.shift(88888888, Decimal(2))
5274 Decimal('888888800')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005275 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005276 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005277 return a.shift(b, context=self)
5278
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005279 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005280 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005281
5282 If the result must be inexact, it is rounded using the round-half-even
5283 algorithm.
5284
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005285 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005286 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005287 >>> ExtendedContext.sqrt(Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005288 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005289 >>> ExtendedContext.sqrt(Decimal('0.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005290 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005291 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005292 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005293 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005294 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005295 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005296 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005297 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005298 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005299 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005300 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005301 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005302 Decimal('3.16227766')
Mark Dickinson84230a12010-02-18 14:49:50 +00005303 >>> ExtendedContext.sqrt(2)
5304 Decimal('1.41421356')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005305 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005306 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005307 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005308 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005309 return a.sqrt(context=self)
5310
5311 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00005312 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005313
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005314 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005315 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005316 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005317 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005318 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005319 Decimal('-0.77')
Mark Dickinson84230a12010-02-18 14:49:50 +00005320 >>> ExtendedContext.subtract(8, 5)
5321 Decimal('3')
5322 >>> ExtendedContext.subtract(Decimal(8), 5)
5323 Decimal('3')
5324 >>> ExtendedContext.subtract(8, Decimal(5))
5325 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005326 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005327 a = _convert_other(a, raiseit=True)
5328 r = a.__sub__(b, context=self)
5329 if r is NotImplemented:
5330 raise TypeError("Unable to convert %s to Decimal" % b)
5331 else:
5332 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005333
5334 def to_eng_string(self, a):
5335 """Converts a number to a string, using scientific notation.
5336
5337 The operation is not affected by the context.
5338 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005339 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005340 return a.to_eng_string(context=self)
5341
5342 def to_sci_string(self, a):
5343 """Converts a number to a string, using scientific notation.
5344
5345 The operation is not affected by the context.
5346 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005347 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005348 return a.__str__(context=self)
5349
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005350 def to_integral_exact(self, a):
5351 """Rounds to an integer.
5352
5353 When the operand has a negative exponent, the result is the same
5354 as using the quantize() operation using the given operand as the
5355 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5356 of the operand as the precision setting; Inexact and Rounded flags
5357 are allowed in this operation. The rounding mode is taken from the
5358 context.
5359
5360 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005361 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005362 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005363 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005364 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005365 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005366 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005367 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005368 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005369 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005370 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005371 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005372 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005373 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005374 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005375 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005376 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005377 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005378 return a.to_integral_exact(context=self)
5379
5380 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005381 """Rounds to an integer.
5382
5383 When the operand has a negative exponent, the result is the same
5384 as using the quantize() operation using the given operand as the
5385 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5386 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00005387 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005388
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005389 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005390 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005391 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005392 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005393 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005394 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005395 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005396 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005397 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005398 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005399 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005400 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005401 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005402 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005403 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005404 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005405 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005406 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005407 return a.to_integral_value(context=self)
5408
5409 # the method name changed, but we provide also the old one, for compatibility
5410 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005411
5412class _WorkRep(object):
5413 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005414 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005415 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005416 # exp: None, int, or string
5417
5418 def __init__(self, value=None):
5419 if value is None:
5420 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005421 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005422 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005423 elif isinstance(value, Decimal):
5424 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005425 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005426 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005427 else:
5428 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005429 self.sign = value[0]
5430 self.int = value[1]
5431 self.exp = value[2]
5432
5433 def __repr__(self):
5434 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5435
5436 __str__ = __repr__
5437
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005438
5439
Christian Heimes2c181612007-12-17 20:04:13 +00005440def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005441 """Normalizes op1, op2 to have the same exp and length of coefficient.
5442
5443 Done during addition.
5444 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005445 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005446 tmp = op2
5447 other = op1
5448 else:
5449 tmp = op1
5450 other = op2
5451
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005452 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5453 # Then adding 10**exp to tmp has the same effect (after rounding)
5454 # as adding any positive quantity smaller than 10**exp; similarly
5455 # for subtraction. So if other is smaller than 10**exp we replace
5456 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00005457 tmp_len = len(str(tmp.int))
5458 other_len = len(str(other.int))
5459 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5460 if other_len + other.exp - 1 < exp:
5461 other.int = 1
5462 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005463
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005464 tmp.int *= 10 ** (tmp.exp - other.exp)
5465 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005466 return op1, op2
5467
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005468##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005469
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005470# This function from Tim Peters was taken from here:
5471# http://mail.python.org/pipermail/python-list/1999-July/007758.html
5472# The correction being in the function definition is for speed, and
5473# the whole function is not resolved with math.log because of avoiding
5474# the use of floats.
5475def _nbits(n, correction = {
5476 '0': 4, '1': 3, '2': 2, '3': 2,
5477 '4': 1, '5': 1, '6': 1, '7': 1,
5478 '8': 0, '9': 0, 'a': 0, 'b': 0,
5479 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
5480 """Number of bits in binary representation of the positive integer n,
5481 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005482 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005483 if n < 0:
5484 raise ValueError("The argument to _nbits should be nonnegative.")
5485 hex_n = "%x" % n
5486 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005487
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005488def _sqrt_nearest(n, a):
5489 """Closest integer to the square root of the positive integer n. a is
5490 an initial approximation to the square root. Any positive integer
5491 will do for a, but the closer a is to the square root of n the
5492 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005493
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005494 """
5495 if n <= 0 or a <= 0:
5496 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5497
5498 b=0
5499 while a != b:
5500 b, a = a, a--n//a>>1
5501 return a
5502
5503def _rshift_nearest(x, shift):
5504 """Given an integer x and a nonnegative integer shift, return closest
5505 integer to x / 2**shift; use round-to-even in case of a tie.
5506
5507 """
5508 b, q = 1 << shift, x >> shift
5509 return q + (2*(x & (b-1)) + (q&1) > b)
5510
5511def _div_nearest(a, b):
5512 """Closest integer to a/b, a and b positive integers; rounds to even
5513 in the case of a tie.
5514
5515 """
5516 q, r = divmod(a, b)
5517 return q + (2*r + (q&1) > b)
5518
5519def _ilog(x, M, L = 8):
5520 """Integer approximation to M*log(x/M), with absolute error boundable
5521 in terms only of x/M.
5522
5523 Given positive integers x and M, return an integer approximation to
5524 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5525 between the approximation and the exact result is at most 22. For
5526 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5527 both cases these are upper bounds on the error; it will usually be
5528 much smaller."""
5529
5530 # The basic algorithm is the following: let log1p be the function
5531 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5532 # the reduction
5533 #
5534 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5535 #
5536 # repeatedly until the argument to log1p is small (< 2**-L in
5537 # absolute value). For small y we can use the Taylor series
5538 # expansion
5539 #
5540 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5541 #
5542 # truncating at T such that y**T is small enough. The whole
5543 # computation is carried out in a form of fixed-point arithmetic,
5544 # with a real number z being represented by an integer
5545 # approximation to z*M. To avoid loss of precision, the y below
5546 # is actually an integer approximation to 2**R*y*M, where R is the
5547 # number of reductions performed so far.
5548
5549 y = x-M
5550 # argument reduction; R = number of reductions performed
5551 R = 0
5552 while (R <= L and abs(y) << L-R >= M or
5553 R > L and abs(y) >> R-L >= M):
5554 y = _div_nearest((M*y) << 1,
5555 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5556 R += 1
5557
5558 # Taylor series with T terms
5559 T = -int(-10*len(str(M))//(3*L))
5560 yshift = _rshift_nearest(y, R)
5561 w = _div_nearest(M, T)
5562 for k in range(T-1, 0, -1):
5563 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5564
5565 return _div_nearest(w*y, M)
5566
5567def _dlog10(c, e, p):
5568 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5569 approximation to 10**p * log10(c*10**e), with an absolute error of
5570 at most 1. Assumes that c*10**e is not exactly 1."""
5571
5572 # increase precision by 2; compensate for this by dividing
5573 # final result by 100
5574 p += 2
5575
5576 # write c*10**e as d*10**f with either:
5577 # f >= 0 and 1 <= d <= 10, or
5578 # f <= 0 and 0.1 <= d <= 1.
5579 # Thus for c*10**e close to 1, f = 0
5580 l = len(str(c))
5581 f = e+l - (e+l >= 1)
5582
5583 if p > 0:
5584 M = 10**p
5585 k = e+p-f
5586 if k >= 0:
5587 c *= 10**k
5588 else:
5589 c = _div_nearest(c, 10**-k)
5590
5591 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005592 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005593 log_d = _div_nearest(log_d*M, log_10)
5594 log_tenpower = f*M # exact
5595 else:
5596 log_d = 0 # error < 2.31
Neal Norwitz2f99b242008-08-24 05:48:10 +00005597 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005598
5599 return _div_nearest(log_tenpower+log_d, 100)
5600
5601def _dlog(c, e, p):
5602 """Given integers c, e and p with c > 0, compute an integer
5603 approximation to 10**p * log(c*10**e), with an absolute error of
5604 at most 1. Assumes that c*10**e is not exactly 1."""
5605
5606 # Increase precision by 2. The precision increase is compensated
5607 # for at the end with a division by 100.
5608 p += 2
5609
5610 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5611 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5612 # as 10**p * log(d) + 10**p*f * log(10).
5613 l = len(str(c))
5614 f = e+l - (e+l >= 1)
5615
5616 # compute approximation to 10**p*log(d), with error < 27
5617 if p > 0:
5618 k = e+p-f
5619 if k >= 0:
5620 c *= 10**k
5621 else:
5622 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5623
5624 # _ilog magnifies existing error in c by a factor of at most 10
5625 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5626 else:
5627 # p <= 0: just approximate the whole thing by 0; error < 2.31
5628 log_d = 0
5629
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005630 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005631 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005632 extra = len(str(abs(f)))-1
5633 if p + extra >= 0:
5634 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5635 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5636 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005637 else:
5638 f_log_ten = 0
5639 else:
5640 f_log_ten = 0
5641
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005642 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005643 return _div_nearest(f_log_ten + log_d, 100)
5644
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005645class _Log10Memoize(object):
5646 """Class to compute, store, and allow retrieval of, digits of the
5647 constant log(10) = 2.302585.... This constant is needed by
5648 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5649 def __init__(self):
5650 self.digits = "23025850929940456840179914546843642076011014886"
5651
5652 def getdigits(self, p):
5653 """Given an integer p >= 0, return floor(10**p)*log(10).
5654
5655 For example, self.getdigits(3) returns 2302.
5656 """
5657 # digits are stored as a string, for quick conversion to
5658 # integer in the case that we've already computed enough
5659 # digits; the stored digits should always be correct
5660 # (truncated, not rounded to nearest).
5661 if p < 0:
5662 raise ValueError("p should be nonnegative")
5663
5664 if p >= len(self.digits):
5665 # compute p+3, p+6, p+9, ... digits; continue until at
5666 # least one of the extra digits is nonzero
5667 extra = 3
5668 while True:
5669 # compute p+extra digits, correct to within 1ulp
5670 M = 10**(p+extra+2)
5671 digits = str(_div_nearest(_ilog(10*M, M), 100))
5672 if digits[-extra:] != '0'*extra:
5673 break
5674 extra += 3
5675 # keep all reliable digits so far; remove trailing zeros
5676 # and next nonzero digit
5677 self.digits = digits.rstrip('0')[:-1]
5678 return int(self.digits[:p+1])
5679
5680_log10_digits = _Log10Memoize().getdigits
5681
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005682def _iexp(x, M, L=8):
5683 """Given integers x and M, M > 0, such that x/M is small in absolute
5684 value, compute an integer approximation to M*exp(x/M). For 0 <=
5685 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5686 is usually much smaller)."""
5687
5688 # Algorithm: to compute exp(z) for a real number z, first divide z
5689 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5690 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5691 # series
5692 #
5693 # expm1(x) = x + x**2/2! + x**3/3! + ...
5694 #
5695 # Now use the identity
5696 #
5697 # expm1(2x) = expm1(x)*(expm1(x)+2)
5698 #
5699 # R times to compute the sequence expm1(z/2**R),
5700 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5701
5702 # Find R such that x/2**R/M <= 2**-L
5703 R = _nbits((x<<L)//M)
5704
5705 # Taylor series. (2**L)**T > M
5706 T = -int(-10*len(str(M))//(3*L))
5707 y = _div_nearest(x, T)
5708 Mshift = M<<R
5709 for i in range(T-1, 0, -1):
5710 y = _div_nearest(x*(Mshift + y), Mshift * i)
5711
5712 # Expansion
5713 for k in range(R-1, -1, -1):
5714 Mshift = M<<(k+2)
5715 y = _div_nearest(y*(y+Mshift), Mshift)
5716
5717 return M+y
5718
5719def _dexp(c, e, p):
5720 """Compute an approximation to exp(c*10**e), with p decimal places of
5721 precision.
5722
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005723 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005724
5725 10**(p-1) <= d <= 10**p, and
5726 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5727
5728 In other words, d*10**f is an approximation to exp(c*10**e) with p
5729 digits of precision, and with an error in d of at most 1. This is
5730 almost, but not quite, the same as the error being < 1ulp: when d
5731 = 10**(p-1) the error could be up to 10 ulp."""
5732
5733 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5734 p += 2
5735
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005736 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005737 extra = max(0, e + len(str(c)) - 1)
5738 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005739
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005740 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005741 # rounding down
5742 shift = e+q
5743 if shift >= 0:
5744 cshift = c*10**shift
5745 else:
5746 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005747 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005748
5749 # reduce remainder back to original precision
5750 rem = _div_nearest(rem, 10**extra)
5751
5752 # error in result of _iexp < 120; error after division < 0.62
5753 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5754
5755def _dpower(xc, xe, yc, ye, p):
5756 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5757 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5758
5759 10**(p-1) <= c <= 10**p, and
5760 (c-1)*10**e < x**y < (c+1)*10**e
5761
5762 in other words, c*10**e is an approximation to x**y with p digits
5763 of precision, and with an error in c of at most 1. (This is
5764 almost, but not quite, the same as the error being < 1ulp: when c
5765 == 10**(p-1) we can only guarantee error < 10ulp.)
5766
5767 We assume that: x is positive and not equal to 1, and y is nonzero.
5768 """
5769
5770 # Find b such that 10**(b-1) <= |y| <= 10**b
5771 b = len(str(abs(yc))) + ye
5772
5773 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5774 lxc = _dlog(xc, xe, p+b+1)
5775
5776 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5777 shift = ye-b
5778 if shift >= 0:
5779 pc = lxc*yc*10**shift
5780 else:
5781 pc = _div_nearest(lxc*yc, 10**-shift)
5782
5783 if pc == 0:
5784 # we prefer a result that isn't exactly 1; this makes it
5785 # easier to compute a correctly rounded result in __pow__
5786 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5787 coeff, exp = 10**(p-1)+1, 1-p
5788 else:
5789 coeff, exp = 10**p-1, -p
5790 else:
5791 coeff, exp = _dexp(pc, -(p+1), p+1)
5792 coeff = _div_nearest(coeff, 10)
5793 exp += 1
5794
5795 return coeff, exp
5796
5797def _log10_lb(c, correction = {
5798 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5799 '6': 23, '7': 16, '8': 10, '9': 5}):
5800 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5801 if c <= 0:
5802 raise ValueError("The argument to _log10_lb should be nonnegative.")
5803 str_c = str(c)
5804 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005805
Guido van Rossumd8faa362007-04-27 19:54:29 +00005806##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005807
Mark Dickinsonac256ab2010-04-03 11:08:14 +00005808def _convert_other(other, raiseit=False, allow_float=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005809 """Convert other to Decimal.
5810
5811 Verifies that it's ok to use in an implicit construction.
Mark Dickinsonac256ab2010-04-03 11:08:14 +00005812 If allow_float is true, allow conversion from float; this
5813 is used in the comparison methods (__eq__ and friends).
5814
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005815 """
5816 if isinstance(other, Decimal):
5817 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005818 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005819 return Decimal(other)
Mark Dickinsonac256ab2010-04-03 11:08:14 +00005820 if allow_float and isinstance(other, float):
5821 return Decimal.from_float(other)
5822
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005823 if raiseit:
5824 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005825 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005826
Guido van Rossumd8faa362007-04-27 19:54:29 +00005827##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005828
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005829# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005830# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005831
5832DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005833 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005834 traps=[DivisionByZero, Overflow, InvalidOperation],
5835 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005836 Emax=999999999,
5837 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005838 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005839)
5840
5841# Pre-made alternate contexts offered by the specification
5842# Don't change these; the user should be able to select these
5843# contexts and be able to reproduce results from other implementations
5844# of the spec.
5845
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005846BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005847 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005848 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5849 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005850)
5851
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005852ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005853 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005854 traps=[],
5855 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005856)
5857
5858
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005859##### crud for parsing strings #############################################
Christian Heimes23daade02008-02-25 12:39:23 +00005860#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005861# Regular expression used for parsing numeric strings. Additional
5862# comments:
5863#
5864# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5865# whitespace. But note that the specification disallows whitespace in
5866# a numeric string.
5867#
5868# 2. For finite numbers (not infinities and NaNs) the body of the
5869# number between the optional sign and the optional exponent must have
5870# at least one decimal digit, possibly after the decimal point. The
Mark Dickinson345adc42009-08-02 10:14:23 +00005871# lookahead expression '(?=\d|\.\d)' checks this.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005872
5873import re
Benjamin Peterson41181742008-07-02 20:22:54 +00005874_parser = re.compile(r""" # A numeric string consists of:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005875# \s*
Benjamin Peterson41181742008-07-02 20:22:54 +00005876 (?P<sign>[-+])? # an optional sign, followed by either...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005877 (
Mark Dickinson345adc42009-08-02 10:14:23 +00005878 (?=\d|\.\d) # ...a number (with at least one digit)
5879 (?P<int>\d*) # having a (possibly empty) integer part
5880 (\.(?P<frac>\d*))? # followed by an optional fractional part
5881 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005882 |
Benjamin Peterson41181742008-07-02 20:22:54 +00005883 Inf(inity)? # ...an infinity, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005884 |
Benjamin Peterson41181742008-07-02 20:22:54 +00005885 (?P<signal>s)? # ...an (optionally signaling)
5886 NaN # NaN
Mark Dickinson345adc42009-08-02 10:14:23 +00005887 (?P<diag>\d*) # with (possibly empty) diagnostic info.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005888 )
5889# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00005890 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005891""", re.VERBOSE | re.IGNORECASE).match
5892
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005893_all_zeros = re.compile('0*$').match
5894_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00005895
5896##### PEP3101 support functions ##############################################
Mark Dickinson79f52032009-03-17 23:12:51 +00005897# The functions in this section have little to do with the Decimal
5898# class, and could potentially be reused or adapted for other pure
Christian Heimesf16baeb2008-02-29 14:57:44 +00005899# Python numeric classes that want to implement __format__
5900#
5901# A format specifier for Decimal looks like:
5902#
Mark Dickinson79f52032009-03-17 23:12:51 +00005903# [[fill]align][sign][0][minimumwidth][,][.precision][type]
Christian Heimesf16baeb2008-02-29 14:57:44 +00005904
5905_parse_format_specifier_regex = re.compile(r"""\A
5906(?:
5907 (?P<fill>.)?
5908 (?P<align>[<>=^])
5909)?
5910(?P<sign>[-+ ])?
5911(?P<zeropad>0)?
5912(?P<minimumwidth>(?!0)\d+)?
Mark Dickinson79f52032009-03-17 23:12:51 +00005913(?P<thousands_sep>,)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00005914(?:\.(?P<precision>0|(?!0)\d+))?
Mark Dickinson79f52032009-03-17 23:12:51 +00005915(?P<type>[eEfFgGn%])?
Christian Heimesf16baeb2008-02-29 14:57:44 +00005916\Z
5917""", re.VERBOSE)
5918
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005919del re
5920
Mark Dickinson79f52032009-03-17 23:12:51 +00005921# The locale module is only needed for the 'n' format specifier. The
5922# rest of the PEP 3101 code functions quite happily without it, so we
5923# don't care too much if locale isn't present.
5924try:
5925 import locale as _locale
5926except ImportError:
5927 pass
5928
5929def _parse_format_specifier(format_spec, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00005930 """Parse and validate a format specifier.
5931
5932 Turns a standard numeric format specifier into a dict, with the
5933 following entries:
5934
5935 fill: fill character to pad field to minimum width
5936 align: alignment type, either '<', '>', '=' or '^'
5937 sign: either '+', '-' or ' '
5938 minimumwidth: nonnegative integer giving minimum width
Mark Dickinson79f52032009-03-17 23:12:51 +00005939 zeropad: boolean, indicating whether to pad with zeros
5940 thousands_sep: string to use as thousands separator, or ''
5941 grouping: grouping for thousands separators, in format
5942 used by localeconv
5943 decimal_point: string to use for decimal point
Christian Heimesf16baeb2008-02-29 14:57:44 +00005944 precision: nonnegative integer giving precision, or None
5945 type: one of the characters 'eEfFgG%', or None
Christian Heimesf16baeb2008-02-29 14:57:44 +00005946
5947 """
5948 m = _parse_format_specifier_regex.match(format_spec)
5949 if m is None:
5950 raise ValueError("Invalid format specifier: " + format_spec)
5951
5952 # get the dictionary
5953 format_dict = m.groupdict()
5954
Mark Dickinson79f52032009-03-17 23:12:51 +00005955 # zeropad; defaults for fill and alignment. If zero padding
5956 # is requested, the fill and align fields should be absent.
Christian Heimesf16baeb2008-02-29 14:57:44 +00005957 fill = format_dict['fill']
5958 align = format_dict['align']
Mark Dickinson79f52032009-03-17 23:12:51 +00005959 format_dict['zeropad'] = (format_dict['zeropad'] is not None)
5960 if format_dict['zeropad']:
5961 if fill is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00005962 raise ValueError("Fill character conflicts with '0'"
5963 " in format specifier: " + format_spec)
Mark Dickinson79f52032009-03-17 23:12:51 +00005964 if align is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00005965 raise ValueError("Alignment conflicts with '0' in "
5966 "format specifier: " + format_spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00005967 format_dict['fill'] = fill or ' '
Mark Dickinson46ab5d02009-09-08 20:22:46 +00005968 # PEP 3101 originally specified that the default alignment should
5969 # be left; it was later agreed that right-aligned makes more sense
5970 # for numeric types. See http://bugs.python.org/issue6857.
5971 format_dict['align'] = align or '>'
Christian Heimesf16baeb2008-02-29 14:57:44 +00005972
Mark Dickinson79f52032009-03-17 23:12:51 +00005973 # default sign handling: '-' for negative, '' for positive
Christian Heimesf16baeb2008-02-29 14:57:44 +00005974 if format_dict['sign'] is None:
5975 format_dict['sign'] = '-'
5976
Christian Heimesf16baeb2008-02-29 14:57:44 +00005977 # minimumwidth defaults to 0; precision remains None if not given
5978 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5979 if format_dict['precision'] is not None:
5980 format_dict['precision'] = int(format_dict['precision'])
5981
5982 # if format type is 'g' or 'G' then a precision of 0 makes little
5983 # sense; convert it to 1. Same if format type is unspecified.
5984 if format_dict['precision'] == 0:
Mark Dickinson7718d2b2009-09-07 16:21:56 +00005985 if format_dict['type'] is None or format_dict['type'] in 'gG':
Christian Heimesf16baeb2008-02-29 14:57:44 +00005986 format_dict['precision'] = 1
5987
Mark Dickinson79f52032009-03-17 23:12:51 +00005988 # determine thousands separator, grouping, and decimal separator, and
5989 # add appropriate entries to format_dict
5990 if format_dict['type'] == 'n':
5991 # apart from separators, 'n' behaves just like 'g'
5992 format_dict['type'] = 'g'
5993 if _localeconv is None:
5994 _localeconv = _locale.localeconv()
5995 if format_dict['thousands_sep'] is not None:
5996 raise ValueError("Explicit thousands separator conflicts with "
5997 "'n' type in format specifier: " + format_spec)
5998 format_dict['thousands_sep'] = _localeconv['thousands_sep']
5999 format_dict['grouping'] = _localeconv['grouping']
6000 format_dict['decimal_point'] = _localeconv['decimal_point']
6001 else:
6002 if format_dict['thousands_sep'] is None:
6003 format_dict['thousands_sep'] = ''
6004 format_dict['grouping'] = [3, 0]
6005 format_dict['decimal_point'] = '.'
Christian Heimesf16baeb2008-02-29 14:57:44 +00006006
6007 return format_dict
6008
Mark Dickinson79f52032009-03-17 23:12:51 +00006009def _format_align(sign, body, spec):
6010 """Given an unpadded, non-aligned numeric string 'body' and sign
6011 string 'sign', add padding and aligment conforming to the given
6012 format specifier dictionary 'spec' (as produced by
6013 parse_format_specifier).
Christian Heimesf16baeb2008-02-29 14:57:44 +00006014
6015 """
Christian Heimesf16baeb2008-02-29 14:57:44 +00006016 # how much extra space do we have to play with?
Mark Dickinson79f52032009-03-17 23:12:51 +00006017 minimumwidth = spec['minimumwidth']
6018 fill = spec['fill']
6019 padding = fill*(minimumwidth - len(sign) - len(body))
Christian Heimesf16baeb2008-02-29 14:57:44 +00006020
Mark Dickinson79f52032009-03-17 23:12:51 +00006021 align = spec['align']
Christian Heimesf16baeb2008-02-29 14:57:44 +00006022 if align == '<':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006023 result = sign + body + padding
Mark Dickinsonad416342009-03-17 18:10:15 +00006024 elif align == '>':
6025 result = padding + sign + body
Christian Heimesf16baeb2008-02-29 14:57:44 +00006026 elif align == '=':
6027 result = sign + padding + body
Mark Dickinson79f52032009-03-17 23:12:51 +00006028 elif align == '^':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006029 half = len(padding)//2
6030 result = padding[:half] + sign + body + padding[half:]
Mark Dickinson79f52032009-03-17 23:12:51 +00006031 else:
6032 raise ValueError('Unrecognised alignment field')
Christian Heimesf16baeb2008-02-29 14:57:44 +00006033
Christian Heimesf16baeb2008-02-29 14:57:44 +00006034 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006035
Mark Dickinson79f52032009-03-17 23:12:51 +00006036def _group_lengths(grouping):
6037 """Convert a localeconv-style grouping into a (possibly infinite)
6038 iterable of integers representing group lengths.
6039
6040 """
6041 # The result from localeconv()['grouping'], and the input to this
6042 # function, should be a list of integers in one of the
6043 # following three forms:
6044 #
6045 # (1) an empty list, or
6046 # (2) nonempty list of positive integers + [0]
6047 # (3) list of positive integers + [locale.CHAR_MAX], or
6048
6049 from itertools import chain, repeat
6050 if not grouping:
6051 return []
6052 elif grouping[-1] == 0 and len(grouping) >= 2:
6053 return chain(grouping[:-1], repeat(grouping[-2]))
6054 elif grouping[-1] == _locale.CHAR_MAX:
6055 return grouping[:-1]
6056 else:
6057 raise ValueError('unrecognised format for grouping')
6058
6059def _insert_thousands_sep(digits, spec, min_width=1):
6060 """Insert thousands separators into a digit string.
6061
6062 spec is a dictionary whose keys should include 'thousands_sep' and
6063 'grouping'; typically it's the result of parsing the format
6064 specifier using _parse_format_specifier.
6065
6066 The min_width keyword argument gives the minimum length of the
6067 result, which will be padded on the left with zeros if necessary.
6068
6069 If necessary, the zero padding adds an extra '0' on the left to
6070 avoid a leading thousands separator. For example, inserting
6071 commas every three digits in '123456', with min_width=8, gives
6072 '0,123,456', even though that has length 9.
6073
6074 """
6075
6076 sep = spec['thousands_sep']
6077 grouping = spec['grouping']
6078
6079 groups = []
6080 for l in _group_lengths(grouping):
Mark Dickinson79f52032009-03-17 23:12:51 +00006081 if l <= 0:
6082 raise ValueError("group length should be positive")
6083 # max(..., 1) forces at least 1 digit to the left of a separator
6084 l = min(max(len(digits), min_width, 1), l)
6085 groups.append('0'*(l - len(digits)) + digits[-l:])
6086 digits = digits[:-l]
6087 min_width -= l
6088 if not digits and min_width <= 0:
6089 break
Mark Dickinson7303b592009-03-18 08:25:36 +00006090 min_width -= len(sep)
Mark Dickinson79f52032009-03-17 23:12:51 +00006091 else:
6092 l = max(len(digits), min_width, 1)
6093 groups.append('0'*(l - len(digits)) + digits[-l:])
6094 return sep.join(reversed(groups))
6095
6096def _format_sign(is_negative, spec):
6097 """Determine sign character."""
6098
6099 if is_negative:
6100 return '-'
6101 elif spec['sign'] in ' +':
6102 return spec['sign']
6103 else:
6104 return ''
6105
6106def _format_number(is_negative, intpart, fracpart, exp, spec):
6107 """Format a number, given the following data:
6108
6109 is_negative: true if the number is negative, else false
6110 intpart: string of digits that must appear before the decimal point
6111 fracpart: string of digits that must come after the point
6112 exp: exponent, as an integer
6113 spec: dictionary resulting from parsing the format specifier
6114
6115 This function uses the information in spec to:
6116 insert separators (decimal separator and thousands separators)
6117 format the sign
6118 format the exponent
6119 add trailing '%' for the '%' type
6120 zero-pad if necessary
6121 fill and align if necessary
6122 """
6123
6124 sign = _format_sign(is_negative, spec)
6125
6126 if fracpart:
6127 fracpart = spec['decimal_point'] + fracpart
6128
6129 if exp != 0 or spec['type'] in 'eE':
6130 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
6131 fracpart += "{0}{1:+}".format(echar, exp)
6132 if spec['type'] == '%':
6133 fracpart += '%'
6134
6135 if spec['zeropad']:
6136 min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
6137 else:
6138 min_width = 0
6139 intpart = _insert_thousands_sep(intpart, spec, min_width)
6140
6141 return _format_align(sign, intpart+fracpart, spec)
6142
6143
Guido van Rossumd8faa362007-04-27 19:54:29 +00006144##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006145
Guido van Rossumd8faa362007-04-27 19:54:29 +00006146# Reusable defaults
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006147_Infinity = Decimal('Inf')
6148_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonf9236412009-01-02 23:23:21 +00006149_NaN = Decimal('NaN')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006150_Zero = Decimal(0)
6151_One = Decimal(1)
6152_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006153
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006154# _SignedInfinity[sign] is infinity w/ that sign
6155_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006156
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006157
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006158
6159if __name__ == '__main__':
6160 import doctest, sys
6161 doctest.testmod(sys.modules[__name__])