blob: b254f9cd86cf74ed72e2735dafc1c5cf1c0e68a1 [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
Senthil Kumaran4fec47e2013-09-07 23:19:29 -070024 http://en.wikipedia.org/wiki/IEEE_854-1987
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000025
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
Mark Dickinsonaa63c4d2010-06-12 16:37:53 +000034of 0.0; Decimal('1.00') % Decimal('0.1') returns the expected
35Decimal('0.00')).
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000036
37Here are some examples of using the decimal module:
38
39>>> from decimal import *
Raymond Hettingerbd7f76d2004-07-08 00:49:18 +000040>>> setcontext(ExtendedContext)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000041>>> Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000042Decimal('0')
43>>> Decimal('1')
44Decimal('1')
45>>> Decimal('-.0123')
46Decimal('-0.0123')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000047>>> Decimal(123456)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000048Decimal('123456')
Stefan Krah1919b7e2012-03-21 18:25:23 +010049>>> Decimal('123.45e12345678')
50Decimal('1.2345E+12345680')
Christian Heimes68f5fbe2008-02-14 08:27:37 +000051>>> Decimal('1.33') + Decimal('1.27')
52Decimal('2.60')
53>>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
54Decimal('-2.20')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000055>>> dig = Decimal(1)
Guido van Rossum7131f842007-02-09 20:13:25 +000056>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000570.333333333
58>>> getcontext().prec = 18
Guido van Rossum7131f842007-02-09 20:13:25 +000059>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000600.333333333333333333
Guido van Rossum7131f842007-02-09 20:13:25 +000061>>> print(dig.sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000621
Guido van Rossum7131f842007-02-09 20:13:25 +000063>>> print(Decimal(3).sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000641.73205080756887729
Guido van Rossum7131f842007-02-09 20:13:25 +000065>>> print(Decimal(3) ** 123)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000664.85192780976896427E+58
67>>> inf = Decimal(1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000068>>> print(inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000069Infinity
70>>> neginf = Decimal(-1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000071>>> print(neginf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000072-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000073>>> print(neginf + inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000074NaN
Guido van Rossum7131f842007-02-09 20:13:25 +000075>>> print(neginf * inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000076-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000077>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000078Infinity
Raymond Hettingerbf440692004-07-10 14:14:37 +000079>>> getcontext().traps[DivisionByZero] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000080>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000081Traceback (most recent call last):
82 ...
83 ...
84 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +000085decimal.DivisionByZero: x / 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000086>>> c = Context()
Raymond Hettingerbf440692004-07-10 14:14:37 +000087>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000088>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000890
90>>> c.divide(Decimal(0), Decimal(0))
Christian Heimes68f5fbe2008-02-14 08:27:37 +000091Decimal('NaN')
Raymond Hettingerbf440692004-07-10 14:14:37 +000092>>> c.traps[InvalidOperation] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000093>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000941
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000095>>> c.flags[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000096>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000970
Guido van Rossum7131f842007-02-09 20:13:25 +000098>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000099Traceback (most recent call last):
100 ...
101 ...
102 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +0000103decimal.InvalidOperation: 0 / 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000104>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001051
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000106>>> c.flags[InvalidOperation] = 0
Raymond Hettingerbf440692004-07-10 14:14:37 +0000107>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000108>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000109NaN
Guido van Rossum7131f842007-02-09 20:13:25 +0000110>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001111
112>>>
113"""
114
115__all__ = [
116 # Two major classes
117 'Decimal', 'Context',
118
Stefan Krah964feab2014-09-09 19:56:56 +0200119 # Named tuple representation
120 'DecimalTuple',
121
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000122 # Contexts
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +0000123 'DefaultContext', 'BasicContext', 'ExtendedContext',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000124
125 # Exceptions
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +0000126 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
127 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
Stefan Krah1919b7e2012-03-21 18:25:23 +0100128 'FloatOperation',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000129
Stefan Krah964feab2014-09-09 19:56:56 +0200130 # Exceptional conditions that trigger InvalidOperation
131 'DivisionImpossible', 'InvalidContext', 'ConversionSyntax', 'DivisionUndefined',
132
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000133 # Constants for use in setting up contexts
134 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000135 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000136
137 # Functions for manipulating contexts
Stefan Krah1919b7e2012-03-21 18:25:23 +0100138 'setcontext', 'getcontext', 'localcontext',
139
140 # Limits for the C version for compatibility
141 'MAX_PREC', 'MAX_EMAX', 'MIN_EMIN', 'MIN_ETINY',
142
143 # C version: compile time choice that enables the thread local context
144 'HAVE_THREADS'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000145]
146
Raymond Hettinger960dc362009-04-21 03:43:15 +0000147__version__ = '1.70' # Highest version of the spec this complies with
Raymond Hettinger697ce952010-11-30 20:32:59 +0000148 # See http://speleotrove.com/decimal/
Stefan Krahcf261152014-08-26 21:31:47 +0200149__libmpdec_version__ = "2.4.1" # compatible libmpdec version
Raymond Hettinger960dc362009-04-21 03:43:15 +0000150
Raymond Hettinger771ed762009-01-03 19:20:32 +0000151import math as _math
Raymond Hettinger82417ca2009-02-03 03:54:28 +0000152import numbers as _numbers
Stefan Krah1919b7e2012-03-21 18:25:23 +0100153import sys
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000154
Christian Heimes25bb7832008-01-11 16:17:00 +0000155try:
156 from collections import namedtuple as _namedtuple
157 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
Brett Cannoncd171c82013-07-04 17:43:24 -0400158except ImportError:
Christian Heimes25bb7832008-01-11 16:17:00 +0000159 DecimalTuple = lambda *args: args
160
Guido van Rossumd8faa362007-04-27 19:54:29 +0000161# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000162ROUND_DOWN = 'ROUND_DOWN'
163ROUND_HALF_UP = 'ROUND_HALF_UP'
164ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
165ROUND_CEILING = 'ROUND_CEILING'
166ROUND_FLOOR = 'ROUND_FLOOR'
167ROUND_UP = 'ROUND_UP'
168ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000169ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000170
Stefan Krah1919b7e2012-03-21 18:25:23 +0100171# Compatibility with the C version
172HAVE_THREADS = True
173if sys.maxsize == 2**63-1:
174 MAX_PREC = 999999999999999999
175 MAX_EMAX = 999999999999999999
176 MIN_EMIN = -999999999999999999
177else:
178 MAX_PREC = 425000000
179 MAX_EMAX = 425000000
180 MIN_EMIN = -425000000
181
182MIN_ETINY = MIN_EMIN - (MAX_PREC-1)
183
Guido van Rossumd8faa362007-04-27 19:54:29 +0000184# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000185
186class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000187 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000188
189 Used exceptions derive from this.
190 If an exception derives from another exception besides this (such as
191 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
192 called if the others are present. This isn't actually used for
193 anything, though.
194
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000195 handle -- Called when context._raise_error is called and the
Stefan Krah2eb4a072010-05-19 15:52:31 +0000196 trap_enabler is not set. First argument is self, second is the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000197 context. More arguments can be given, those being after
198 the explanation in _raise_error (For example,
199 context._raise_error(NewError, '(-x)!', self._sign) would
200 call NewError().handle(context, self._sign).)
201
202 To define a new exception, it should be sufficient to have it derive
203 from DecimalException.
204 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000205 def handle(self, context, *args):
206 pass
207
208
209class Clamped(DecimalException):
210 """Exponent of a 0 changed to fit bounds.
211
212 This occurs and signals clamped if the exponent of a result has been
213 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000214 representation. This may occur when the exponent of a zero result would
215 be outside the bounds of a representation, or when a large normal
216 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000217 this latter case, the exponent is reduced to fit and the corresponding
218 number of zero digits are appended to the coefficient ("fold-down").
219 """
220
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000221class InvalidOperation(DecimalException):
222 """An invalid operation was performed.
223
224 Various bad things cause this:
225
226 Something creates a signaling NaN
227 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000228 0 * (+-)INF
229 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000230 x % 0
231 (+-)INF % x
232 x._rescale( non-integer )
233 sqrt(-x) , x > 0
234 0 ** 0
235 x ** (non-integer)
236 x ** (+-)INF
237 An operand is invalid
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000238
239 The result of the operation after these is a quiet positive NaN,
240 except when the cause is a signaling NaN, in which case the result is
241 also a quiet NaN, but with the original sign, and an optional
242 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000243 """
244 def handle(self, context, *args):
245 if args:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000246 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
247 return ans._fix_nan(context)
Mark Dickinsonf9236412009-01-02 23:23:21 +0000248 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000249
250class ConversionSyntax(InvalidOperation):
251 """Trying to convert badly formed string.
252
253 This occurs and signals invalid-operation if an string is being
254 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000255 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000256 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000257 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000258 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000259
260class DivisionByZero(DecimalException, ZeroDivisionError):
261 """Division by 0.
262
263 This occurs and signals division-by-zero if division of a finite number
264 by zero was attempted (during a divide-integer or divide operation, or a
265 power operation with negative right-hand operand), and the dividend was
266 not zero.
267
268 The result of the operation is [sign,inf], where sign is the exclusive
269 or of the signs of the operands for divide, or is 1 for an odd power of
270 -0, for power.
271 """
272
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000273 def handle(self, context, sign, *args):
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000274 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000275
276class DivisionImpossible(InvalidOperation):
277 """Cannot perform the division adequately.
278
279 This occurs and signals invalid-operation if the integer result of a
280 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000281 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000282 """
283
284 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000285 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000286
287class DivisionUndefined(InvalidOperation, ZeroDivisionError):
288 """Undefined result of division.
289
290 This occurs and signals invalid-operation if division by zero was
291 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000292 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000293 """
294
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000295 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000296 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000297
298class Inexact(DecimalException):
299 """Had to round, losing information.
300
301 This occurs and signals inexact whenever the result of an operation is
302 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000303 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000304 result in all cases is unchanged.
305
306 The inexact signal may be tested (or trapped) to determine if a given
307 operation (or sequence of operations) was inexact.
308 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000309
310class InvalidContext(InvalidOperation):
311 """Invalid context. Unknown rounding, for example.
312
313 This occurs and signals invalid-operation if an invalid context was
Guido van Rossumd8faa362007-04-27 19:54:29 +0000314 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000315 on creation and either the precision exceeds the capability of the
316 underlying concrete representation or an unknown or unsupported rounding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000317 was specified. These aspects of the context need only be checked when
318 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000319 """
320
321 def handle(self, context, *args):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000322 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000323
324class Rounded(DecimalException):
325 """Number got rounded (not necessarily changed during rounding).
326
327 This occurs and signals rounded whenever the result of an operation is
328 rounded (that is, some zero or non-zero digits were discarded from the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000329 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000330 result in all cases is unchanged.
331
332 The rounded signal may be tested (or trapped) to determine if a given
333 operation (or sequence of operations) caused a loss of precision.
334 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000335
336class Subnormal(DecimalException):
337 """Exponent < Emin before rounding.
338
339 This occurs and signals subnormal whenever the result of a conversion or
340 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000341 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000342
343 The subnormal signal may be tested (or trapped) to determine if a given
344 or operation (or sequence of operations) yielded a subnormal result.
345 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000346
347class Overflow(Inexact, Rounded):
348 """Numerical overflow.
349
350 This occurs and signals overflow if the adjusted exponent of a result
351 (from a conversion or from an operation that is not an attempt to divide
352 by zero), after rounding, would be greater than the largest value that
353 can be handled by the implementation (the value Emax).
354
355 The result depends on the rounding mode:
356
357 For round-half-up and round-half-even (and for round-half-down and
358 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000359 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000360 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000361 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000362 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000363 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000364 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000365 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000366 will also be raised.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000367 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000368
369 def handle(self, context, sign, *args):
370 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000371 ROUND_HALF_DOWN, ROUND_UP):
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000372 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000373 if sign == 0:
374 if context.rounding == ROUND_CEILING:
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000375 return _SignedInfinity[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000376 return _dec_from_triple(sign, '9'*context.prec,
377 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000378 if sign == 1:
379 if context.rounding == ROUND_FLOOR:
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000380 return _SignedInfinity[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000381 return _dec_from_triple(sign, '9'*context.prec,
382 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000383
384
385class Underflow(Inexact, Rounded, Subnormal):
386 """Numerical underflow with result rounded to 0.
387
388 This occurs and signals underflow if a result is inexact and the
389 adjusted exponent of the result would be smaller (more negative) than
390 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000391 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000392
393 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000394 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000395 in 0 with the sign of the intermediate result and an exponent of Etiny.
396
397 In all cases, Inexact, Rounded, and Subnormal will also be raised.
398 """
399
Stefan Krahb6405ef2012-03-23 14:46:48 +0100400class FloatOperation(DecimalException, TypeError):
Stefan Krah1919b7e2012-03-21 18:25:23 +0100401 """Enable stricter semantics for mixing floats and Decimals.
402
403 If the signal is not trapped (default), mixing floats and Decimals is
404 permitted in the Decimal() constructor, context.create_decimal() and
405 all comparison operators. Both conversion and comparisons are exact.
406 Any occurrence of a mixed operation is silently recorded by setting
407 FloatOperation in the context flags. Explicit conversions with
408 Decimal.from_float() or context.create_decimal_from_float() do not
409 set the flag.
410
411 Otherwise (the signal is trapped), only equality comparisons and explicit
412 conversions are silent. All other mixed operations raise FloatOperation.
413 """
414
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000415# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000416_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Stefan Krah1919b7e2012-03-21 18:25:23 +0100417 Underflow, InvalidOperation, Subnormal, FloatOperation]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000418
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000419# Map conditions (per the spec) to signals
420_condition_map = {ConversionSyntax:InvalidOperation,
421 DivisionImpossible:InvalidOperation,
422 DivisionUndefined:InvalidOperation,
423 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000424
Stefan Krah1919b7e2012-03-21 18:25:23 +0100425# Valid rounding modes
426_rounding_modes = (ROUND_DOWN, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_CEILING,
427 ROUND_FLOOR, ROUND_UP, ROUND_HALF_DOWN, ROUND_05UP)
428
Guido van Rossumd8faa362007-04-27 19:54:29 +0000429##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000430
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000431# The getcontext() and setcontext() function manage access to a thread-local
432# current context. Py2.4 offers direct support for thread locals. If that
Georg Brandlf9926402008-06-13 06:32:25 +0000433# is not available, use threading.current_thread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000434# work for older Pythons. If threads are not part of the build, create a
435# mock threading object with threading.local() returning the module namespace.
436
437try:
438 import threading
Brett Cannoncd171c82013-07-04 17:43:24 -0400439except ImportError:
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000440 # Python was compiled without threads; create a mock object instead
Guido van Rossumd8faa362007-04-27 19:54:29 +0000441 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000442 def local(self, sys=sys):
443 return sys.modules[__name__]
444 threading = MockThreading()
Stefan Krah1919b7e2012-03-21 18:25:23 +0100445 del MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000446
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000447try:
448 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000449
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000450except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000451
Guido van Rossumd8faa362007-04-27 19:54:29 +0000452 # To fix reloading, force it to create a new context
453 # Old contexts have different exceptions in their dicts, making problems.
Georg Brandlf9926402008-06-13 06:32:25 +0000454 if hasattr(threading.current_thread(), '__decimal_context__'):
455 del threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000456
457 def setcontext(context):
458 """Set this thread's context to context."""
459 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000460 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000461 context.clear_flags()
Georg Brandlf9926402008-06-13 06:32:25 +0000462 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000463
464 def getcontext():
465 """Returns this thread's context.
466
467 If this thread does not yet have a context, returns
468 a new context and sets this thread's context.
469 New contexts are copies of DefaultContext.
470 """
471 try:
Georg Brandlf9926402008-06-13 06:32:25 +0000472 return threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000473 except AttributeError:
474 context = Context()
Georg Brandlf9926402008-06-13 06:32:25 +0000475 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000476 return context
477
478else:
479
480 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000481 if hasattr(local, '__decimal_context__'):
482 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000483
484 def getcontext(_local=local):
485 """Returns this thread's context.
486
487 If this thread does not yet have a context, returns
488 a new context and sets this thread's context.
489 New contexts are copies of DefaultContext.
490 """
491 try:
492 return _local.__decimal_context__
493 except AttributeError:
494 context = Context()
495 _local.__decimal_context__ = context
496 return context
497
498 def setcontext(context, _local=local):
499 """Set this thread's context to context."""
500 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000501 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000502 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000503 _local.__decimal_context__ = context
504
505 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000506
Thomas Wouters89f507f2006-12-13 04:49:30 +0000507def localcontext(ctx=None):
508 """Return a context manager for a copy of the supplied context
509
510 Uses a copy of the current context if no context is specified
511 The returned context manager creates a local decimal context
512 in a with statement:
513 def sin(x):
514 with localcontext() as ctx:
515 ctx.prec += 2
516 # Rest of sin calculation algorithm
517 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000518 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000519
520 def sin(x):
521 with localcontext(ExtendedContext):
522 # Rest of sin calculation algorithm
523 # uses the Extended Context from the
524 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000525 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000526
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000527 >>> setcontext(DefaultContext)
Guido van Rossum7131f842007-02-09 20:13:25 +0000528 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000529 28
530 >>> with localcontext():
531 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000532 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000533 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000534 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000535 30
536 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000537 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000538 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000539 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000540 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000541 28
542 """
543 if ctx is None: ctx = getcontext()
544 return _ContextManager(ctx)
545
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000546
Guido van Rossumd8faa362007-04-27 19:54:29 +0000547##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000548
Raymond Hettingera0fd8882009-01-20 07:24:44 +0000549# Do not subclass Decimal from numbers.Real and do not register it as such
550# (because Decimals are not interoperable with floats). See the notes in
551# numbers.py for more detail.
552
553class Decimal(object):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000554 """Floating point class for decimal arithmetic."""
555
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000556 __slots__ = ('_exp','_int','_sign', '_is_special')
557 # Generally, the value of the Decimal instance is given by
558 # (-1)**_sign * _int * 10**_exp
559 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000560
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000561 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000562 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000563 """Create a decimal point instance.
564
565 >>> Decimal('3.14') # string input
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000566 Decimal('3.14')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000567 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000568 Decimal('3.14')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000569 >>> Decimal(314) # int
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000570 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000571 >>> Decimal(Decimal(314)) # another decimal instance
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000572 Decimal('314')
Christian Heimesa62da1d2008-01-12 19:39:10 +0000573 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000574 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000575 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000576
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000577 # Note that the coefficient, self._int, is actually stored as
578 # a string rather than as a tuple of digits. This speeds up
579 # the "digits to integer" and "integer to digits" conversions
580 # that are used in almost every arithmetic operation on
581 # Decimals. This is an internal detail: the as_tuple function
582 # and the Decimal constructor still deal with tuples of
583 # digits.
584
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000585 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000586
Christian Heimesd59c64c2007-11-30 19:27:20 +0000587 # From a string
588 # REs insist on real strings, so we can too.
589 if isinstance(value, str):
Christian Heimesa62da1d2008-01-12 19:39:10 +0000590 m = _parser(value.strip())
Christian Heimesd59c64c2007-11-30 19:27:20 +0000591 if m is None:
592 if context is None:
593 context = getcontext()
594 return context._raise_error(ConversionSyntax,
595 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000596
Christian Heimesd59c64c2007-11-30 19:27:20 +0000597 if m.group('sign') == "-":
598 self._sign = 1
599 else:
600 self._sign = 0
601 intpart = m.group('int')
602 if intpart is not None:
603 # finite number
Mark Dickinson345adc42009-08-02 10:14:23 +0000604 fracpart = m.group('frac') or ''
Christian Heimesd59c64c2007-11-30 19:27:20 +0000605 exp = int(m.group('exp') or '0')
Mark Dickinson345adc42009-08-02 10:14:23 +0000606 self._int = str(int(intpart+fracpart))
607 self._exp = exp - len(fracpart)
Christian Heimesd59c64c2007-11-30 19:27:20 +0000608 self._is_special = False
609 else:
610 diag = m.group('diag')
611 if diag is not None:
612 # NaN
Mark Dickinson345adc42009-08-02 10:14:23 +0000613 self._int = str(int(diag or '0')).lstrip('0')
Christian Heimesd59c64c2007-11-30 19:27:20 +0000614 if m.group('signal'):
615 self._exp = 'N'
616 else:
617 self._exp = 'n'
618 else:
619 # infinity
620 self._int = '0'
621 self._exp = 'F'
622 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000623 return self
624
625 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000626 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000627 if value >= 0:
628 self._sign = 0
629 else:
630 self._sign = 1
631 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000632 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000633 self._is_special = False
634 return self
635
636 # From another decimal
637 if isinstance(value, Decimal):
638 self._exp = value._exp
639 self._sign = value._sign
640 self._int = value._int
641 self._is_special = value._is_special
642 return self
643
644 # From an internal working value
645 if isinstance(value, _WorkRep):
646 self._sign = value.sign
647 self._int = str(value.int)
648 self._exp = int(value.exp)
649 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000650 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000651
652 # tuple/list conversion (possibly from as_tuple())
653 if isinstance(value, (list,tuple)):
654 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000655 raise ValueError('Invalid tuple size in creation of Decimal '
656 'from list or tuple. The list or tuple '
657 'should have exactly three elements.')
658 # process sign. The isinstance test rejects floats
659 if not (isinstance(value[0], int) and value[0] in (0,1)):
660 raise ValueError("Invalid sign. The first value in the tuple "
661 "should be an integer; either 0 for a "
662 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000663 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000664 if value[2] == 'F':
665 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000666 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000667 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000668 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000669 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000670 # process and validate the digits in value[1]
671 digits = []
672 for digit in value[1]:
673 if isinstance(digit, int) and 0 <= digit <= 9:
674 # skip leading zeros
675 if digits or digit != 0:
676 digits.append(digit)
677 else:
678 raise ValueError("The second value in the tuple must "
679 "be composed of integers in the range "
680 "0 through 9.")
681 if value[2] in ('n', 'N'):
682 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000683 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000684 self._exp = value[2]
685 self._is_special = True
686 elif isinstance(value[2], int):
687 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000688 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000689 self._exp = value[2]
690 self._is_special = False
691 else:
692 raise ValueError("The third value in the tuple must "
693 "be an integer, or one of the "
694 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000695 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000696
Raymond Hettingerbf440692004-07-10 14:14:37 +0000697 if isinstance(value, float):
Stefan Krah1919b7e2012-03-21 18:25:23 +0100698 if context is None:
699 context = getcontext()
700 context._raise_error(FloatOperation,
701 "strict semantics for mixing floats and Decimals are "
702 "enabled")
Raymond Hettinger96798592010-04-02 16:58:27 +0000703 value = Decimal.from_float(value)
704 self._exp = value._exp
705 self._sign = value._sign
706 self._int = value._int
707 self._is_special = value._is_special
708 return self
Raymond Hettingerbf440692004-07-10 14:14:37 +0000709
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000710 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000711
Mark Dickinson9c3f5032012-10-31 17:53:27 +0000712 @classmethod
Raymond Hettinger771ed762009-01-03 19:20:32 +0000713 def from_float(cls, f):
714 """Converts a float to a decimal number, exactly.
715
716 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
717 Since 0.1 is not exactly representable in binary floating point, the
718 value is stored as the nearest representable value which is
719 0x1.999999999999ap-4. The exact equivalent of the value in decimal
720 is 0.1000000000000000055511151231257827021181583404541015625.
721
722 >>> Decimal.from_float(0.1)
723 Decimal('0.1000000000000000055511151231257827021181583404541015625')
724 >>> Decimal.from_float(float('nan'))
725 Decimal('NaN')
726 >>> Decimal.from_float(float('inf'))
727 Decimal('Infinity')
728 >>> Decimal.from_float(-float('inf'))
729 Decimal('-Infinity')
730 >>> Decimal.from_float(-0.0)
731 Decimal('-0')
732
733 """
734 if isinstance(f, int): # handle integer inputs
735 return cls(f)
Stefan Krah1919b7e2012-03-21 18:25:23 +0100736 if not isinstance(f, float):
737 raise TypeError("argument must be int or float.")
738 if _math.isinf(f) or _math.isnan(f):
Raymond Hettinger771ed762009-01-03 19:20:32 +0000739 return cls(repr(f))
Mark Dickinsonba298e42009-01-04 21:17:43 +0000740 if _math.copysign(1.0, f) == 1.0:
741 sign = 0
742 else:
743 sign = 1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000744 n, d = abs(f).as_integer_ratio()
745 k = d.bit_length() - 1
746 result = _dec_from_triple(sign, str(n*5**k), -k)
Mark Dickinsonba298e42009-01-04 21:17:43 +0000747 if cls is Decimal:
748 return result
749 else:
750 return cls(result)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000751
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000752 def _isnan(self):
753 """Returns whether the number is not actually one.
754
755 0 if a number
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000756 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000757 2 if sNaN
758 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000759 if self._is_special:
760 exp = self._exp
761 if exp == 'n':
762 return 1
763 elif exp == 'N':
764 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000765 return 0
766
767 def _isinfinity(self):
768 """Returns whether the number is infinite
769
770 0 if finite or not a number
771 1 if +INF
772 -1 if -INF
773 """
774 if self._exp == 'F':
775 if self._sign:
776 return -1
777 return 1
778 return 0
779
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000780 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000781 """Returns whether the number is not actually one.
782
783 if self, other are sNaN, signal
784 if self, other are NaN return nan
785 return 0
786
787 Done before operations.
788 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000789
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000790 self_is_nan = self._isnan()
791 if other is None:
792 other_is_nan = False
793 else:
794 other_is_nan = other._isnan()
795
796 if self_is_nan or other_is_nan:
797 if context is None:
798 context = getcontext()
799
800 if self_is_nan == 2:
801 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000802 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000803 if other_is_nan == 2:
804 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000805 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000806 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000807 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000808
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000809 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000810 return 0
811
Christian Heimes77c02eb2008-02-09 02:18:51 +0000812 def _compare_check_nans(self, other, context):
813 """Version of _check_nans used for the signaling comparisons
814 compare_signal, __le__, __lt__, __ge__, __gt__.
815
816 Signal InvalidOperation if either self or other is a (quiet
817 or signaling) NaN. Signaling NaNs take precedence over quiet
818 NaNs.
819
820 Return 0 if neither operand is a NaN.
821
822 """
823 if context is None:
824 context = getcontext()
825
826 if self._is_special or other._is_special:
827 if self.is_snan():
828 return context._raise_error(InvalidOperation,
829 'comparison involving sNaN',
830 self)
831 elif other.is_snan():
832 return context._raise_error(InvalidOperation,
833 'comparison involving sNaN',
834 other)
835 elif self.is_qnan():
836 return context._raise_error(InvalidOperation,
837 'comparison involving NaN',
838 self)
839 elif other.is_qnan():
840 return context._raise_error(InvalidOperation,
841 'comparison involving NaN',
842 other)
843 return 0
844
Jack Diederich4dafcc42006-11-28 19:15:13 +0000845 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000846 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000847
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000848 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000849 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000850 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000851
Christian Heimes77c02eb2008-02-09 02:18:51 +0000852 def _cmp(self, other):
853 """Compare the two non-NaN decimal instances self and other.
854
855 Returns -1 if self < other, 0 if self == other and 1
856 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000857
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000858 if self._is_special or other._is_special:
Mark Dickinsone6aad752009-01-25 10:48:51 +0000859 self_inf = self._isinfinity()
860 other_inf = other._isinfinity()
861 if self_inf == other_inf:
862 return 0
863 elif self_inf < other_inf:
864 return -1
865 else:
866 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000867
Mark Dickinsone6aad752009-01-25 10:48:51 +0000868 # check for zeros; Decimal('0') == Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000869 if not self:
870 if not other:
871 return 0
872 else:
873 return -((-1)**other._sign)
874 if not other:
875 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000876
Guido van Rossumd8faa362007-04-27 19:54:29 +0000877 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000878 if other._sign < self._sign:
879 return -1
880 if self._sign < other._sign:
881 return 1
882
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000883 self_adjusted = self.adjusted()
884 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000885 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000886 self_padded = self._int + '0'*(self._exp - other._exp)
887 other_padded = other._int + '0'*(other._exp - self._exp)
Mark Dickinsone6aad752009-01-25 10:48:51 +0000888 if self_padded == other_padded:
889 return 0
890 elif self_padded < other_padded:
891 return -(-1)**self._sign
892 else:
893 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000894 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000895 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000896 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000897 return -((-1)**self._sign)
898
Christian Heimes77c02eb2008-02-09 02:18:51 +0000899 # Note: The Decimal standard doesn't cover rich comparisons for
900 # Decimals. In particular, the specification is silent on the
901 # subject of what should happen for a comparison involving a NaN.
902 # We take the following approach:
903 #
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000904 # == comparisons involving a quiet NaN always return False
905 # != comparisons involving a quiet NaN always return True
906 # == or != comparisons involving a signaling NaN signal
907 # InvalidOperation, and return False or True as above if the
908 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000909 # <, >, <= and >= comparisons involving a (quiet or signaling)
910 # NaN signal InvalidOperation, and return False if the
Christian Heimes3feef612008-02-11 06:19:17 +0000911 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000912 #
913 # This behavior is designed to conform as closely as possible to
914 # that specified by IEEE 754.
915
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000916 def __eq__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000917 self, other = _convert_for_comparison(self, other, equality_op=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000918 if other is NotImplemented:
919 return other
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000920 if self._check_nans(other, context):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000921 return False
922 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000923
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000924 def __ne__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000925 self, other = _convert_for_comparison(self, other, equality_op=True)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000926 if other is NotImplemented:
927 return other
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000928 if self._check_nans(other, context):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000929 return True
930 return self._cmp(other) != 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000931
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000932
Christian Heimes77c02eb2008-02-09 02:18:51 +0000933 def __lt__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000934 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000935 if other is NotImplemented:
936 return other
937 ans = self._compare_check_nans(other, context)
938 if ans:
939 return False
940 return self._cmp(other) < 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000941
Christian Heimes77c02eb2008-02-09 02:18:51 +0000942 def __le__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000943 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000944 if other is NotImplemented:
945 return other
946 ans = self._compare_check_nans(other, context)
947 if ans:
948 return False
949 return self._cmp(other) <= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000950
Christian Heimes77c02eb2008-02-09 02:18:51 +0000951 def __gt__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000952 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000953 if other is NotImplemented:
954 return other
955 ans = self._compare_check_nans(other, context)
956 if ans:
957 return False
958 return self._cmp(other) > 0
959
960 def __ge__(self, other, context=None):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000961 self, other = _convert_for_comparison(self, other)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000962 if other is NotImplemented:
963 return other
964 ans = self._compare_check_nans(other, context)
965 if ans:
966 return False
967 return self._cmp(other) >= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000968
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000969 def compare(self, other, context=None):
970 """Compares one to another.
971
972 -1 => a < b
973 0 => a = b
974 1 => a > b
975 NaN => one is NaN
976 Like __cmp__, but returns Decimal instances.
977 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000978 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000979
Guido van Rossumd8faa362007-04-27 19:54:29 +0000980 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000981 if (self._is_special or other and other._is_special):
982 ans = self._check_nans(other, context)
983 if ans:
984 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000985
Christian Heimes77c02eb2008-02-09 02:18:51 +0000986 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000987
988 def __hash__(self):
989 """x.__hash__() <==> hash(x)"""
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000990
Mark Dickinsondc787d22010-05-23 13:33:13 +0000991 # In order to make sure that the hash of a Decimal instance
992 # agrees with the hash of a numerically equal integer, float
993 # or Fraction, we follow the rules for numeric hashes outlined
994 # in the documentation. (See library docs, 'Built-in Types').
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000995 if self._is_special:
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000996 if self.is_snan():
Raymond Hettingerd325c4b2010-11-21 04:08:28 +0000997 raise TypeError('Cannot hash a signaling NaN value.')
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000998 elif self.is_nan():
Mark Dickinsondc787d22010-05-23 13:33:13 +0000999 return _PyHASH_NAN
Mark Dickinsonac256ab2010-04-03 11:08:14 +00001000 else:
Mark Dickinsonac256ab2010-04-03 11:08:14 +00001001 if self._sign:
Mark Dickinsondc787d22010-05-23 13:33:13 +00001002 return -_PyHASH_INF
Mark Dickinsonac256ab2010-04-03 11:08:14 +00001003 else:
Mark Dickinsondc787d22010-05-23 13:33:13 +00001004 return _PyHASH_INF
Mark Dickinsonac256ab2010-04-03 11:08:14 +00001005
Mark Dickinsondc787d22010-05-23 13:33:13 +00001006 if self._exp >= 0:
1007 exp_hash = pow(10, self._exp, _PyHASH_MODULUS)
1008 else:
1009 exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS)
1010 hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS
Stefan Krahdc817b22010-11-17 11:16:34 +00001011 ans = hash_ if self >= 0 else -hash_
1012 return -2 if ans == -1 else ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001013
1014 def as_tuple(self):
1015 """Represents the number as a triple tuple.
1016
1017 To show the internals exactly as they are.
1018 """
Christian Heimes25bb7832008-01-11 16:17:00 +00001019 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001020
1021 def __repr__(self):
1022 """Represents the number as an instance of Decimal."""
1023 # Invariant: eval(repr(d)) == d
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001024 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001025
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001026 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001027 """Return string representation of the number in scientific notation.
1028
1029 Captures all of the information in the underlying representation.
1030 """
1031
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001032 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +00001033 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001034 if self._exp == 'F':
1035 return sign + 'Infinity'
1036 elif self._exp == 'n':
1037 return sign + 'NaN' + self._int
1038 else: # self._exp == 'N'
1039 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001040
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001041 # number of digits of self._int to left of decimal point
1042 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001043
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001044 # dotplace is number of digits of self._int to the left of the
1045 # decimal point in the mantissa of the output string (that is,
1046 # after adjusting the exponent)
1047 if self._exp <= 0 and leftdigits > -6:
1048 # no exponent required
1049 dotplace = leftdigits
1050 elif not eng:
1051 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001052 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001053 elif self._int == '0':
1054 # engineering notation, zero
1055 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001056 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001057 # engineering notation, nonzero
1058 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001059
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001060 if dotplace <= 0:
1061 intpart = '0'
1062 fracpart = '.' + '0'*(-dotplace) + self._int
1063 elif dotplace >= len(self._int):
1064 intpart = self._int+'0'*(dotplace-len(self._int))
1065 fracpart = ''
1066 else:
1067 intpart = self._int[:dotplace]
1068 fracpart = '.' + self._int[dotplace:]
1069 if leftdigits == dotplace:
1070 exp = ''
1071 else:
1072 if context is None:
1073 context = getcontext()
1074 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1075
1076 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001077
1078 def to_eng_string(self, context=None):
1079 """Convert to engineering-type string.
1080
1081 Engineering notation has an exponent which is a multiple of 3, so there
1082 are up to 3 digits left of the decimal place.
1083
1084 Same rules for when in exponential and when as a value as in __str__.
1085 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001086 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001087
1088 def __neg__(self, context=None):
1089 """Returns a copy with the sign switched.
1090
1091 Rounds, if it has reason.
1092 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001093 if self._is_special:
1094 ans = self._check_nans(context=context)
1095 if ans:
1096 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001097
Mark Dickinson37a79fb2011-03-12 11:12:52 +00001098 if context is None:
1099 context = getcontext()
1100
1101 if not self and context.rounding != ROUND_FLOOR:
1102 # -Decimal('0') is Decimal('0'), not Decimal('-0'), except
1103 # in ROUND_FLOOR rounding mode.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001104 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001105 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001106 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001107
Christian Heimes2c181612007-12-17 20:04:13 +00001108 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001109
1110 def __pos__(self, context=None):
1111 """Returns a copy, unless it is a sNaN.
1112
1113 Rounds the number (if more then precision digits)
1114 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001115 if self._is_special:
1116 ans = self._check_nans(context=context)
1117 if ans:
1118 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001119
Mark Dickinson37a79fb2011-03-12 11:12:52 +00001120 if context is None:
1121 context = getcontext()
1122
1123 if not self and context.rounding != ROUND_FLOOR:
1124 # + (-0) = 0, except in ROUND_FLOOR rounding mode.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001125 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001126 else:
1127 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001128
Christian Heimes2c181612007-12-17 20:04:13 +00001129 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001130
Christian Heimes2c181612007-12-17 20:04:13 +00001131 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001132 """Returns the absolute value of self.
1133
Christian Heimes2c181612007-12-17 20:04:13 +00001134 If the keyword argument 'round' is false, do not round. The
1135 expression self.__abs__(round=False) is equivalent to
1136 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001137 """
Christian Heimes2c181612007-12-17 20:04:13 +00001138 if not round:
1139 return self.copy_abs()
1140
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001141 if self._is_special:
1142 ans = self._check_nans(context=context)
1143 if ans:
1144 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001145
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001146 if self._sign:
1147 ans = self.__neg__(context=context)
1148 else:
1149 ans = self.__pos__(context=context)
1150
1151 return ans
1152
1153 def __add__(self, other, context=None):
1154 """Returns self + other.
1155
1156 -INF + INF (or the reverse) cause InvalidOperation errors.
1157 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001158 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001159 if other is NotImplemented:
1160 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001161
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001162 if context is None:
1163 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001164
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001165 if self._is_special or other._is_special:
1166 ans = self._check_nans(other, context)
1167 if ans:
1168 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001169
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001170 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001171 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001172 if self._sign != other._sign and other._isinfinity():
1173 return context._raise_error(InvalidOperation, '-INF + INF')
1174 return Decimal(self)
1175 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001176 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001177
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001178 exp = min(self._exp, other._exp)
1179 negativezero = 0
1180 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001181 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001182 negativezero = 1
1183
1184 if not self and not other:
1185 sign = min(self._sign, other._sign)
1186 if negativezero:
1187 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001188 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001189 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001190 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001191 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001192 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001193 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001194 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001195 return ans
1196 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001197 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001198 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001199 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001200 return ans
1201
1202 op1 = _WorkRep(self)
1203 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001204 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001205
1206 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001207 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001208 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001209 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001210 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001211 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001212 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001213 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001214 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001215 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001216 if op1.sign == 1:
1217 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001218 op1.sign, op2.sign = op2.sign, op1.sign
1219 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001220 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001221 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001222 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001223 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001224 op1.sign, op2.sign = (0, 0)
1225 else:
1226 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001227 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001228
Raymond Hettinger17931de2004-10-27 06:21:46 +00001229 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001230 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001231 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001232 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001233
1234 result.exp = op1.exp
1235 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001236 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001237 return ans
1238
1239 __radd__ = __add__
1240
1241 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001242 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001243 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001244 if other is NotImplemented:
1245 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001246
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001247 if self._is_special or other._is_special:
1248 ans = self._check_nans(other, context=context)
1249 if ans:
1250 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001251
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001252 # self - other is computed as self + other.copy_negate()
1253 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001254
1255 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001256 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001257 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001258 if other is NotImplemented:
1259 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001260
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001261 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001262
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001263 def __mul__(self, other, context=None):
1264 """Return self * other.
1265
1266 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1267 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001268 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001269 if other is NotImplemented:
1270 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001271
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001272 if context is None:
1273 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001274
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001275 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001276
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001277 if self._is_special or other._is_special:
1278 ans = self._check_nans(other, context)
1279 if ans:
1280 return ans
1281
1282 if self._isinfinity():
1283 if not other:
1284 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001285 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001286
1287 if other._isinfinity():
1288 if not self:
1289 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001290 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001291
1292 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001293
1294 # Special case for multiplying by zero
1295 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001296 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001297 # Fixing in case the exponent is out of bounds
1298 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001299 return ans
1300
1301 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001302 if self._int == '1':
1303 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001304 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001305 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001306 if other._int == '1':
1307 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001308 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001309 return ans
1310
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001311 op1 = _WorkRep(self)
1312 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001313
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001314 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001315 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001316
1317 return ans
1318 __rmul__ = __mul__
1319
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001320 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001321 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001322 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001323 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001324 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001325
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001326 if context is None:
1327 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001328
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001329 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001330
1331 if self._is_special or other._is_special:
1332 ans = self._check_nans(other, context)
1333 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001334 return ans
1335
1336 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001337 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001338
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001339 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001340 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001341
1342 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001343 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001344 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001345
1346 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001347 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001348 if not self:
1349 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001350 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001351
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001352 if not self:
1353 exp = self._exp - other._exp
1354 coeff = 0
1355 else:
1356 # OK, so neither = 0, INF or NaN
1357 shift = len(other._int) - len(self._int) + context.prec + 1
1358 exp = self._exp - other._exp - shift
1359 op1 = _WorkRep(self)
1360 op2 = _WorkRep(other)
1361 if shift >= 0:
1362 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1363 else:
1364 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1365 if remainder:
1366 # result is not exact; adjust to ensure correct rounding
1367 if coeff % 5 == 0:
1368 coeff += 1
1369 else:
1370 # result is exact; get as close to ideal exponent as possible
1371 ideal_exp = self._exp - other._exp
1372 while exp < ideal_exp and coeff % 10 == 0:
1373 coeff //= 10
1374 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001375
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001376 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001377 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001378
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001379 def _divide(self, other, context):
1380 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001381
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001382 Assumes that neither self nor other is a NaN, that self is not
1383 infinite and that other is nonzero.
1384 """
1385 sign = self._sign ^ other._sign
1386 if other._isinfinity():
1387 ideal_exp = self._exp
1388 else:
1389 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001390
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001391 expdiff = self.adjusted() - other.adjusted()
1392 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001393 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001394 self._rescale(ideal_exp, context.rounding))
1395 if expdiff <= context.prec:
1396 op1 = _WorkRep(self)
1397 op2 = _WorkRep(other)
1398 if op1.exp >= op2.exp:
1399 op1.int *= 10**(op1.exp - op2.exp)
1400 else:
1401 op2.int *= 10**(op2.exp - op1.exp)
1402 q, r = divmod(op1.int, op2.int)
1403 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001404 return (_dec_from_triple(sign, str(q), 0),
1405 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001406
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001407 # Here the quotient is too large to be representable
1408 ans = context._raise_error(DivisionImpossible,
1409 'quotient too large in //, % or divmod')
1410 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001411
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001412 def __rtruediv__(self, other, context=None):
1413 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001414 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001415 if other is NotImplemented:
1416 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001417 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001418
1419 def __divmod__(self, other, context=None):
1420 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001421 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001422 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001423 other = _convert_other(other)
1424 if other is NotImplemented:
1425 return other
1426
1427 if context is None:
1428 context = getcontext()
1429
1430 ans = self._check_nans(other, context)
1431 if ans:
1432 return (ans, ans)
1433
1434 sign = self._sign ^ other._sign
1435 if self._isinfinity():
1436 if other._isinfinity():
1437 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1438 return ans, ans
1439 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001440 return (_SignedInfinity[sign],
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001441 context._raise_error(InvalidOperation, 'INF % x'))
1442
1443 if not other:
1444 if not self:
1445 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1446 return ans, ans
1447 else:
1448 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1449 context._raise_error(InvalidOperation, 'x % 0'))
1450
1451 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001452 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001453 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001454
1455 def __rdivmod__(self, other, context=None):
1456 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001457 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001458 if other is NotImplemented:
1459 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001460 return other.__divmod__(self, context=context)
1461
1462 def __mod__(self, other, context=None):
1463 """
1464 self % other
1465 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001466 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001467 if other is NotImplemented:
1468 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001469
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001470 if context is None:
1471 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001472
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001473 ans = self._check_nans(other, context)
1474 if ans:
1475 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001476
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001477 if self._isinfinity():
1478 return context._raise_error(InvalidOperation, 'INF % x')
1479 elif not other:
1480 if self:
1481 return context._raise_error(InvalidOperation, 'x % 0')
1482 else:
1483 return context._raise_error(DivisionUndefined, '0 % 0')
1484
1485 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001486 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001487 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001488
1489 def __rmod__(self, other, context=None):
1490 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001491 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001492 if other is NotImplemented:
1493 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001494 return other.__mod__(self, context=context)
1495
1496 def remainder_near(self, other, context=None):
1497 """
1498 Remainder nearest to 0- abs(remainder-near) <= other/2
1499 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001500 if context is None:
1501 context = getcontext()
1502
1503 other = _convert_other(other, raiseit=True)
1504
1505 ans = self._check_nans(other, context)
1506 if ans:
1507 return ans
1508
1509 # self == +/-infinity -> InvalidOperation
1510 if self._isinfinity():
1511 return context._raise_error(InvalidOperation,
1512 'remainder_near(infinity, x)')
1513
1514 # other == 0 -> either InvalidOperation or DivisionUndefined
1515 if not other:
1516 if self:
1517 return context._raise_error(InvalidOperation,
1518 'remainder_near(x, 0)')
1519 else:
1520 return context._raise_error(DivisionUndefined,
1521 'remainder_near(0, 0)')
1522
1523 # other = +/-infinity -> remainder = self
1524 if other._isinfinity():
1525 ans = Decimal(self)
1526 return ans._fix(context)
1527
1528 # self = 0 -> remainder = self, with ideal exponent
1529 ideal_exponent = min(self._exp, other._exp)
1530 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001531 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001532 return ans._fix(context)
1533
1534 # catch most cases of large or small quotient
1535 expdiff = self.adjusted() - other.adjusted()
1536 if expdiff >= context.prec + 1:
1537 # expdiff >= prec+1 => abs(self/other) > 10**prec
1538 return context._raise_error(DivisionImpossible)
1539 if expdiff <= -2:
1540 # expdiff <= -2 => abs(self/other) < 0.1
1541 ans = self._rescale(ideal_exponent, context.rounding)
1542 return ans._fix(context)
1543
1544 # adjust both arguments to have the same exponent, then divide
1545 op1 = _WorkRep(self)
1546 op2 = _WorkRep(other)
1547 if op1.exp >= op2.exp:
1548 op1.int *= 10**(op1.exp - op2.exp)
1549 else:
1550 op2.int *= 10**(op2.exp - op1.exp)
1551 q, r = divmod(op1.int, op2.int)
1552 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1553 # 10**ideal_exponent. Apply correction to ensure that
1554 # abs(remainder) <= abs(other)/2
1555 if 2*r + (q&1) > op2.int:
1556 r -= op2.int
1557 q += 1
1558
1559 if q >= 10**context.prec:
1560 return context._raise_error(DivisionImpossible)
1561
1562 # result has same sign as self unless r is negative
1563 sign = self._sign
1564 if r < 0:
1565 sign = 1-sign
1566 r = -r
1567
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001568 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001569 return ans._fix(context)
1570
1571 def __floordiv__(self, other, context=None):
1572 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001573 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001574 if other is NotImplemented:
1575 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001576
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001577 if context is None:
1578 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001579
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001580 ans = self._check_nans(other, context)
1581 if ans:
1582 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001583
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001584 if self._isinfinity():
1585 if other._isinfinity():
1586 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001587 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001588 return _SignedInfinity[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001589
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001590 if not other:
1591 if self:
1592 return context._raise_error(DivisionByZero, 'x // 0',
1593 self._sign ^ other._sign)
1594 else:
1595 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001596
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001597 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001598
1599 def __rfloordiv__(self, other, context=None):
1600 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001601 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001602 if other is NotImplemented:
1603 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001604 return other.__floordiv__(self, context=context)
1605
1606 def __float__(self):
1607 """Float representation."""
Mark Dickinsonfc33d4c2012-08-24 18:53:10 +01001608 if self._isnan():
1609 if self.is_snan():
1610 raise ValueError("Cannot convert signaling NaN to float")
1611 s = "-nan" if self._sign else "nan"
1612 else:
1613 s = str(self)
1614 return float(s)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001615
1616 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001617 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001618 if self._is_special:
1619 if self._isnan():
Mark Dickinson825fce32009-09-07 18:08:12 +00001620 raise ValueError("Cannot convert NaN to integer")
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001621 elif self._isinfinity():
Mark Dickinson825fce32009-09-07 18:08:12 +00001622 raise OverflowError("Cannot convert infinity to integer")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001623 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001624 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001625 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001626 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001627 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001628
Christian Heimes969fe572008-01-25 11:23:10 +00001629 __trunc__ = __int__
1630
Christian Heimes0bd4e112008-02-12 22:59:25 +00001631 def real(self):
1632 return self
Mark Dickinson315a20a2009-01-04 21:34:18 +00001633 real = property(real)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001634
Christian Heimes0bd4e112008-02-12 22:59:25 +00001635 def imag(self):
1636 return Decimal(0)
Mark Dickinson315a20a2009-01-04 21:34:18 +00001637 imag = property(imag)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001638
1639 def conjugate(self):
1640 return self
1641
1642 def __complex__(self):
1643 return complex(float(self))
1644
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001645 def _fix_nan(self, context):
1646 """Decapitate the payload of a NaN to fit the context"""
1647 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001648
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001649 # maximum length of payload is precision if clamp=0,
1650 # precision-1 if clamp=1.
1651 max_payload_len = context.prec - context.clamp
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001652 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001653 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1654 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001655 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001656
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001657 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001658 """Round if it is necessary to keep self within prec precision.
1659
1660 Rounds and fixes the exponent. Does not raise on a sNaN.
1661
1662 Arguments:
1663 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001664 context - context used.
1665 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001666
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001667 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001668 if self._isnan():
1669 # decapitate payload if necessary
1670 return self._fix_nan(context)
1671 else:
1672 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001673 return Decimal(self)
1674
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001675 # if self is zero then exponent should be between Etiny and
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001676 # Emax if clamp==0, and between Etiny and Etop if clamp==1.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001677 Etiny = context.Etiny()
1678 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001679 if not self:
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001680 exp_max = [context.Emax, Etop][context.clamp]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001681 new_exp = min(max(self._exp, Etiny), exp_max)
1682 if new_exp != self._exp:
1683 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001684 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001685 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001686 return Decimal(self)
1687
1688 # exp_min is the smallest allowable exponent of the result,
1689 # equal to max(self.adjusted()-context.prec+1, Etiny)
1690 exp_min = len(self._int) + self._exp - context.prec
1691 if exp_min > Etop:
1692 # overflow: exp_min > Etop iff self.adjusted() > Emax
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001693 ans = context._raise_error(Overflow, 'above Emax', self._sign)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001694 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001695 context._raise_error(Rounded)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001696 return ans
1697
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001698 self_is_subnormal = exp_min < Etiny
1699 if self_is_subnormal:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001700 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001701
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001702 # round if self has too many digits
1703 if self._exp < exp_min:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001704 digits = len(self._int) + self._exp - exp_min
1705 if digits < 0:
1706 self = _dec_from_triple(self._sign, '1', exp_min-1)
1707 digits = 0
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001708 rounding_method = self._pick_rounding_function[context.rounding]
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04001709 changed = rounding_method(self, digits)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001710 coeff = self._int[:digits] or '0'
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001711 if changed > 0:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001712 coeff = str(int(coeff)+1)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001713 if len(coeff) > context.prec:
1714 coeff = coeff[:-1]
1715 exp_min += 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001716
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001717 # check whether the rounding pushed the exponent out of range
1718 if exp_min > Etop:
1719 ans = context._raise_error(Overflow, 'above Emax', self._sign)
1720 else:
1721 ans = _dec_from_triple(self._sign, coeff, exp_min)
1722
1723 # raise the appropriate signals, taking care to respect
1724 # the precedence described in the specification
1725 if changed and self_is_subnormal:
1726 context._raise_error(Underflow)
1727 if self_is_subnormal:
1728 context._raise_error(Subnormal)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001729 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001730 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001731 context._raise_error(Rounded)
1732 if not ans:
1733 # raise Clamped on underflow to 0
1734 context._raise_error(Clamped)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001735 return ans
1736
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001737 if self_is_subnormal:
1738 context._raise_error(Subnormal)
1739
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001740 # fold down if clamp == 1 and self has too few digits
1741 if context.clamp == 1 and self._exp > Etop:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001742 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001743 self_padded = self._int + '0'*(self._exp - Etop)
1744 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001745
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001746 # here self was representable to begin with; return unchanged
1747 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001748
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001749 # for each of the rounding functions below:
1750 # self is a finite, nonzero Decimal
1751 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001752 #
1753 # each function returns either -1, 0, or 1, as follows:
1754 # 1 indicates that self should be rounded up (away from zero)
1755 # 0 indicates that self should be truncated, and that all the
1756 # digits to be truncated are zeros (so the value is unchanged)
1757 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001758
1759 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001760 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001761 if _all_zeros(self._int, prec):
1762 return 0
1763 else:
1764 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001765
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001766 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001767 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001768 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001769
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001770 def _round_half_up(self, prec):
1771 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001772 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001773 return 1
1774 elif _all_zeros(self._int, prec):
1775 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001776 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001777 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001778
1779 def _round_half_down(self, prec):
1780 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001781 if _exact_half(self._int, prec):
1782 return -1
1783 else:
1784 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001785
1786 def _round_half_even(self, prec):
1787 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001788 if _exact_half(self._int, prec) and \
1789 (prec == 0 or self._int[prec-1] in '02468'):
1790 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001791 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001792 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001793
1794 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001795 """Rounds up (not away from 0 if negative.)"""
1796 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001797 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001798 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001799 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001800
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001801 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001802 """Rounds down (not towards 0 if negative)"""
1803 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001804 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001805 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001806 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001807
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001808 def _round_05up(self, prec):
1809 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001810 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001811 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001812 else:
1813 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001814
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04001815 _pick_rounding_function = dict(
1816 ROUND_DOWN = _round_down,
1817 ROUND_UP = _round_up,
1818 ROUND_HALF_UP = _round_half_up,
1819 ROUND_HALF_DOWN = _round_half_down,
1820 ROUND_HALF_EVEN = _round_half_even,
1821 ROUND_CEILING = _round_ceiling,
1822 ROUND_FLOOR = _round_floor,
1823 ROUND_05UP = _round_05up,
1824 )
1825
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001826 def __round__(self, n=None):
1827 """Round self to the nearest integer, or to a given precision.
1828
1829 If only one argument is supplied, round a finite Decimal
1830 instance self to the nearest integer. If self is infinite or
1831 a NaN then a Python exception is raised. If self is finite
1832 and lies exactly halfway between two integers then it is
1833 rounded to the integer with even last digit.
1834
1835 >>> round(Decimal('123.456'))
1836 123
1837 >>> round(Decimal('-456.789'))
1838 -457
1839 >>> round(Decimal('-3.0'))
1840 -3
1841 >>> round(Decimal('2.5'))
1842 2
1843 >>> round(Decimal('3.5'))
1844 4
1845 >>> round(Decimal('Inf'))
1846 Traceback (most recent call last):
1847 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001848 OverflowError: cannot round an infinity
1849 >>> round(Decimal('NaN'))
1850 Traceback (most recent call last):
1851 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001852 ValueError: cannot round a NaN
1853
1854 If a second argument n is supplied, self is rounded to n
1855 decimal places using the rounding mode for the current
1856 context.
1857
1858 For an integer n, round(self, -n) is exactly equivalent to
1859 self.quantize(Decimal('1En')).
1860
1861 >>> round(Decimal('123.456'), 0)
1862 Decimal('123')
1863 >>> round(Decimal('123.456'), 2)
1864 Decimal('123.46')
1865 >>> round(Decimal('123.456'), -2)
1866 Decimal('1E+2')
1867 >>> round(Decimal('-Infinity'), 37)
1868 Decimal('NaN')
1869 >>> round(Decimal('sNaN123'), 0)
1870 Decimal('NaN123')
1871
1872 """
1873 if n is not None:
1874 # two-argument form: use the equivalent quantize call
1875 if not isinstance(n, int):
1876 raise TypeError('Second argument to round should be integral')
1877 exp = _dec_from_triple(0, '1', -n)
1878 return self.quantize(exp)
1879
1880 # one-argument form
1881 if self._is_special:
1882 if self.is_nan():
1883 raise ValueError("cannot round a NaN")
1884 else:
1885 raise OverflowError("cannot round an infinity")
1886 return int(self._rescale(0, ROUND_HALF_EVEN))
1887
1888 def __floor__(self):
1889 """Return the floor of self, as an integer.
1890
1891 For a finite Decimal instance self, return the greatest
1892 integer n such that n <= self. If self is infinite or a NaN
1893 then a Python exception is raised.
1894
1895 """
1896 if self._is_special:
1897 if self.is_nan():
1898 raise ValueError("cannot round a NaN")
1899 else:
1900 raise OverflowError("cannot round an infinity")
1901 return int(self._rescale(0, ROUND_FLOOR))
1902
1903 def __ceil__(self):
1904 """Return the ceiling of self, as an integer.
1905
1906 For a finite Decimal instance self, return the least integer n
1907 such that n >= self. If self is infinite or a NaN then a
1908 Python exception is raised.
1909
1910 """
1911 if self._is_special:
1912 if self.is_nan():
1913 raise ValueError("cannot round a NaN")
1914 else:
1915 raise OverflowError("cannot round an infinity")
1916 return int(self._rescale(0, ROUND_CEILING))
1917
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001918 def fma(self, other, third, context=None):
1919 """Fused multiply-add.
1920
1921 Returns self*other+third with no rounding of the intermediate
1922 product self*other.
1923
1924 self and other are multiplied together, with no rounding of
1925 the result. The third operand is then added to the result,
1926 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001927 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001928
1929 other = _convert_other(other, raiseit=True)
Mark Dickinsonb455e582011-05-22 12:53:18 +01001930 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001931
1932 # compute product; raise InvalidOperation if either operand is
1933 # a signaling NaN or if the product is zero times infinity.
1934 if self._is_special or other._is_special:
1935 if context is None:
1936 context = getcontext()
1937 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001938 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001939 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001940 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001941 if self._exp == 'n':
1942 product = self
1943 elif other._exp == 'n':
1944 product = other
1945 elif self._exp == 'F':
1946 if not other:
1947 return context._raise_error(InvalidOperation,
1948 'INF * 0 in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001949 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001950 elif other._exp == 'F':
1951 if not self:
1952 return context._raise_error(InvalidOperation,
1953 '0 * INF in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001954 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001955 else:
1956 product = _dec_from_triple(self._sign ^ other._sign,
1957 str(int(self._int) * int(other._int)),
1958 self._exp + other._exp)
1959
Christian Heimes8b0facf2007-12-04 19:30:01 +00001960 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001961
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001962 def _power_modulo(self, other, modulo, context=None):
1963 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001964
Stefan Krah1919b7e2012-03-21 18:25:23 +01001965 other = _convert_other(other)
1966 if other is NotImplemented:
1967 return other
1968 modulo = _convert_other(modulo)
1969 if modulo is NotImplemented:
1970 return modulo
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001971
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001972 if context is None:
1973 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001974
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001975 # deal with NaNs: if there are any sNaNs then first one wins,
1976 # (i.e. behaviour for NaNs is identical to that of fma)
1977 self_is_nan = self._isnan()
1978 other_is_nan = other._isnan()
1979 modulo_is_nan = modulo._isnan()
1980 if self_is_nan or other_is_nan or modulo_is_nan:
1981 if self_is_nan == 2:
1982 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001983 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001984 if other_is_nan == 2:
1985 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001986 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001987 if modulo_is_nan == 2:
1988 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001989 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001990 if self_is_nan:
1991 return self._fix_nan(context)
1992 if other_is_nan:
1993 return other._fix_nan(context)
1994 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001995
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001996 # check inputs: we apply same restrictions as Python's pow()
1997 if not (self._isinteger() and
1998 other._isinteger() and
1999 modulo._isinteger()):
2000 return context._raise_error(InvalidOperation,
2001 'pow() 3rd argument not allowed '
2002 'unless all arguments are integers')
2003 if other < 0:
2004 return context._raise_error(InvalidOperation,
2005 'pow() 2nd argument cannot be '
2006 'negative when 3rd argument specified')
2007 if not modulo:
2008 return context._raise_error(InvalidOperation,
2009 'pow() 3rd argument cannot be 0')
2010
2011 # additional restriction for decimal: the modulus must be less
2012 # than 10**prec in absolute value
2013 if modulo.adjusted() >= context.prec:
2014 return context._raise_error(InvalidOperation,
2015 'insufficient precision: pow() 3rd '
2016 'argument must not have more than '
2017 'precision digits')
2018
2019 # define 0**0 == NaN, for consistency with two-argument pow
2020 # (even though it hurts!)
2021 if not other and not self:
2022 return context._raise_error(InvalidOperation,
2023 'at least one of pow() 1st argument '
2024 'and 2nd argument must be nonzero ;'
2025 '0**0 is not defined')
2026
2027 # compute sign of result
2028 if other._iseven():
2029 sign = 0
2030 else:
2031 sign = self._sign
2032
2033 # convert modulo to a Python integer, and self and other to
2034 # Decimal integers (i.e. force their exponents to be >= 0)
2035 modulo = abs(int(modulo))
2036 base = _WorkRep(self.to_integral_value())
2037 exponent = _WorkRep(other.to_integral_value())
2038
2039 # compute result using integer pow()
2040 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
2041 for i in range(exponent.exp):
2042 base = pow(base, 10, modulo)
2043 base = pow(base, exponent.int, modulo)
2044
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002045 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002046
2047 def _power_exact(self, other, p):
2048 """Attempt to compute self**other exactly.
2049
2050 Given Decimals self and other and an integer p, attempt to
2051 compute an exact result for the power self**other, with p
2052 digits of precision. Return None if self**other is not
2053 exactly representable in p digits.
2054
2055 Assumes that elimination of special cases has already been
2056 performed: self and other must both be nonspecial; self must
2057 be positive and not numerically equal to 1; other must be
2058 nonzero. For efficiency, other._exp should not be too large,
2059 so that 10**abs(other._exp) is a feasible calculation."""
2060
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002061 # In the comments below, we write x for the value of self and y for the
2062 # value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc
2063 # and yc positive integers not divisible by 10.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002064
2065 # The main purpose of this method is to identify the *failure*
2066 # of x**y to be exactly representable with as little effort as
2067 # possible. So we look for cheap and easy tests that
2068 # eliminate the possibility of x**y being exact. Only if all
2069 # these tests are passed do we go on to actually compute x**y.
2070
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002071 # Here's the main idea. Express y as a rational number m/n, with m and
2072 # n relatively prime and n>0. Then for x**y to be exactly
2073 # representable (at *any* precision), xc must be the nth power of a
2074 # positive integer and xe must be divisible by n. If y is negative
2075 # then additionally xc must be a power of either 2 or 5, hence a power
2076 # of 2**n or 5**n.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002077 #
2078 # There's a limit to how small |y| can be: if y=m/n as above
2079 # then:
2080 #
2081 # (1) if xc != 1 then for the result to be representable we
2082 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
2083 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
2084 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
2085 # representable.
2086 #
2087 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
2088 # |y| < 1/|xe| then the result is not representable.
2089 #
2090 # Note that since x is not equal to 1, at least one of (1) and
2091 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2092 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2093 #
2094 # There's also a limit to how large y can be, at least if it's
2095 # positive: the normalized result will have coefficient xc**y,
2096 # so if it's representable then xc**y < 10**p, and y <
2097 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
2098 # not exactly representable.
2099
2100 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2101 # so |y| < 1/xe and the result is not representable.
2102 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2103 # < 1/nbits(xc).
2104
2105 x = _WorkRep(self)
2106 xc, xe = x.int, x.exp
2107 while xc % 10 == 0:
2108 xc //= 10
2109 xe += 1
2110
2111 y = _WorkRep(other)
2112 yc, ye = y.int, y.exp
2113 while yc % 10 == 0:
2114 yc //= 10
2115 ye += 1
2116
2117 # case where xc == 1: result is 10**(xe*y), with xe*y
2118 # required to be an integer
2119 if xc == 1:
Mark Dickinsona1236312010-07-08 19:03:34 +00002120 xe *= yc
2121 # result is now 10**(xe * 10**ye); xe * 10**ye must be integral
2122 while xe % 10 == 0:
2123 xe //= 10
2124 ye += 1
2125 if ye < 0:
2126 return None
2127 exponent = xe * 10**ye
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002128 if y.sign == 1:
2129 exponent = -exponent
2130 # if other is a nonnegative integer, use ideal exponent
2131 if other._isinteger() and other._sign == 0:
2132 ideal_exponent = self._exp*int(other)
2133 zeros = min(exponent-ideal_exponent, p-1)
2134 else:
2135 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002136 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002137
2138 # case where y is negative: xc must be either a power
2139 # of 2 or a power of 5.
2140 if y.sign == 1:
2141 last_digit = xc % 10
2142 if last_digit in (2,4,6,8):
2143 # quick test for power of 2
2144 if xc & -xc != xc:
2145 return None
2146 # now xc is a power of 2; e is its exponent
2147 e = _nbits(xc)-1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002148
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002149 # We now have:
2150 #
2151 # x = 2**e * 10**xe, e > 0, and y < 0.
2152 #
2153 # The exact result is:
2154 #
2155 # x**y = 5**(-e*y) * 10**(e*y + xe*y)
2156 #
2157 # provided that both e*y and xe*y are integers. Note that if
2158 # 5**(-e*y) >= 10**p, then the result can't be expressed
2159 # exactly with p digits of precision.
2160 #
2161 # Using the above, we can guard against large values of ye.
2162 # 93/65 is an upper bound for log(10)/log(5), so if
2163 #
2164 # ye >= len(str(93*p//65))
2165 #
2166 # then
2167 #
2168 # -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5),
2169 #
2170 # so 5**(-e*y) >= 10**p, and the coefficient of the result
2171 # can't be expressed in p digits.
2172
2173 # emax >= largest e such that 5**e < 10**p.
2174 emax = p*93//65
2175 if ye >= len(str(emax)):
2176 return None
2177
2178 # Find -e*y and -xe*y; both must be integers
2179 e = _decimal_lshift_exact(e * yc, ye)
2180 xe = _decimal_lshift_exact(xe * yc, ye)
2181 if e is None or xe is None:
2182 return None
2183
2184 if e > emax:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002185 return None
2186 xc = 5**e
2187
2188 elif last_digit == 5:
2189 # e >= log_5(xc) if xc is a power of 5; we have
2190 # equality all the way up to xc=5**2658
2191 e = _nbits(xc)*28//65
2192 xc, remainder = divmod(5**e, xc)
2193 if remainder:
2194 return None
2195 while xc % 5 == 0:
2196 xc //= 5
2197 e -= 1
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002198
2199 # Guard against large values of ye, using the same logic as in
2200 # the 'xc is a power of 2' branch. 10/3 is an upper bound for
2201 # log(10)/log(2).
2202 emax = p*10//3
2203 if ye >= len(str(emax)):
2204 return None
2205
2206 e = _decimal_lshift_exact(e * yc, ye)
2207 xe = _decimal_lshift_exact(xe * yc, ye)
2208 if e is None or xe is None:
2209 return None
2210
2211 if e > emax:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002212 return None
2213 xc = 2**e
2214 else:
2215 return None
2216
2217 if xc >= 10**p:
2218 return None
2219 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002220 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002221
2222 # now y is positive; find m and n such that y = m/n
2223 if ye >= 0:
2224 m, n = yc*10**ye, 1
2225 else:
2226 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2227 return None
2228 xc_bits = _nbits(xc)
2229 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2230 return None
2231 m, n = yc, 10**(-ye)
2232 while m % 2 == n % 2 == 0:
2233 m //= 2
2234 n //= 2
2235 while m % 5 == n % 5 == 0:
2236 m //= 5
2237 n //= 5
2238
2239 # compute nth root of xc*10**xe
2240 if n > 1:
2241 # if 1 < xc < 2**n then xc isn't an nth power
2242 if xc != 1 and xc_bits <= n:
2243 return None
2244
2245 xe, rem = divmod(xe, n)
2246 if rem != 0:
2247 return None
2248
2249 # compute nth root of xc using Newton's method
2250 a = 1 << -(-_nbits(xc)//n) # initial estimate
2251 while True:
2252 q, r = divmod(xc, a**(n-1))
2253 if a <= q:
2254 break
2255 else:
2256 a = (a*(n-1) + q)//n
2257 if not (a == q and r == 0):
2258 return None
2259 xc = a
2260
2261 # now xc*10**xe is the nth root of the original xc*10**xe
2262 # compute mth power of xc*10**xe
2263
2264 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2265 # 10**p and the result is not representable.
2266 if xc > 1 and m > p*100//_log10_lb(xc):
2267 return None
2268 xc = xc**m
2269 xe *= m
2270 if xc > 10**p:
2271 return None
2272
2273 # by this point the result *is* exactly representable
2274 # adjust the exponent to get as close as possible to the ideal
2275 # exponent, if necessary
2276 str_xc = str(xc)
2277 if other._isinteger() and other._sign == 0:
2278 ideal_exponent = self._exp*int(other)
2279 zeros = min(xe-ideal_exponent, p-len(str_xc))
2280 else:
2281 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002282 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002283
2284 def __pow__(self, other, modulo=None, context=None):
2285 """Return self ** other [ % modulo].
2286
2287 With two arguments, compute self**other.
2288
2289 With three arguments, compute (self**other) % modulo. For the
2290 three argument form, the following restrictions on the
2291 arguments hold:
2292
2293 - all three arguments must be integral
2294 - other must be nonnegative
2295 - either self or other (or both) must be nonzero
2296 - modulo must be nonzero and must have at most p digits,
2297 where p is the context precision.
2298
2299 If any of these restrictions is violated the InvalidOperation
2300 flag is raised.
2301
2302 The result of pow(self, other, modulo) is identical to the
2303 result that would be obtained by computing (self**other) %
2304 modulo with unbounded precision, but is computed more
2305 efficiently. It is always exact.
2306 """
2307
2308 if modulo is not None:
2309 return self._power_modulo(other, modulo, context)
2310
2311 other = _convert_other(other)
2312 if other is NotImplemented:
2313 return other
2314
2315 if context is None:
2316 context = getcontext()
2317
2318 # either argument is a NaN => result is NaN
2319 ans = self._check_nans(other, context)
2320 if ans:
2321 return ans
2322
2323 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2324 if not other:
2325 if not self:
2326 return context._raise_error(InvalidOperation, '0 ** 0')
2327 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002328 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002329
2330 # result has sign 1 iff self._sign is 1 and other is an odd integer
2331 result_sign = 0
2332 if self._sign == 1:
2333 if other._isinteger():
2334 if not other._iseven():
2335 result_sign = 1
2336 else:
2337 # -ve**noninteger = NaN
2338 # (-0)**noninteger = 0**noninteger
2339 if self:
2340 return context._raise_error(InvalidOperation,
2341 'x ** y with x negative and y not an integer')
2342 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002343 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002344
2345 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2346 if not self:
2347 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002348 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002349 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002350 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002351
2352 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002353 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002354 if other._sign == 0:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002355 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002356 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002357 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002358
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002359 # 1**other = 1, but the choice of exponent and the flags
2360 # depend on the exponent of self, and on whether other is a
2361 # positive integer, a negative integer, or neither
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002362 if self == _One:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002363 if other._isinteger():
2364 # exp = max(self._exp*max(int(other), 0),
2365 # 1-context.prec) but evaluating int(other) directly
2366 # is dangerous until we know other is small (other
2367 # could be 1e999999999)
2368 if other._sign == 1:
2369 multiplier = 0
2370 elif other > context.prec:
2371 multiplier = context.prec
2372 else:
2373 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002374
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002375 exp = self._exp * multiplier
2376 if exp < 1-context.prec:
2377 exp = 1-context.prec
2378 context._raise_error(Rounded)
2379 else:
2380 context._raise_error(Inexact)
2381 context._raise_error(Rounded)
2382 exp = 1-context.prec
2383
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002384 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002385
2386 # compute adjusted exponent of self
2387 self_adj = self.adjusted()
2388
2389 # self ** infinity is infinity if self > 1, 0 if self < 1
2390 # self ** -infinity is infinity if self < 1, 0 if self > 1
2391 if other._isinfinity():
2392 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002393 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002394 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002395 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002396
2397 # from here on, the result always goes through the call
2398 # to _fix at the end of this function.
2399 ans = None
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002400 exact = False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002401
2402 # crude test to catch cases of extreme overflow/underflow. If
2403 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2404 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2405 # self**other >= 10**(Emax+1), so overflow occurs. The test
2406 # for underflow is similar.
2407 bound = self._log10_exp_bound() + other.adjusted()
2408 if (self_adj >= 0) == (other._sign == 0):
2409 # self > 1 and other +ve, or self < 1 and other -ve
2410 # possibility of overflow
2411 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002412 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002413 else:
2414 # self > 1 and other -ve, or self < 1 and other +ve
2415 # possibility of underflow to 0
2416 Etiny = context.Etiny()
2417 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002418 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002419
2420 # try for an exact result with precision +1
2421 if ans is None:
2422 ans = self._power_exact(other, context.prec + 1)
Mark Dickinsone42f1bb2010-07-08 19:09:16 +00002423 if ans is not None:
2424 if result_sign == 1:
2425 ans = _dec_from_triple(1, ans._int, ans._exp)
2426 exact = True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002427
2428 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2429 if ans is None:
2430 p = context.prec
2431 x = _WorkRep(self)
2432 xc, xe = x.int, x.exp
2433 y = _WorkRep(other)
2434 yc, ye = y.int, y.exp
2435 if y.sign == 1:
2436 yc = -yc
2437
2438 # compute correctly rounded result: start with precision +3,
2439 # then increase precision until result is unambiguously roundable
2440 extra = 3
2441 while True:
2442 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2443 if coeff % (5*10**(len(str(coeff))-p-1)):
2444 break
2445 extra += 3
2446
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002447 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002448
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002449 # unlike exp, ln and log10, the power function respects the
2450 # rounding mode; no need to switch to ROUND_HALF_EVEN here
2451
2452 # There's a difficulty here when 'other' is not an integer and
2453 # the result is exact. In this case, the specification
2454 # requires that the Inexact flag be raised (in spite of
2455 # exactness), but since the result is exact _fix won't do this
2456 # for us. (Correspondingly, the Underflow signal should also
2457 # be raised for subnormal results.) We can't directly raise
2458 # these signals either before or after calling _fix, since
2459 # that would violate the precedence for signals. So we wrap
2460 # the ._fix call in a temporary context, and reraise
2461 # afterwards.
2462 if exact and not other._isinteger():
2463 # pad with zeros up to length context.prec+1 if necessary; this
2464 # ensures that the Rounded signal will be raised.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002465 if len(ans._int) <= context.prec:
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002466 expdiff = context.prec + 1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002467 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2468 ans._exp-expdiff)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002469
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002470 # create a copy of the current context, with cleared flags/traps
2471 newcontext = context.copy()
2472 newcontext.clear_flags()
2473 for exception in _signals:
2474 newcontext.traps[exception] = 0
2475
2476 # round in the new context
2477 ans = ans._fix(newcontext)
2478
2479 # raise Inexact, and if necessary, Underflow
2480 newcontext._raise_error(Inexact)
2481 if newcontext.flags[Subnormal]:
2482 newcontext._raise_error(Underflow)
2483
2484 # propagate signals to the original context; _fix could
2485 # have raised any of Overflow, Underflow, Subnormal,
2486 # Inexact, Rounded, Clamped. Overflow needs the correct
2487 # arguments. Note that the order of the exceptions is
2488 # important here.
2489 if newcontext.flags[Overflow]:
2490 context._raise_error(Overflow, 'above Emax', ans._sign)
2491 for exception in Underflow, Subnormal, Inexact, Rounded, Clamped:
2492 if newcontext.flags[exception]:
2493 context._raise_error(exception)
2494
2495 else:
2496 ans = ans._fix(context)
2497
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002498 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002499
2500 def __rpow__(self, other, context=None):
2501 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002502 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002503 if other is NotImplemented:
2504 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002505 return other.__pow__(self, context=context)
2506
2507 def normalize(self, context=None):
2508 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002509
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002510 if context is None:
2511 context = getcontext()
2512
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002513 if self._is_special:
2514 ans = self._check_nans(context=context)
2515 if ans:
2516 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002517
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002518 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002519 if dup._isinfinity():
2520 return dup
2521
2522 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002523 return _dec_from_triple(dup._sign, '0', 0)
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00002524 exp_max = [context.Emax, context.Etop()][context.clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002525 end = len(dup._int)
2526 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002527 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002528 exp += 1
2529 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002530 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002531
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002532 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002533 """Quantize self so its exponent is the same as that of exp.
2534
2535 Similar to self._rescale(exp._exp) but with error checking.
2536 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002537 exp = _convert_other(exp, raiseit=True)
2538
2539 if context is None:
2540 context = getcontext()
2541 if rounding is None:
2542 rounding = context.rounding
2543
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002544 if self._is_special or exp._is_special:
2545 ans = self._check_nans(exp, context)
2546 if ans:
2547 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002548
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002549 if exp._isinfinity() or self._isinfinity():
2550 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002551 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002552 return context._raise_error(InvalidOperation,
2553 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002554
2555 # if we're not watching exponents, do a simple rescale
2556 if not watchexp:
2557 ans = self._rescale(exp._exp, rounding)
2558 # raise Inexact and Rounded where appropriate
2559 if ans._exp > self._exp:
2560 context._raise_error(Rounded)
2561 if ans != self:
2562 context._raise_error(Inexact)
2563 return ans
2564
2565 # exp._exp should be between Etiny and Emax
2566 if not (context.Etiny() <= exp._exp <= context.Emax):
2567 return context._raise_error(InvalidOperation,
2568 'target exponent out of bounds in quantize')
2569
2570 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002571 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002572 return ans._fix(context)
2573
2574 self_adjusted = self.adjusted()
2575 if self_adjusted > context.Emax:
2576 return context._raise_error(InvalidOperation,
2577 'exponent of quantize result too large for current context')
2578 if self_adjusted - exp._exp + 1 > context.prec:
2579 return context._raise_error(InvalidOperation,
2580 'quantize result has too many digits for current context')
2581
2582 ans = self._rescale(exp._exp, rounding)
2583 if ans.adjusted() > context.Emax:
2584 return context._raise_error(InvalidOperation,
2585 'exponent of quantize result too large for current context')
2586 if len(ans._int) > context.prec:
2587 return context._raise_error(InvalidOperation,
2588 'quantize result has too many digits for current context')
2589
2590 # raise appropriate flags
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002591 if ans and ans.adjusted() < context.Emin:
2592 context._raise_error(Subnormal)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002593 if ans._exp > self._exp:
2594 if ans != self:
2595 context._raise_error(Inexact)
2596 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002597
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002598 # call to fix takes care of any necessary folddown, and
2599 # signals Clamped if necessary
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002600 ans = ans._fix(context)
2601 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002602
Stefan Krah040e3112012-12-15 22:33:33 +01002603 def same_quantum(self, other, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002604 """Return True if self and other have the same exponent; otherwise
2605 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002606
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002607 If either operand is a special value, the following rules are used:
2608 * return True if both operands are infinities
2609 * return True if both operands are NaNs
2610 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002611 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002612 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002613 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002614 return (self.is_nan() and other.is_nan() or
2615 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002616 return self._exp == other._exp
2617
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002618 def _rescale(self, exp, rounding):
2619 """Rescale self so that the exponent is exp, either by padding with zeros
2620 or by truncating digits, using the given rounding mode.
2621
2622 Specials are returned without change. This operation is
2623 quiet: it raises no flags, and uses no information from the
2624 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002625
2626 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002627 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002628 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002629 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002630 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002631 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002632 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002633
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002634 if self._exp >= exp:
2635 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002636 return _dec_from_triple(self._sign,
2637 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002638
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002639 # too many digits; round and lose data. If self.adjusted() <
2640 # exp-1, replace self by 10**(exp-1) before rounding
2641 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002642 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002643 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002644 digits = 0
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04002645 this_function = self._pick_rounding_function[rounding]
2646 changed = this_function(self, digits)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002647 coeff = self._int[:digits] or '0'
2648 if changed == 1:
2649 coeff = str(int(coeff)+1)
2650 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002651
Christian Heimesf16baeb2008-02-29 14:57:44 +00002652 def _round(self, places, rounding):
2653 """Round a nonzero, nonspecial Decimal to a fixed number of
2654 significant figures, using the given rounding mode.
2655
2656 Infinities, NaNs and zeros are returned unaltered.
2657
2658 This operation is quiet: it raises no flags, and uses no
2659 information from the context.
2660
2661 """
2662 if places <= 0:
2663 raise ValueError("argument should be at least 1 in _round")
2664 if self._is_special or not self:
2665 return Decimal(self)
2666 ans = self._rescale(self.adjusted()+1-places, rounding)
2667 # it can happen that the rescale alters the adjusted exponent;
2668 # for example when rounding 99.97 to 3 significant figures.
2669 # When this happens we end up with an extra 0 at the end of
2670 # the number; a second rescale fixes this.
2671 if ans.adjusted() != self.adjusted():
2672 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2673 return ans
2674
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002675 def to_integral_exact(self, rounding=None, context=None):
2676 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002677
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002678 If no rounding mode is specified, take the rounding mode from
2679 the context. This method raises the Rounded and Inexact flags
2680 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002681
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002682 See also: to_integral_value, which does exactly the same as
2683 this method except that it doesn't raise Inexact or Rounded.
2684 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002685 if self._is_special:
2686 ans = self._check_nans(context=context)
2687 if ans:
2688 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002689 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002690 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002691 return Decimal(self)
2692 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002693 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002694 if context is None:
2695 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002696 if rounding is None:
2697 rounding = context.rounding
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002698 ans = self._rescale(0, rounding)
2699 if ans != self:
2700 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002701 context._raise_error(Rounded)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002702 return ans
2703
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002704 def to_integral_value(self, rounding=None, context=None):
2705 """Rounds to the nearest integer, without raising inexact, rounded."""
2706 if context is None:
2707 context = getcontext()
2708 if rounding is None:
2709 rounding = context.rounding
2710 if self._is_special:
2711 ans = self._check_nans(context=context)
2712 if ans:
2713 return ans
2714 return Decimal(self)
2715 if self._exp >= 0:
2716 return Decimal(self)
2717 else:
2718 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002719
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002720 # the method name changed, but we provide also the old one, for compatibility
2721 to_integral = to_integral_value
2722
2723 def sqrt(self, context=None):
2724 """Return the square root of self."""
Christian Heimes0348fb62008-03-26 12:55:56 +00002725 if context is None:
2726 context = getcontext()
2727
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002728 if self._is_special:
2729 ans = self._check_nans(context=context)
2730 if ans:
2731 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002732
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002733 if self._isinfinity() and self._sign == 0:
2734 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002735
2736 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002737 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002738 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002739 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002740
2741 if self._sign == 1:
2742 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2743
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002744 # At this point self represents a positive number. Let p be
2745 # the desired precision and express self in the form c*100**e
2746 # with c a positive real number and e an integer, c and e
2747 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2748 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2749 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2750 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2751 # the closest integer to sqrt(c) with the even integer chosen
2752 # in the case of a tie.
2753 #
2754 # To ensure correct rounding in all cases, we use the
2755 # following trick: we compute the square root to an extra
2756 # place (precision p+1 instead of precision p), rounding down.
2757 # Then, if the result is inexact and its last digit is 0 or 5,
2758 # we increase the last digit to 1 or 6 respectively; if it's
2759 # exact we leave the last digit alone. Now the final round to
2760 # p places (or fewer in the case of underflow) will round
2761 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002762
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002763 # use an extra digit of precision
2764 prec = context.prec+1
2765
2766 # write argument in the form c*100**e where e = self._exp//2
2767 # is the 'ideal' exponent, to be used if the square root is
2768 # exactly representable. l is the number of 'digits' of c in
2769 # base 100, so that 100**(l-1) <= c < 100**l.
2770 op = _WorkRep(self)
2771 e = op.exp >> 1
2772 if op.exp & 1:
2773 c = op.int * 10
2774 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002775 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002776 c = op.int
2777 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002778
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002779 # rescale so that c has exactly prec base 100 'digits'
2780 shift = prec-l
2781 if shift >= 0:
2782 c *= 100**shift
2783 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002784 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002785 c, remainder = divmod(c, 100**-shift)
2786 exact = not remainder
2787 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002788
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002789 # find n = floor(sqrt(c)) using Newton's method
2790 n = 10**prec
2791 while True:
2792 q = c//n
2793 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002794 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002795 else:
2796 n = n + q >> 1
2797 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002798
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002799 if exact:
2800 # result is exact; rescale to use ideal exponent e
2801 if shift >= 0:
2802 # assert n % 10**shift == 0
2803 n //= 10**shift
2804 else:
2805 n *= 10**-shift
2806 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002807 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002808 # result is not exact; fix last digit as described above
2809 if n % 5 == 0:
2810 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002811
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002812 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002813
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002814 # round, and fit to current context
2815 context = context._shallow_copy()
2816 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002817 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002818 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002819
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002820 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002821
2822 def max(self, other, context=None):
2823 """Returns the larger value.
2824
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002825 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002826 NaN (and signals if one is sNaN). Also rounds.
2827 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002828 other = _convert_other(other, raiseit=True)
2829
2830 if context is None:
2831 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002832
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002833 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002834 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002835 # number is always returned
2836 sn = self._isnan()
2837 on = other._isnan()
2838 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002839 if on == 1 and sn == 0:
2840 return self._fix(context)
2841 if sn == 1 and on == 0:
2842 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002843 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002844
Christian Heimes77c02eb2008-02-09 02:18:51 +00002845 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002846 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002847 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002848 # then an ordering is applied:
2849 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002850 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002851 # positive sign and min returns the operand with the negative sign
2852 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002853 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002854 # the result. This is exactly the ordering used in compare_total.
2855 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002856
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002857 if c == -1:
2858 ans = other
2859 else:
2860 ans = self
2861
Christian Heimes2c181612007-12-17 20:04:13 +00002862 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002863
2864 def min(self, other, context=None):
2865 """Returns the smaller value.
2866
Guido van Rossumd8faa362007-04-27 19:54:29 +00002867 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002868 NaN (and signals if one is sNaN). Also rounds.
2869 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002870 other = _convert_other(other, raiseit=True)
2871
2872 if context is None:
2873 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002874
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002875 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002876 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002877 # number is always returned
2878 sn = self._isnan()
2879 on = other._isnan()
2880 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002881 if on == 1 and sn == 0:
2882 return self._fix(context)
2883 if sn == 1 and on == 0:
2884 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002885 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002886
Christian Heimes77c02eb2008-02-09 02:18:51 +00002887 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002888 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002889 c = self.compare_total(other)
2890
2891 if c == -1:
2892 ans = self
2893 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002894 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002895
Christian Heimes2c181612007-12-17 20:04:13 +00002896 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002897
2898 def _isinteger(self):
2899 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002900 if self._is_special:
2901 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002902 if self._exp >= 0:
2903 return True
2904 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002905 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002906
2907 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002908 """Returns True if self is even. Assumes self is an integer."""
2909 if not self or self._exp > 0:
2910 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002911 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002912
2913 def adjusted(self):
2914 """Return the adjusted exponent of self"""
2915 try:
2916 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002917 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002918 except TypeError:
2919 return 0
2920
Stefan Krah040e3112012-12-15 22:33:33 +01002921 def canonical(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002922 """Returns the same Decimal object.
2923
2924 As we do not have different encodings for the same number, the
2925 received object already is in its canonical form.
2926 """
2927 return self
2928
2929 def compare_signal(self, other, context=None):
2930 """Compares self to the other operand numerically.
2931
2932 It's pretty much like compare(), but all NaNs signal, with signaling
2933 NaNs taking precedence over quiet NaNs.
2934 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002935 other = _convert_other(other, raiseit = True)
2936 ans = self._compare_check_nans(other, context)
2937 if ans:
2938 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002939 return self.compare(other, context=context)
2940
Stefan Krah040e3112012-12-15 22:33:33 +01002941 def compare_total(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002942 """Compares self to other using the abstract representations.
2943
2944 This is not like the standard compare, which use their numerical
2945 value. Note that a total ordering is defined for all possible abstract
2946 representations.
2947 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00002948 other = _convert_other(other, raiseit=True)
2949
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002950 # if one is negative and the other is positive, it's easy
2951 if self._sign and not other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002952 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002953 if not self._sign and other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002954 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002955 sign = self._sign
2956
2957 # let's handle both NaN types
2958 self_nan = self._isnan()
2959 other_nan = other._isnan()
2960 if self_nan or other_nan:
2961 if self_nan == other_nan:
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002962 # compare payloads as though they're integers
2963 self_key = len(self._int), self._int
2964 other_key = len(other._int), other._int
2965 if self_key < other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002966 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002967 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002968 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002969 return _NegativeOne
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002970 if self_key > other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002971 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002972 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002973 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002974 return _One
2975 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002976
2977 if sign:
2978 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002979 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002980 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002981 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002982 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002983 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002984 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002985 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002986 else:
2987 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002988 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002989 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002990 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002991 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002992 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002993 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002994 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002995
2996 if self < other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002997 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002998 if self > other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002999 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003000
3001 if self._exp < other._exp:
3002 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003003 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003004 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003005 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003006 if self._exp > other._exp:
3007 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003008 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003009 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003010 return _One
3011 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003012
3013
Stefan Krah040e3112012-12-15 22:33:33 +01003014 def compare_total_mag(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003015 """Compares self to other using abstract repr., ignoring sign.
3016
3017 Like compare_total, but with operand's sign ignored and assumed to be 0.
3018 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003019 other = _convert_other(other, raiseit=True)
3020
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003021 s = self.copy_abs()
3022 o = other.copy_abs()
3023 return s.compare_total(o)
3024
3025 def copy_abs(self):
3026 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003027 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003028
3029 def copy_negate(self):
3030 """Returns a copy with the sign inverted."""
3031 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003032 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003033 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003034 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003035
Stefan Krah040e3112012-12-15 22:33:33 +01003036 def copy_sign(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003037 """Returns self with the sign of other."""
Mark Dickinson84230a12010-02-18 14:49:50 +00003038 other = _convert_other(other, raiseit=True)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003039 return _dec_from_triple(other._sign, self._int,
3040 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003041
3042 def exp(self, context=None):
3043 """Returns e ** self."""
3044
3045 if context is None:
3046 context = getcontext()
3047
3048 # exp(NaN) = NaN
3049 ans = self._check_nans(context=context)
3050 if ans:
3051 return ans
3052
3053 # exp(-Infinity) = 0
3054 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003055 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003056
3057 # exp(0) = 1
3058 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003059 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003060
3061 # exp(Infinity) = Infinity
3062 if self._isinfinity() == 1:
3063 return Decimal(self)
3064
3065 # the result is now guaranteed to be inexact (the true
3066 # mathematical result is transcendental). There's no need to
3067 # raise Rounded and Inexact here---they'll always be raised as
3068 # a result of the call to _fix.
3069 p = context.prec
3070 adj = self.adjusted()
3071
3072 # we only need to do any computation for quite a small range
3073 # of adjusted exponents---for example, -29 <= adj <= 10 for
3074 # the default context. For smaller exponent the result is
3075 # indistinguishable from 1 at the given precision, while for
3076 # larger exponent the result either overflows or underflows.
3077 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
3078 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003079 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003080 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
3081 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003082 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003083 elif self._sign == 0 and adj < -p:
3084 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003085 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003086 elif self._sign == 1 and adj < -p-1:
3087 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003088 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003089 # general case
3090 else:
3091 op = _WorkRep(self)
3092 c, e = op.int, op.exp
3093 if op.sign == 1:
3094 c = -c
3095
3096 # compute correctly rounded result: increase precision by
3097 # 3 digits at a time until we get an unambiguously
3098 # roundable result
3099 extra = 3
3100 while True:
3101 coeff, exp = _dexp(c, e, p+extra)
3102 if coeff % (5*10**(len(str(coeff))-p-1)):
3103 break
3104 extra += 3
3105
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003106 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003107
3108 # at this stage, ans should round correctly with *any*
3109 # rounding mode, not just with ROUND_HALF_EVEN
3110 context = context._shallow_copy()
3111 rounding = context._set_rounding(ROUND_HALF_EVEN)
3112 ans = ans._fix(context)
3113 context.rounding = rounding
3114
3115 return ans
3116
3117 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003118 """Return True if self is canonical; otherwise return False.
3119
3120 Currently, the encoding of a Decimal instance is always
3121 canonical, so this method returns True for any Decimal.
3122 """
3123 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003124
3125 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003126 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003127
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003128 A Decimal instance is considered finite if it is neither
3129 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003130 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003131 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003132
3133 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003134 """Return True if self is infinite; otherwise return False."""
3135 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003136
3137 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003138 """Return True if self is a qNaN or sNaN; otherwise return False."""
3139 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003140
3141 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003142 """Return True if self is a normal number; otherwise return False."""
3143 if self._is_special or not self:
3144 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003145 if context is None:
3146 context = getcontext()
Mark Dickinson06bb6742009-10-20 13:38:04 +00003147 return context.Emin <= self.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003148
3149 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003150 """Return True if self is a quiet NaN; otherwise return False."""
3151 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003152
3153 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003154 """Return True if self is negative; otherwise return False."""
3155 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003156
3157 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003158 """Return True if self is a signaling NaN; otherwise return False."""
3159 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003160
3161 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003162 """Return True if self is subnormal; otherwise return False."""
3163 if self._is_special or not self:
3164 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003165 if context is None:
3166 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003167 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003168
3169 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003170 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003171 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003172
3173 def _ln_exp_bound(self):
3174 """Compute a lower bound for the adjusted exponent of self.ln().
3175 In other words, compute r such that self.ln() >= 10**r. Assumes
3176 that self is finite and positive and that self != 1.
3177 """
3178
3179 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
3180 adj = self._exp + len(self._int) - 1
3181 if adj >= 1:
3182 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
3183 return len(str(adj*23//10)) - 1
3184 if adj <= -2:
3185 # argument <= 0.1
3186 return len(str((-1-adj)*23//10)) - 1
3187 op = _WorkRep(self)
3188 c, e = op.int, op.exp
3189 if adj == 0:
3190 # 1 < self < 10
3191 num = str(c-10**-e)
3192 den = str(c)
3193 return len(num) - len(den) - (num < den)
3194 # adj == -1, 0.1 <= self < 1
3195 return e + len(str(10**-e - c)) - 1
3196
3197
3198 def ln(self, context=None):
3199 """Returns the natural (base e) logarithm of self."""
3200
3201 if context is None:
3202 context = getcontext()
3203
3204 # ln(NaN) = NaN
3205 ans = self._check_nans(context=context)
3206 if ans:
3207 return ans
3208
3209 # ln(0.0) == -Infinity
3210 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003211 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003212
3213 # ln(Infinity) = Infinity
3214 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003215 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003216
3217 # ln(1.0) == 0.0
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003218 if self == _One:
3219 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003220
3221 # ln(negative) raises InvalidOperation
3222 if self._sign == 1:
3223 return context._raise_error(InvalidOperation,
3224 'ln of a negative value')
3225
3226 # result is irrational, so necessarily inexact
3227 op = _WorkRep(self)
3228 c, e = op.int, op.exp
3229 p = context.prec
3230
3231 # correctly rounded result: repeatedly increase precision by 3
3232 # until we get an unambiguously roundable result
3233 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3234 while True:
3235 coeff = _dlog(c, e, places)
3236 # assert len(str(abs(coeff)))-p >= 1
3237 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3238 break
3239 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003240 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003241
3242 context = context._shallow_copy()
3243 rounding = context._set_rounding(ROUND_HALF_EVEN)
3244 ans = ans._fix(context)
3245 context.rounding = rounding
3246 return ans
3247
3248 def _log10_exp_bound(self):
3249 """Compute a lower bound for the adjusted exponent of self.log10().
3250 In other words, find r such that self.log10() >= 10**r.
3251 Assumes that self is finite and positive and that self != 1.
3252 """
3253
3254 # For x >= 10 or x < 0.1 we only need a bound on the integer
3255 # part of log10(self), and this comes directly from the
3256 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3257 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3258 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3259
3260 adj = self._exp + len(self._int) - 1
3261 if adj >= 1:
3262 # self >= 10
3263 return len(str(adj))-1
3264 if adj <= -2:
3265 # self < 0.1
3266 return len(str(-1-adj))-1
3267 op = _WorkRep(self)
3268 c, e = op.int, op.exp
3269 if adj == 0:
3270 # 1 < self < 10
3271 num = str(c-10**-e)
3272 den = str(231*c)
3273 return len(num) - len(den) - (num < den) + 2
3274 # adj == -1, 0.1 <= self < 1
3275 num = str(10**-e-c)
3276 return len(num) + e - (num < "231") - 1
3277
3278 def log10(self, context=None):
3279 """Returns the base 10 logarithm of self."""
3280
3281 if context is None:
3282 context = getcontext()
3283
3284 # log10(NaN) = NaN
3285 ans = self._check_nans(context=context)
3286 if ans:
3287 return ans
3288
3289 # log10(0.0) == -Infinity
3290 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003291 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003292
3293 # log10(Infinity) = Infinity
3294 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003295 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003296
3297 # log10(negative or -Infinity) raises InvalidOperation
3298 if self._sign == 1:
3299 return context._raise_error(InvalidOperation,
3300 'log10 of a negative value')
3301
3302 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003303 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003304 # answer may need rounding
3305 ans = Decimal(self._exp + len(self._int) - 1)
3306 else:
3307 # result is irrational, so necessarily inexact
3308 op = _WorkRep(self)
3309 c, e = op.int, op.exp
3310 p = context.prec
3311
3312 # correctly rounded result: repeatedly increase precision
3313 # until result is unambiguously roundable
3314 places = p-self._log10_exp_bound()+2
3315 while True:
3316 coeff = _dlog10(c, e, places)
3317 # assert len(str(abs(coeff)))-p >= 1
3318 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3319 break
3320 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003321 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003322
3323 context = context._shallow_copy()
3324 rounding = context._set_rounding(ROUND_HALF_EVEN)
3325 ans = ans._fix(context)
3326 context.rounding = rounding
3327 return ans
3328
3329 def logb(self, context=None):
3330 """ Returns the exponent of the magnitude of self's MSD.
3331
3332 The result is the integer which is the exponent of the magnitude
3333 of the most significant digit of self (as though it were truncated
3334 to a single digit while maintaining the value of that digit and
3335 without limiting the resulting exponent).
3336 """
3337 # logb(NaN) = NaN
3338 ans = self._check_nans(context=context)
3339 if ans:
3340 return ans
3341
3342 if context is None:
3343 context = getcontext()
3344
3345 # logb(+/-Inf) = +Inf
3346 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003347 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003348
3349 # logb(0) = -Inf, DivisionByZero
3350 if not self:
3351 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3352
3353 # otherwise, simply return the adjusted exponent of self, as a
3354 # Decimal. Note that no attempt is made to fit the result
3355 # into the current context.
Mark Dickinson56df8872009-10-07 19:23:50 +00003356 ans = Decimal(self.adjusted())
3357 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003358
3359 def _islogical(self):
3360 """Return True if self is a logical operand.
3361
Christian Heimes679db4a2008-01-18 09:56:22 +00003362 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003363 an exponent of 0, and a coefficient whose digits must all be
3364 either 0 or 1.
3365 """
3366 if self._sign != 0 or self._exp != 0:
3367 return False
3368 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003369 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003370 return False
3371 return True
3372
3373 def _fill_logical(self, context, opa, opb):
3374 dif = context.prec - len(opa)
3375 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003376 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003377 elif dif < 0:
3378 opa = opa[-context.prec:]
3379 dif = context.prec - len(opb)
3380 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003381 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003382 elif dif < 0:
3383 opb = opb[-context.prec:]
3384 return opa, opb
3385
3386 def logical_and(self, other, context=None):
3387 """Applies an 'and' operation between self and other's digits."""
3388 if context is None:
3389 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003390
3391 other = _convert_other(other, raiseit=True)
3392
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003393 if not self._islogical() or not other._islogical():
3394 return context._raise_error(InvalidOperation)
3395
3396 # fill to context.prec
3397 (opa, opb) = self._fill_logical(context, self._int, other._int)
3398
3399 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003400 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3401 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003402
3403 def logical_invert(self, context=None):
3404 """Invert all its digits."""
3405 if context is None:
3406 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003407 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3408 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003409
3410 def logical_or(self, other, context=None):
3411 """Applies an 'or' operation between self and other's digits."""
3412 if context is None:
3413 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003414
3415 other = _convert_other(other, raiseit=True)
3416
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003417 if not self._islogical() or not other._islogical():
3418 return context._raise_error(InvalidOperation)
3419
3420 # fill to context.prec
3421 (opa, opb) = self._fill_logical(context, self._int, other._int)
3422
3423 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003424 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003425 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003426
3427 def logical_xor(self, other, context=None):
3428 """Applies an 'xor' operation between self and other's digits."""
3429 if context is None:
3430 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003431
3432 other = _convert_other(other, raiseit=True)
3433
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003434 if not self._islogical() or not other._islogical():
3435 return context._raise_error(InvalidOperation)
3436
3437 # fill to context.prec
3438 (opa, opb) = self._fill_logical(context, self._int, other._int)
3439
3440 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003441 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003442 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003443
3444 def max_mag(self, other, context=None):
3445 """Compares the values numerically with their sign ignored."""
3446 other = _convert_other(other, raiseit=True)
3447
3448 if context is None:
3449 context = getcontext()
3450
3451 if self._is_special or other._is_special:
3452 # If one operand is a quiet NaN and the other is number, then the
3453 # number is always returned
3454 sn = self._isnan()
3455 on = other._isnan()
3456 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003457 if on == 1 and sn == 0:
3458 return self._fix(context)
3459 if sn == 1 and on == 0:
3460 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003461 return self._check_nans(other, context)
3462
Christian Heimes77c02eb2008-02-09 02:18:51 +00003463 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003464 if c == 0:
3465 c = self.compare_total(other)
3466
3467 if c == -1:
3468 ans = other
3469 else:
3470 ans = self
3471
Christian Heimes2c181612007-12-17 20:04:13 +00003472 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003473
3474 def min_mag(self, other, context=None):
3475 """Compares the values numerically with their sign ignored."""
3476 other = _convert_other(other, raiseit=True)
3477
3478 if context is None:
3479 context = getcontext()
3480
3481 if self._is_special or other._is_special:
3482 # If one operand is a quiet NaN and the other is number, then the
3483 # number is always returned
3484 sn = self._isnan()
3485 on = other._isnan()
3486 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003487 if on == 1 and sn == 0:
3488 return self._fix(context)
3489 if sn == 1 and on == 0:
3490 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003491 return self._check_nans(other, context)
3492
Christian Heimes77c02eb2008-02-09 02:18:51 +00003493 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003494 if c == 0:
3495 c = self.compare_total(other)
3496
3497 if c == -1:
3498 ans = self
3499 else:
3500 ans = other
3501
Christian Heimes2c181612007-12-17 20:04:13 +00003502 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003503
3504 def next_minus(self, context=None):
3505 """Returns the largest representable number smaller than itself."""
3506 if context is None:
3507 context = getcontext()
3508
3509 ans = self._check_nans(context=context)
3510 if ans:
3511 return ans
3512
3513 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003514 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003515 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003516 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003517
3518 context = context.copy()
3519 context._set_rounding(ROUND_FLOOR)
3520 context._ignore_all_flags()
3521 new_self = self._fix(context)
3522 if new_self != self:
3523 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003524 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3525 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003526
3527 def next_plus(self, context=None):
3528 """Returns the smallest representable number larger than itself."""
3529 if context is None:
3530 context = getcontext()
3531
3532 ans = self._check_nans(context=context)
3533 if ans:
3534 return ans
3535
3536 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003537 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003538 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003539 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003540
3541 context = context.copy()
3542 context._set_rounding(ROUND_CEILING)
3543 context._ignore_all_flags()
3544 new_self = self._fix(context)
3545 if new_self != self:
3546 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003547 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3548 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003549
3550 def next_toward(self, other, context=None):
3551 """Returns the number closest to self, in the direction towards other.
3552
3553 The result is the closest representable number to self
3554 (excluding self) that is in the direction towards other,
3555 unless both have the same value. If the two operands are
3556 numerically equal, then the result is a copy of self with the
3557 sign set to be the same as the sign of other.
3558 """
3559 other = _convert_other(other, raiseit=True)
3560
3561 if context is None:
3562 context = getcontext()
3563
3564 ans = self._check_nans(other, context)
3565 if ans:
3566 return ans
3567
Christian Heimes77c02eb2008-02-09 02:18:51 +00003568 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003569 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003570 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003571
3572 if comparison == -1:
3573 ans = self.next_plus(context)
3574 else: # comparison == 1
3575 ans = self.next_minus(context)
3576
3577 # decide which flags to raise using value of ans
3578 if ans._isinfinity():
3579 context._raise_error(Overflow,
3580 'Infinite result from next_toward',
3581 ans._sign)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003582 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00003583 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003584 elif ans.adjusted() < context.Emin:
3585 context._raise_error(Underflow)
3586 context._raise_error(Subnormal)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003587 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00003588 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003589 # if precision == 1 then we don't raise Clamped for a
3590 # result 0E-Etiny.
3591 if not ans:
3592 context._raise_error(Clamped)
3593
3594 return ans
3595
3596 def number_class(self, context=None):
3597 """Returns an indication of the class of self.
3598
3599 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003600 sNaN
3601 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003602 -Infinity
3603 -Normal
3604 -Subnormal
3605 -Zero
3606 +Zero
3607 +Subnormal
3608 +Normal
3609 +Infinity
3610 """
3611 if self.is_snan():
3612 return "sNaN"
3613 if self.is_qnan():
3614 return "NaN"
3615 inf = self._isinfinity()
3616 if inf == 1:
3617 return "+Infinity"
3618 if inf == -1:
3619 return "-Infinity"
3620 if self.is_zero():
3621 if self._sign:
3622 return "-Zero"
3623 else:
3624 return "+Zero"
3625 if context is None:
3626 context = getcontext()
3627 if self.is_subnormal(context=context):
3628 if self._sign:
3629 return "-Subnormal"
3630 else:
3631 return "+Subnormal"
3632 # just a normal, regular, boring number, :)
3633 if self._sign:
3634 return "-Normal"
3635 else:
3636 return "+Normal"
3637
3638 def radix(self):
3639 """Just returns 10, as this is Decimal, :)"""
3640 return Decimal(10)
3641
3642 def rotate(self, other, context=None):
3643 """Returns a rotated copy of self, value-of-other times."""
3644 if context is None:
3645 context = getcontext()
3646
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003647 other = _convert_other(other, raiseit=True)
3648
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003649 ans = self._check_nans(other, context)
3650 if ans:
3651 return ans
3652
3653 if other._exp != 0:
3654 return context._raise_error(InvalidOperation)
3655 if not (-context.prec <= int(other) <= context.prec):
3656 return context._raise_error(InvalidOperation)
3657
3658 if self._isinfinity():
3659 return Decimal(self)
3660
3661 # get values, pad if necessary
3662 torot = int(other)
3663 rotdig = self._int
3664 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003665 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003666 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003667 elif topad < 0:
3668 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003669
3670 # let's rotate!
3671 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003672 return _dec_from_triple(self._sign,
3673 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003674
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003675 def scaleb(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003676 """Returns self operand after adding the second value to its exp."""
3677 if context is None:
3678 context = getcontext()
3679
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003680 other = _convert_other(other, raiseit=True)
3681
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003682 ans = self._check_nans(other, context)
3683 if ans:
3684 return ans
3685
3686 if other._exp != 0:
3687 return context._raise_error(InvalidOperation)
3688 liminf = -2 * (context.Emax + context.prec)
3689 limsup = 2 * (context.Emax + context.prec)
3690 if not (liminf <= int(other) <= limsup):
3691 return context._raise_error(InvalidOperation)
3692
3693 if self._isinfinity():
3694 return Decimal(self)
3695
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003696 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003697 d = d._fix(context)
3698 return d
3699
3700 def shift(self, other, context=None):
3701 """Returns a shifted copy of self, value-of-other times."""
3702 if context is None:
3703 context = getcontext()
3704
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003705 other = _convert_other(other, raiseit=True)
3706
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003707 ans = self._check_nans(other, context)
3708 if ans:
3709 return ans
3710
3711 if other._exp != 0:
3712 return context._raise_error(InvalidOperation)
3713 if not (-context.prec <= int(other) <= context.prec):
3714 return context._raise_error(InvalidOperation)
3715
3716 if self._isinfinity():
3717 return Decimal(self)
3718
3719 # get values, pad if necessary
3720 torot = int(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003721 rotdig = self._int
3722 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003723 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003724 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003725 elif topad < 0:
3726 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003727
3728 # let's shift!
3729 if torot < 0:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003730 shifted = rotdig[:torot]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003731 else:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003732 shifted = rotdig + '0'*torot
3733 shifted = shifted[-context.prec:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003734
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003735 return _dec_from_triple(self._sign,
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003736 shifted.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003737
Guido van Rossumd8faa362007-04-27 19:54:29 +00003738 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003739 def __reduce__(self):
3740 return (self.__class__, (str(self),))
3741
3742 def __copy__(self):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003743 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003744 return self # I'm immutable; therefore I am my own clone
3745 return self.__class__(str(self))
3746
3747 def __deepcopy__(self, memo):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003748 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003749 return self # My components are also immutable
3750 return self.__class__(str(self))
3751
Mark Dickinson79f52032009-03-17 23:12:51 +00003752 # PEP 3101 support. the _localeconv keyword argument should be
3753 # considered private: it's provided for ease of testing only.
3754 def __format__(self, specifier, context=None, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00003755 """Format a Decimal instance according to the given specifier.
3756
3757 The specifier should be a standard format specifier, with the
3758 form described in PEP 3101. Formatting types 'e', 'E', 'f',
Mark Dickinson79f52032009-03-17 23:12:51 +00003759 'F', 'g', 'G', 'n' and '%' are supported. If the formatting
3760 type is omitted it defaults to 'g' or 'G', depending on the
3761 value of context.capitals.
Christian Heimesf16baeb2008-02-29 14:57:44 +00003762 """
3763
3764 # Note: PEP 3101 says that if the type is not present then
3765 # there should be at least one digit after the decimal point.
3766 # We take the liberty of ignoring this requirement for
3767 # Decimal---it's presumably there to make sure that
3768 # format(float, '') behaves similarly to str(float).
3769 if context is None:
3770 context = getcontext()
3771
Mark Dickinson79f52032009-03-17 23:12:51 +00003772 spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003773
Mark Dickinson79f52032009-03-17 23:12:51 +00003774 # special values don't care about the type or precision
Christian Heimesf16baeb2008-02-29 14:57:44 +00003775 if self._is_special:
Mark Dickinson79f52032009-03-17 23:12:51 +00003776 sign = _format_sign(self._sign, spec)
3777 body = str(self.copy_abs())
Stefan Krah298131a2014-08-26 20:46:49 +02003778 if spec['type'] == '%':
3779 body += '%'
Mark Dickinson79f52032009-03-17 23:12:51 +00003780 return _format_align(sign, body, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003781
3782 # a type of None defaults to 'g' or 'G', depending on context
Christian Heimesf16baeb2008-02-29 14:57:44 +00003783 if spec['type'] is None:
3784 spec['type'] = ['g', 'G'][context.capitals]
Mark Dickinson79f52032009-03-17 23:12:51 +00003785
3786 # if type is '%', adjust exponent of self accordingly
3787 if spec['type'] == '%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003788 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3789
3790 # round if necessary, taking rounding mode from the context
3791 rounding = context.rounding
3792 precision = spec['precision']
3793 if precision is not None:
3794 if spec['type'] in 'eE':
3795 self = self._round(precision+1, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003796 elif spec['type'] in 'fF%':
3797 self = self._rescale(-precision, rounding)
Mark Dickinson79f52032009-03-17 23:12:51 +00003798 elif spec['type'] in 'gG' and len(self._int) > precision:
3799 self = self._round(precision, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003800 # special case: zeros with a positive exponent can't be
3801 # represented in fixed point; rescale them to 0e0.
Mark Dickinson79f52032009-03-17 23:12:51 +00003802 if not self and self._exp > 0 and spec['type'] in 'fF%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003803 self = self._rescale(0, rounding)
3804
3805 # figure out placement of the decimal point
3806 leftdigits = self._exp + len(self._int)
Mark Dickinson79f52032009-03-17 23:12:51 +00003807 if spec['type'] in 'eE':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003808 if not self and precision is not None:
3809 dotplace = 1 - precision
3810 else:
3811 dotplace = 1
Mark Dickinson79f52032009-03-17 23:12:51 +00003812 elif spec['type'] in 'fF%':
3813 dotplace = leftdigits
Christian Heimesf16baeb2008-02-29 14:57:44 +00003814 elif spec['type'] in 'gG':
3815 if self._exp <= 0 and leftdigits > -6:
3816 dotplace = leftdigits
3817 else:
3818 dotplace = 1
3819
Mark Dickinson79f52032009-03-17 23:12:51 +00003820 # find digits before and after decimal point, and get exponent
3821 if dotplace < 0:
3822 intpart = '0'
3823 fracpart = '0'*(-dotplace) + self._int
3824 elif dotplace > len(self._int):
3825 intpart = self._int + '0'*(dotplace-len(self._int))
3826 fracpart = ''
Christian Heimesf16baeb2008-02-29 14:57:44 +00003827 else:
Mark Dickinson79f52032009-03-17 23:12:51 +00003828 intpart = self._int[:dotplace] or '0'
3829 fracpart = self._int[dotplace:]
3830 exp = leftdigits-dotplace
Christian Heimesf16baeb2008-02-29 14:57:44 +00003831
Mark Dickinson79f52032009-03-17 23:12:51 +00003832 # done with the decimal-specific stuff; hand over the rest
3833 # of the formatting to the _format_number function
3834 return _format_number(self._sign, intpart, fracpart, exp, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003835
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003836def _dec_from_triple(sign, coefficient, exponent, special=False):
3837 """Create a decimal instance directly, without any validation,
3838 normalization (e.g. removal of leading zeros) or argument
3839 conversion.
3840
3841 This function is for *internal use only*.
3842 """
3843
3844 self = object.__new__(Decimal)
3845 self._sign = sign
3846 self._int = coefficient
3847 self._exp = exponent
3848 self._is_special = special
3849
3850 return self
3851
Raymond Hettinger82417ca2009-02-03 03:54:28 +00003852# Register Decimal as a kind of Number (an abstract base class).
3853# However, do not register it as Real (because Decimals are not
3854# interoperable with floats).
3855_numbers.Number.register(Decimal)
3856
3857
Guido van Rossumd8faa362007-04-27 19:54:29 +00003858##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003859
Thomas Wouters89f507f2006-12-13 04:49:30 +00003860class _ContextManager(object):
3861 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003862
Thomas Wouters89f507f2006-12-13 04:49:30 +00003863 Sets a copy of the supplied context in __enter__() and restores
3864 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003865 """
3866 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003867 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003868 def __enter__(self):
3869 self.saved_context = getcontext()
3870 setcontext(self.new_context)
3871 return self.new_context
3872 def __exit__(self, t, v, tb):
3873 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003874
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003875class Context(object):
3876 """Contains the context for a Decimal instance.
3877
3878 Contains:
3879 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003880 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003881 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003882 raised when it is caused. Otherwise, a value is
3883 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003884 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003885 (Whether or not the trap_enabler is set)
3886 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003887 Emin - Minimum exponent
3888 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003889 capitals - If 1, 1*10^1 is printed as 1E+1.
3890 If 0, printed as 1e1
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00003891 clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003892 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003893
Stefan Krah1919b7e2012-03-21 18:25:23 +01003894 def __init__(self, prec=None, rounding=None, Emin=None, Emax=None,
3895 capitals=None, clamp=None, flags=None, traps=None,
3896 _ignored_flags=None):
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003897 # Set defaults; for everything except flags and _ignored_flags,
3898 # inherit from DefaultContext.
3899 try:
3900 dc = DefaultContext
3901 except NameError:
3902 pass
3903
3904 self.prec = prec if prec is not None else dc.prec
3905 self.rounding = rounding if rounding is not None else dc.rounding
3906 self.Emin = Emin if Emin is not None else dc.Emin
3907 self.Emax = Emax if Emax is not None else dc.Emax
3908 self.capitals = capitals if capitals is not None else dc.capitals
3909 self.clamp = clamp if clamp is not None else dc.clamp
3910
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003911 if _ignored_flags is None:
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003912 self._ignored_flags = []
3913 else:
3914 self._ignored_flags = _ignored_flags
3915
3916 if traps is None:
3917 self.traps = dc.traps.copy()
3918 elif not isinstance(traps, dict):
Stefan Krah1919b7e2012-03-21 18:25:23 +01003919 self.traps = dict((s, int(s in traps)) for s in _signals + traps)
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003920 else:
3921 self.traps = traps
3922
3923 if flags is None:
3924 self.flags = dict.fromkeys(_signals, 0)
3925 elif not isinstance(flags, dict):
Stefan Krah1919b7e2012-03-21 18:25:23 +01003926 self.flags = dict((s, int(s in flags)) for s in _signals + flags)
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003927 else:
3928 self.flags = flags
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003929
Stefan Krah1919b7e2012-03-21 18:25:23 +01003930 def _set_integer_check(self, name, value, vmin, vmax):
3931 if not isinstance(value, int):
3932 raise TypeError("%s must be an integer" % name)
3933 if vmin == '-inf':
3934 if value > vmax:
3935 raise ValueError("%s must be in [%s, %d]. got: %s" % (name, vmin, vmax, value))
3936 elif vmax == 'inf':
3937 if value < vmin:
3938 raise ValueError("%s must be in [%d, %s]. got: %s" % (name, vmin, vmax, value))
3939 else:
3940 if value < vmin or value > vmax:
3941 raise ValueError("%s must be in [%d, %d]. got %s" % (name, vmin, vmax, value))
3942 return object.__setattr__(self, name, value)
3943
3944 def _set_signal_dict(self, name, d):
3945 if not isinstance(d, dict):
3946 raise TypeError("%s must be a signal dict" % d)
3947 for key in d:
3948 if not key in _signals:
3949 raise KeyError("%s is not a valid signal dict" % d)
3950 for key in _signals:
3951 if not key in d:
3952 raise KeyError("%s is not a valid signal dict" % d)
3953 return object.__setattr__(self, name, d)
3954
3955 def __setattr__(self, name, value):
3956 if name == 'prec':
3957 return self._set_integer_check(name, value, 1, 'inf')
3958 elif name == 'Emin':
3959 return self._set_integer_check(name, value, '-inf', 0)
3960 elif name == 'Emax':
3961 return self._set_integer_check(name, value, 0, 'inf')
3962 elif name == 'capitals':
3963 return self._set_integer_check(name, value, 0, 1)
3964 elif name == 'clamp':
3965 return self._set_integer_check(name, value, 0, 1)
3966 elif name == 'rounding':
3967 if not value in _rounding_modes:
3968 # raise TypeError even for strings to have consistency
3969 # among various implementations.
3970 raise TypeError("%s: invalid rounding mode" % value)
3971 return object.__setattr__(self, name, value)
3972 elif name == 'flags' or name == 'traps':
3973 return self._set_signal_dict(name, value)
3974 elif name == '_ignored_flags':
3975 return object.__setattr__(self, name, value)
3976 else:
3977 raise AttributeError(
3978 "'decimal.Context' object has no attribute '%s'" % name)
3979
3980 def __delattr__(self, name):
3981 raise AttributeError("%s cannot be deleted" % name)
3982
3983 # Support for pickling, copy, and deepcopy
3984 def __reduce__(self):
3985 flags = [sig for sig, v in self.flags.items() if v]
3986 traps = [sig for sig, v in self.traps.items() if v]
3987 return (self.__class__,
3988 (self.prec, self.rounding, self.Emin, self.Emax,
3989 self.capitals, self.clamp, flags, traps))
3990
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003991 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003992 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003993 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003994 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00003995 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, '
3996 'clamp=%(clamp)d'
Guido van Rossumd8faa362007-04-27 19:54:29 +00003997 % vars(self))
3998 names = [f.__name__ for f, v in self.flags.items() if v]
3999 s.append('flags=[' + ', '.join(names) + ']')
4000 names = [t.__name__ for t, v in self.traps.items() if v]
4001 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00004002 return ', '.join(s) + ')'
4003
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00004004 def clear_flags(self):
4005 """Reset all flags to zero"""
4006 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00004007 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00004008
Stefan Krah1919b7e2012-03-21 18:25:23 +01004009 def clear_traps(self):
4010 """Reset all traps to zero"""
4011 for flag in self.traps:
4012 self.traps[flag] = 0
4013
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004014 def _shallow_copy(self):
4015 """Returns a shallow copy from self."""
Stefan Krah1919b7e2012-03-21 18:25:23 +01004016 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
4017 self.capitals, self.clamp, self.flags, self.traps,
4018 self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004019 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004020
4021 def copy(self):
4022 """Returns a deep copy from self."""
Stefan Krah1919b7e2012-03-21 18:25:23 +01004023 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
4024 self.capitals, self.clamp,
4025 self.flags.copy(), self.traps.copy(),
4026 self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004027 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004028 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004029
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004030 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004031 """Handles an error
4032
4033 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00004034 Otherwise, it sets the flag, then, if the corresponding
Stefan Krah2eb4a072010-05-19 15:52:31 +00004035 trap_enabler is set, it reraises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00004036 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004037 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004038 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004039 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00004040 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004041 return error().handle(self, *args)
4042
Raymond Hettinger86173da2008-02-01 20:38:12 +00004043 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00004044 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00004045 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004046 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004047
4048 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00004049 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00004050 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004051
4052 def _ignore_all_flags(self):
4053 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00004054 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004055
4056 def _ignore_flags(self, *flags):
4057 """Ignore the flags, if they are raised"""
4058 # Do not mutate-- This way, copies of a context leave the original
4059 # alone.
4060 self._ignored_flags = (self._ignored_flags + list(flags))
4061 return list(flags)
4062
4063 def _regard_flags(self, *flags):
4064 """Stop ignoring the flags, if they are raised"""
4065 if flags and isinstance(flags[0], (tuple,list)):
4066 flags = flags[0]
4067 for flag in flags:
4068 self._ignored_flags.remove(flag)
4069
Nick Coghland1abd252008-07-15 15:46:38 +00004070 # We inherit object.__hash__, so we must deny this explicitly
4071 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004072
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004073 def Etiny(self):
4074 """Returns Etiny (= Emin - prec + 1)"""
4075 return int(self.Emin - self.prec + 1)
4076
4077 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004078 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004079 return int(self.Emax - self.prec + 1)
4080
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004081 def _set_rounding(self, type):
4082 """Sets the rounding type.
4083
4084 Sets the rounding type, and returns the current (previous)
4085 rounding type. Often used like:
4086
4087 context = context.copy()
4088 # so you don't change the calling context
4089 # if an error occurs in the middle.
4090 rounding = context._set_rounding(ROUND_UP)
4091 val = self.__sub__(other, context=context)
4092 context._set_rounding(rounding)
4093
4094 This will make it round up for that operation.
4095 """
4096 rounding = self.rounding
4097 self.rounding= type
4098 return rounding
4099
Raymond Hettingerfed52962004-07-14 15:41:57 +00004100 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00004101 """Creates a new Decimal instance but using self as context.
4102
4103 This method implements the to-number operation of the
4104 IBM Decimal specification."""
4105
4106 if isinstance(num, str) and num != num.strip():
4107 return self._raise_error(ConversionSyntax,
4108 "no trailing or leading whitespace is "
4109 "permitted.")
4110
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004111 d = Decimal(num, context=self)
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00004112 if d._isnan() and len(d._int) > self.prec - self.clamp:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004113 return self._raise_error(ConversionSyntax,
4114 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00004115 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004116
Raymond Hettinger771ed762009-01-03 19:20:32 +00004117 def create_decimal_from_float(self, f):
4118 """Creates a new Decimal instance from a float but rounding using self
4119 as the context.
4120
4121 >>> context = Context(prec=5, rounding=ROUND_DOWN)
4122 >>> context.create_decimal_from_float(3.1415926535897932)
4123 Decimal('3.1415')
4124 >>> context = Context(prec=5, traps=[Inexact])
4125 >>> context.create_decimal_from_float(3.1415926535897932)
4126 Traceback (most recent call last):
4127 ...
4128 decimal.Inexact: None
4129
4130 """
4131 d = Decimal.from_float(f) # An exact conversion
4132 return d._fix(self) # Apply the context rounding
4133
Guido van Rossumd8faa362007-04-27 19:54:29 +00004134 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004135 def abs(self, a):
4136 """Returns the absolute value of the operand.
4137
4138 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00004139 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004140 the plus operation on the operand.
4141
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004142 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004143 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004144 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004145 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004146 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004147 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004148 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004149 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00004150 >>> ExtendedContext.abs(-1)
4151 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004152 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004153 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004154 return a.__abs__(context=self)
4155
4156 def add(self, a, b):
4157 """Return the sum of the two operands.
4158
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004159 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004160 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004161 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004162 Decimal('1.02E+4')
Mark Dickinson84230a12010-02-18 14:49:50 +00004163 >>> ExtendedContext.add(1, Decimal(2))
4164 Decimal('3')
4165 >>> ExtendedContext.add(Decimal(8), 5)
4166 Decimal('13')
4167 >>> ExtendedContext.add(5, 5)
4168 Decimal('10')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004169 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004170 a = _convert_other(a, raiseit=True)
4171 r = a.__add__(b, context=self)
4172 if r is NotImplemented:
4173 raise TypeError("Unable to convert %s to Decimal" % b)
4174 else:
4175 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004176
4177 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00004178 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004179
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004180 def canonical(self, a):
4181 """Returns the same Decimal object.
4182
4183 As we do not have different encodings for the same number, the
4184 received object already is in its canonical form.
4185
4186 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004187 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004188 """
Stefan Krah1919b7e2012-03-21 18:25:23 +01004189 if not isinstance(a, Decimal):
4190 raise TypeError("canonical requires a Decimal as an argument.")
Stefan Krah040e3112012-12-15 22:33:33 +01004191 return a.canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004192
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004193 def compare(self, a, b):
4194 """Compares values numerically.
4195
4196 If the signs of the operands differ, a value representing each operand
4197 ('-1' if the operand is less than zero, '0' if the operand is zero or
4198 negative zero, or '1' if the operand is greater than zero) is used in
4199 place of that operand for the comparison instead of the actual
4200 operand.
4201
4202 The comparison is then effected by subtracting the second operand from
4203 the first and then returning a value according to the result of the
4204 subtraction: '-1' if the result is less than zero, '0' if the result is
4205 zero or negative zero, or '1' if the result is greater than zero.
4206
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004207 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004208 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004209 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004210 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004211 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004212 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004213 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004214 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004215 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004216 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004217 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004218 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004219 >>> ExtendedContext.compare(1, 2)
4220 Decimal('-1')
4221 >>> ExtendedContext.compare(Decimal(1), 2)
4222 Decimal('-1')
4223 >>> ExtendedContext.compare(1, Decimal(2))
4224 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004225 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004226 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004227 return a.compare(b, context=self)
4228
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004229 def compare_signal(self, a, b):
4230 """Compares the values of the two operands numerically.
4231
4232 It's pretty much like compare(), but all NaNs signal, with signaling
4233 NaNs taking precedence over quiet NaNs.
4234
4235 >>> c = ExtendedContext
4236 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004237 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004238 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004239 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004240 >>> c.flags[InvalidOperation] = 0
4241 >>> print(c.flags[InvalidOperation])
4242 0
4243 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004244 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004245 >>> print(c.flags[InvalidOperation])
4246 1
4247 >>> c.flags[InvalidOperation] = 0
4248 >>> print(c.flags[InvalidOperation])
4249 0
4250 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004251 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004252 >>> print(c.flags[InvalidOperation])
4253 1
Mark Dickinson84230a12010-02-18 14:49:50 +00004254 >>> c.compare_signal(-1, 2)
4255 Decimal('-1')
4256 >>> c.compare_signal(Decimal(-1), 2)
4257 Decimal('-1')
4258 >>> c.compare_signal(-1, Decimal(2))
4259 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004260 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004261 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004262 return a.compare_signal(b, context=self)
4263
4264 def compare_total(self, a, b):
4265 """Compares two operands using their abstract representation.
4266
4267 This is not like the standard compare, which use their numerical
4268 value. Note that a total ordering is defined for all possible abstract
4269 representations.
4270
4271 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004272 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004273 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004274 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004275 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004276 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004277 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004278 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004279 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004280 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004281 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004282 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004283 >>> ExtendedContext.compare_total(1, 2)
4284 Decimal('-1')
4285 >>> ExtendedContext.compare_total(Decimal(1), 2)
4286 Decimal('-1')
4287 >>> ExtendedContext.compare_total(1, Decimal(2))
4288 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004289 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004290 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004291 return a.compare_total(b)
4292
4293 def compare_total_mag(self, a, b):
4294 """Compares two operands using their abstract representation ignoring sign.
4295
4296 Like compare_total, but with operand's sign ignored and assumed to be 0.
4297 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004298 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004299 return a.compare_total_mag(b)
4300
4301 def copy_abs(self, a):
4302 """Returns a copy of the operand with the sign set to 0.
4303
4304 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004305 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004306 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004307 Decimal('100')
Mark Dickinson84230a12010-02-18 14:49:50 +00004308 >>> ExtendedContext.copy_abs(-1)
4309 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004310 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004311 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004312 return a.copy_abs()
4313
4314 def copy_decimal(self, a):
Mark Dickinson84230a12010-02-18 14:49:50 +00004315 """Returns a copy of the decimal object.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004316
4317 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004318 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004319 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004320 Decimal('-1.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00004321 >>> ExtendedContext.copy_decimal(1)
4322 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004323 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004324 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004325 return Decimal(a)
4326
4327 def copy_negate(self, a):
4328 """Returns a copy of the operand with the sign inverted.
4329
4330 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004331 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004332 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004333 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00004334 >>> ExtendedContext.copy_negate(1)
4335 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004336 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004337 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004338 return a.copy_negate()
4339
4340 def copy_sign(self, a, b):
4341 """Copies the second operand's sign to the first one.
4342
4343 In detail, it returns a copy of the first operand with the sign
4344 equal to the sign of the second operand.
4345
4346 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004347 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004348 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004349 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004350 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004351 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004352 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004353 Decimal('-1.50')
Mark Dickinson84230a12010-02-18 14:49:50 +00004354 >>> ExtendedContext.copy_sign(1, -2)
4355 Decimal('-1')
4356 >>> ExtendedContext.copy_sign(Decimal(1), -2)
4357 Decimal('-1')
4358 >>> ExtendedContext.copy_sign(1, Decimal(-2))
4359 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004360 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004361 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004362 return a.copy_sign(b)
4363
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004364 def divide(self, a, b):
4365 """Decimal division in a specified context.
4366
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004367 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004368 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004369 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004370 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004371 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004372 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004373 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004374 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004375 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004376 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004377 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004378 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004379 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004380 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004381 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004382 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004383 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004384 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004385 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004386 Decimal('1.20E+6')
Mark Dickinson84230a12010-02-18 14:49:50 +00004387 >>> ExtendedContext.divide(5, 5)
4388 Decimal('1')
4389 >>> ExtendedContext.divide(Decimal(5), 5)
4390 Decimal('1')
4391 >>> ExtendedContext.divide(5, Decimal(5))
4392 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004393 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004394 a = _convert_other(a, raiseit=True)
4395 r = a.__truediv__(b, context=self)
4396 if r is NotImplemented:
4397 raise TypeError("Unable to convert %s to Decimal" % b)
4398 else:
4399 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004400
4401 def divide_int(self, a, b):
4402 """Divides two numbers and returns the integer part of the result.
4403
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004404 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004405 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004406 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004407 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004408 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004409 Decimal('3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004410 >>> ExtendedContext.divide_int(10, 3)
4411 Decimal('3')
4412 >>> ExtendedContext.divide_int(Decimal(10), 3)
4413 Decimal('3')
4414 >>> ExtendedContext.divide_int(10, Decimal(3))
4415 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004416 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004417 a = _convert_other(a, raiseit=True)
4418 r = a.__floordiv__(b, context=self)
4419 if r is NotImplemented:
4420 raise TypeError("Unable to convert %s to Decimal" % b)
4421 else:
4422 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004423
4424 def divmod(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004425 """Return (a // b, a % b).
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004426
4427 >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
4428 (Decimal('2'), Decimal('2'))
4429 >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
4430 (Decimal('2'), Decimal('0'))
Mark Dickinson84230a12010-02-18 14:49:50 +00004431 >>> ExtendedContext.divmod(8, 4)
4432 (Decimal('2'), Decimal('0'))
4433 >>> ExtendedContext.divmod(Decimal(8), 4)
4434 (Decimal('2'), Decimal('0'))
4435 >>> ExtendedContext.divmod(8, Decimal(4))
4436 (Decimal('2'), Decimal('0'))
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004437 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004438 a = _convert_other(a, raiseit=True)
4439 r = a.__divmod__(b, context=self)
4440 if r is NotImplemented:
4441 raise TypeError("Unable to convert %s to Decimal" % b)
4442 else:
4443 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004444
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004445 def exp(self, a):
4446 """Returns e ** a.
4447
4448 >>> c = ExtendedContext.copy()
4449 >>> c.Emin = -999
4450 >>> c.Emax = 999
4451 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004452 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004453 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004454 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004455 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004456 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004457 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004458 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004459 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004460 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004461 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004462 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004463 >>> c.exp(10)
4464 Decimal('22026.4658')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004465 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004466 a =_convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004467 return a.exp(context=self)
4468
4469 def fma(self, a, b, c):
4470 """Returns a multiplied by b, plus c.
4471
4472 The first two operands are multiplied together, using multiply,
4473 the third operand is then added to the result of that
4474 multiplication, using add, all with only one final rounding.
4475
4476 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004477 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004478 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004479 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004480 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004481 Decimal('1.38435736E+12')
Mark Dickinson84230a12010-02-18 14:49:50 +00004482 >>> ExtendedContext.fma(1, 3, 4)
4483 Decimal('7')
4484 >>> ExtendedContext.fma(1, Decimal(3), 4)
4485 Decimal('7')
4486 >>> ExtendedContext.fma(1, 3, Decimal(4))
4487 Decimal('7')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004488 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004489 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004490 return a.fma(b, c, context=self)
4491
4492 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004493 """Return True if the operand is canonical; otherwise return False.
4494
4495 Currently, the encoding of a Decimal instance is always
4496 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004497
4498 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004499 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004500 """
Stefan Krah1919b7e2012-03-21 18:25:23 +01004501 if not isinstance(a, Decimal):
4502 raise TypeError("is_canonical requires a Decimal as an argument.")
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004503 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004504
4505 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004506 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004507
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004508 A Decimal instance is considered finite if it is neither
4509 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004510
4511 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004512 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004513 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004514 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004515 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004516 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004517 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004518 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004519 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004520 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004521 >>> ExtendedContext.is_finite(1)
4522 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004523 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004524 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004525 return a.is_finite()
4526
4527 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004528 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004529
4530 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004531 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004532 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004533 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004534 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004535 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004536 >>> ExtendedContext.is_infinite(1)
4537 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004538 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004539 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004540 return a.is_infinite()
4541
4542 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004543 """Return True if the operand is a qNaN or sNaN;
4544 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004545
4546 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004547 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004548 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004549 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004550 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004551 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004552 >>> ExtendedContext.is_nan(1)
4553 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004554 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004555 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004556 return a.is_nan()
4557
4558 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004559 """Return True if the operand is a normal number;
4560 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004561
4562 >>> c = ExtendedContext.copy()
4563 >>> c.Emin = -999
4564 >>> c.Emax = 999
4565 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004566 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004567 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004568 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004569 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004570 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004571 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004572 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004573 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004574 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004575 >>> c.is_normal(1)
4576 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004577 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004578 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004579 return a.is_normal(context=self)
4580
4581 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004582 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004583
4584 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004585 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004586 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004587 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004588 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004589 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004590 >>> ExtendedContext.is_qnan(1)
4591 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004592 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004593 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004594 return a.is_qnan()
4595
4596 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004597 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004598
4599 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004600 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004601 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004602 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004603 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004604 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004605 >>> ExtendedContext.is_signed(8)
4606 False
4607 >>> ExtendedContext.is_signed(-8)
4608 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004609 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004610 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004611 return a.is_signed()
4612
4613 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004614 """Return True if the operand is a signaling NaN;
4615 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004616
4617 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004618 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004619 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004620 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004621 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004622 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004623 >>> ExtendedContext.is_snan(1)
4624 False
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.is_snan()
4628
4629 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004630 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004631
4632 >>> c = ExtendedContext.copy()
4633 >>> c.Emin = -999
4634 >>> c.Emax = 999
4635 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004636 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004637 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004638 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004639 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004640 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004641 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004642 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004643 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004644 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004645 >>> c.is_subnormal(1)
4646 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004647 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004648 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004649 return a.is_subnormal(context=self)
4650
4651 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004652 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004653
4654 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004655 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004656 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004657 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004658 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004659 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004660 >>> ExtendedContext.is_zero(1)
4661 False
4662 >>> ExtendedContext.is_zero(0)
4663 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004664 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004665 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004666 return a.is_zero()
4667
4668 def ln(self, a):
4669 """Returns the natural (base e) logarithm of the operand.
4670
4671 >>> c = ExtendedContext.copy()
4672 >>> c.Emin = -999
4673 >>> c.Emax = 999
4674 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004675 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004676 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004677 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004678 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004679 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004680 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004681 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004682 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004683 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004684 >>> c.ln(1)
4685 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004686 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004687 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004688 return a.ln(context=self)
4689
4690 def log10(self, a):
4691 """Returns the base 10 logarithm of the operand.
4692
4693 >>> c = ExtendedContext.copy()
4694 >>> c.Emin = -999
4695 >>> c.Emax = 999
4696 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004697 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004698 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004699 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004700 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004701 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004702 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004703 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004704 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004705 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004706 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004707 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004708 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004709 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004710 >>> c.log10(0)
4711 Decimal('-Infinity')
4712 >>> c.log10(1)
4713 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004714 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004715 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004716 return a.log10(context=self)
4717
4718 def logb(self, a):
4719 """ Returns the exponent of the magnitude of the operand's MSD.
4720
4721 The result is the integer which is the exponent of the magnitude
4722 of the most significant digit of the operand (as though the
4723 operand were truncated to a single digit while maintaining the
4724 value of that digit and without limiting the resulting exponent).
4725
4726 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004727 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004728 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004729 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004730 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004731 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004732 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004733 Decimal('-Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004734 >>> ExtendedContext.logb(1)
4735 Decimal('0')
4736 >>> ExtendedContext.logb(10)
4737 Decimal('1')
4738 >>> ExtendedContext.logb(100)
4739 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004740 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004741 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004742 return a.logb(context=self)
4743
4744 def logical_and(self, a, b):
4745 """Applies the logical operation 'and' between each operand's digits.
4746
4747 The operands must be both logical numbers.
4748
4749 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004750 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004751 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004752 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004753 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004754 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004755 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004756 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004757 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004758 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004759 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004760 Decimal('10')
Mark Dickinson84230a12010-02-18 14:49:50 +00004761 >>> ExtendedContext.logical_and(110, 1101)
4762 Decimal('100')
4763 >>> ExtendedContext.logical_and(Decimal(110), 1101)
4764 Decimal('100')
4765 >>> ExtendedContext.logical_and(110, Decimal(1101))
4766 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004767 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004768 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004769 return a.logical_and(b, context=self)
4770
4771 def logical_invert(self, a):
4772 """Invert all the digits in the operand.
4773
4774 The operand must be a logical number.
4775
4776 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004777 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004778 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004779 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004780 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004781 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004782 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004783 Decimal('10101010')
Mark Dickinson84230a12010-02-18 14:49:50 +00004784 >>> ExtendedContext.logical_invert(1101)
4785 Decimal('111110010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004786 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004787 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004788 return a.logical_invert(context=self)
4789
4790 def logical_or(self, a, b):
4791 """Applies the logical operation 'or' between each operand's digits.
4792
4793 The operands must be both logical numbers.
4794
4795 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004796 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004797 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004798 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004799 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004800 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004801 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004802 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004803 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004804 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004805 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004806 Decimal('1110')
Mark Dickinson84230a12010-02-18 14:49:50 +00004807 >>> ExtendedContext.logical_or(110, 1101)
4808 Decimal('1111')
4809 >>> ExtendedContext.logical_or(Decimal(110), 1101)
4810 Decimal('1111')
4811 >>> ExtendedContext.logical_or(110, Decimal(1101))
4812 Decimal('1111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004813 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004814 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004815 return a.logical_or(b, context=self)
4816
4817 def logical_xor(self, a, b):
4818 """Applies the logical operation 'xor' between each operand's digits.
4819
4820 The operands must be both logical numbers.
4821
4822 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004823 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004824 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004825 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004826 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004827 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004828 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004829 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004830 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004831 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004832 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004833 Decimal('1101')
Mark Dickinson84230a12010-02-18 14:49:50 +00004834 >>> ExtendedContext.logical_xor(110, 1101)
4835 Decimal('1011')
4836 >>> ExtendedContext.logical_xor(Decimal(110), 1101)
4837 Decimal('1011')
4838 >>> ExtendedContext.logical_xor(110, Decimal(1101))
4839 Decimal('1011')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004840 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004841 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004842 return a.logical_xor(b, context=self)
4843
Mark Dickinson84230a12010-02-18 14:49:50 +00004844 def max(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004845 """max compares two values numerically and returns the maximum.
4846
4847 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004848 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004849 operation. If they are numerically equal then the left-hand operand
4850 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004851 infinity) of the two operands is chosen as the result.
4852
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004853 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004854 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004855 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004856 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004857 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004858 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004859 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004860 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004861 >>> ExtendedContext.max(1, 2)
4862 Decimal('2')
4863 >>> ExtendedContext.max(Decimal(1), 2)
4864 Decimal('2')
4865 >>> ExtendedContext.max(1, Decimal(2))
4866 Decimal('2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004867 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004868 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004869 return a.max(b, context=self)
4870
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004871 def max_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004872 """Compares the values numerically with their sign ignored.
4873
4874 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
4875 Decimal('7')
4876 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
4877 Decimal('-10')
4878 >>> ExtendedContext.max_mag(1, -2)
4879 Decimal('-2')
4880 >>> ExtendedContext.max_mag(Decimal(1), -2)
4881 Decimal('-2')
4882 >>> ExtendedContext.max_mag(1, Decimal(-2))
4883 Decimal('-2')
4884 """
4885 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004886 return a.max_mag(b, context=self)
4887
Mark Dickinson84230a12010-02-18 14:49:50 +00004888 def min(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004889 """min compares two values numerically and returns the minimum.
4890
4891 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004892 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004893 operation. If they are numerically equal then the left-hand operand
4894 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004895 infinity) of the two operands is chosen as the result.
4896
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004897 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004898 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004899 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004900 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004901 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004902 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004903 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004904 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004905 >>> ExtendedContext.min(1, 2)
4906 Decimal('1')
4907 >>> ExtendedContext.min(Decimal(1), 2)
4908 Decimal('1')
4909 >>> ExtendedContext.min(1, Decimal(29))
4910 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004911 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004912 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004913 return a.min(b, context=self)
4914
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004915 def min_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004916 """Compares the values numerically with their sign ignored.
4917
4918 >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
4919 Decimal('-2')
4920 >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
4921 Decimal('-3')
4922 >>> ExtendedContext.min_mag(1, -2)
4923 Decimal('1')
4924 >>> ExtendedContext.min_mag(Decimal(1), -2)
4925 Decimal('1')
4926 >>> ExtendedContext.min_mag(1, Decimal(-2))
4927 Decimal('1')
4928 """
4929 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004930 return a.min_mag(b, context=self)
4931
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004932 def minus(self, a):
4933 """Minus corresponds to unary prefix minus in Python.
4934
4935 The operation is evaluated using the same rules as subtract; the
4936 operation minus(a) is calculated as subtract('0', a) where the '0'
4937 has the same exponent as the operand.
4938
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004939 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004940 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004941 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004942 Decimal('1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004943 >>> ExtendedContext.minus(1)
4944 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004945 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004946 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004947 return a.__neg__(context=self)
4948
4949 def multiply(self, a, b):
4950 """multiply multiplies two operands.
4951
4952 If either operand is a special value then the general rules apply.
Mark Dickinson84230a12010-02-18 14:49:50 +00004953 Otherwise, the operands are multiplied together
4954 ('long multiplication'), resulting in a number which may be as long as
4955 the sum of the lengths of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004956
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004957 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004958 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004959 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004960 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004961 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004962 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004963 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004964 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004965 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004966 Decimal('4.28135971E+11')
Mark Dickinson84230a12010-02-18 14:49:50 +00004967 >>> ExtendedContext.multiply(7, 7)
4968 Decimal('49')
4969 >>> ExtendedContext.multiply(Decimal(7), 7)
4970 Decimal('49')
4971 >>> ExtendedContext.multiply(7, Decimal(7))
4972 Decimal('49')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004973 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004974 a = _convert_other(a, raiseit=True)
4975 r = a.__mul__(b, context=self)
4976 if r is NotImplemented:
4977 raise TypeError("Unable to convert %s to Decimal" % b)
4978 else:
4979 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004980
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004981 def next_minus(self, a):
4982 """Returns the largest representable number smaller than a.
4983
4984 >>> c = ExtendedContext.copy()
4985 >>> c.Emin = -999
4986 >>> c.Emax = 999
4987 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004988 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004989 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004990 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004991 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004992 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004993 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004994 Decimal('9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00004995 >>> c.next_minus(1)
4996 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004997 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004998 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004999 return a.next_minus(context=self)
5000
5001 def next_plus(self, a):
5002 """Returns the smallest representable number larger than a.
5003
5004 >>> c = ExtendedContext.copy()
5005 >>> c.Emin = -999
5006 >>> c.Emax = 999
5007 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005008 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005009 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005010 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005011 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005012 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005013 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005014 Decimal('-9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00005015 >>> c.next_plus(1)
5016 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005017 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005018 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005019 return a.next_plus(context=self)
5020
5021 def next_toward(self, a, b):
5022 """Returns the number closest to a, in direction towards b.
5023
5024 The result is the closest representable number from the first
5025 operand (but not the first operand) that is in the direction
5026 towards the second operand, unless the operands have the same
5027 value.
5028
5029 >>> c = ExtendedContext.copy()
5030 >>> c.Emin = -999
5031 >>> c.Emax = 999
5032 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005033 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005034 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005035 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005036 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005037 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005038 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005039 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005040 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005041 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005042 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005043 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005044 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005045 Decimal('-0.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00005046 >>> c.next_toward(0, 1)
5047 Decimal('1E-1007')
5048 >>> c.next_toward(Decimal(0), 1)
5049 Decimal('1E-1007')
5050 >>> c.next_toward(0, Decimal(1))
5051 Decimal('1E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005052 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005053 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005054 return a.next_toward(b, context=self)
5055
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005056 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00005057 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005058
5059 Essentially a plus operation with all trailing zeros removed from the
5060 result.
5061
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005062 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005063 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005064 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005065 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005066 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005067 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005068 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005069 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005070 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005071 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005072 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005073 Decimal('0')
Mark Dickinson84230a12010-02-18 14:49:50 +00005074 >>> ExtendedContext.normalize(6)
5075 Decimal('6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005076 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005077 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005078 return a.normalize(context=self)
5079
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005080 def number_class(self, a):
5081 """Returns an indication of the class of the operand.
5082
5083 The class is one of the following strings:
5084 -sNaN
5085 -NaN
5086 -Infinity
5087 -Normal
5088 -Subnormal
5089 -Zero
5090 +Zero
5091 +Subnormal
5092 +Normal
5093 +Infinity
5094
Stefan Krah1919b7e2012-03-21 18:25:23 +01005095 >>> c = ExtendedContext.copy()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005096 >>> c.Emin = -999
5097 >>> c.Emax = 999
5098 >>> c.number_class(Decimal('Infinity'))
5099 '+Infinity'
5100 >>> c.number_class(Decimal('1E-10'))
5101 '+Normal'
5102 >>> c.number_class(Decimal('2.50'))
5103 '+Normal'
5104 >>> c.number_class(Decimal('0.1E-999'))
5105 '+Subnormal'
5106 >>> c.number_class(Decimal('0'))
5107 '+Zero'
5108 >>> c.number_class(Decimal('-0'))
5109 '-Zero'
5110 >>> c.number_class(Decimal('-0.1E-999'))
5111 '-Subnormal'
5112 >>> c.number_class(Decimal('-1E-10'))
5113 '-Normal'
5114 >>> c.number_class(Decimal('-2.50'))
5115 '-Normal'
5116 >>> c.number_class(Decimal('-Infinity'))
5117 '-Infinity'
5118 >>> c.number_class(Decimal('NaN'))
5119 'NaN'
5120 >>> c.number_class(Decimal('-NaN'))
5121 'NaN'
5122 >>> c.number_class(Decimal('sNaN'))
5123 'sNaN'
Mark Dickinson84230a12010-02-18 14:49:50 +00005124 >>> c.number_class(123)
5125 '+Normal'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005126 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005127 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005128 return a.number_class(context=self)
5129
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005130 def plus(self, a):
5131 """Plus corresponds to unary prefix plus in Python.
5132
5133 The operation is evaluated using the same rules as add; the
5134 operation plus(a) is calculated as add('0', a) where the '0'
5135 has the same exponent as the operand.
5136
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005137 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005138 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005139 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005140 Decimal('-1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005141 >>> ExtendedContext.plus(-1)
5142 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005143 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005144 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005145 return a.__pos__(context=self)
5146
5147 def power(self, a, b, modulo=None):
5148 """Raises a to the power of b, to modulo if given.
5149
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005150 With two arguments, compute a**b. If a is negative then b
5151 must be integral. The result will be inexact unless b is
5152 integral and the result is finite and can be expressed exactly
5153 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005154
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005155 With three arguments, compute (a**b) % modulo. For the
5156 three argument form, the following restrictions on the
5157 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005158
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005159 - all three arguments must be integral
5160 - b must be nonnegative
5161 - at least one of a or b must be nonzero
5162 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005163
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005164 The result of pow(a, b, modulo) is identical to the result
5165 that would be obtained by computing (a**b) % modulo with
5166 unbounded precision, but is computed more efficiently. It is
5167 always exact.
5168
5169 >>> c = ExtendedContext.copy()
5170 >>> c.Emin = -999
5171 >>> c.Emax = 999
5172 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005173 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005174 >>> c.power(Decimal('-2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005175 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005176 >>> c.power(Decimal('2'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005177 Decimal('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005178 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005179 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005180 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005181 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005182 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005183 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005184 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005185 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005186 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005187 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005188 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005189 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005190 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005191 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005192 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005193 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005194 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005195 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005196 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005197 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005198
5199 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005200 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005201 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005202 Decimal('-11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005203 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005204 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005205 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005206 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005207 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005208 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005209 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005210 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005211 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005212 Decimal('1')
Mark Dickinson84230a12010-02-18 14:49:50 +00005213 >>> ExtendedContext.power(7, 7)
5214 Decimal('823543')
5215 >>> ExtendedContext.power(Decimal(7), 7)
5216 Decimal('823543')
5217 >>> ExtendedContext.power(7, Decimal(7), 2)
5218 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005219 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005220 a = _convert_other(a, raiseit=True)
5221 r = a.__pow__(b, modulo, context=self)
5222 if r is NotImplemented:
5223 raise TypeError("Unable to convert %s to Decimal" % b)
5224 else:
5225 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005226
5227 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005228 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005229
5230 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00005231 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005232 exponent is being increased), multiplied by a positive power of ten (if
5233 the exponent is being decreased), or is unchanged (if the exponent is
5234 already equal to that of the right-hand operand).
5235
5236 Unlike other operations, if the length of the coefficient after the
5237 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00005238 operation condition is raised. This guarantees that, unless there is
5239 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005240 equal to that of the right-hand operand.
5241
5242 Also unlike other operations, quantize will never raise Underflow, even
5243 if the result is subnormal and inexact.
5244
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005245 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005246 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005247 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005248 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005249 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005250 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005251 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005252 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005253 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005254 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005255 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005256 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005257 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005258 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005259 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005260 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005261 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005262 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005263 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005264 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005265 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005266 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005267 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005268 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005269 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005270 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005271 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005272 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005273 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005274 Decimal('2E+2')
Mark Dickinson84230a12010-02-18 14:49:50 +00005275 >>> ExtendedContext.quantize(1, 2)
5276 Decimal('1')
5277 >>> ExtendedContext.quantize(Decimal(1), 2)
5278 Decimal('1')
5279 >>> ExtendedContext.quantize(1, Decimal(2))
5280 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005281 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005282 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005283 return a.quantize(b, context=self)
5284
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005285 def radix(self):
5286 """Just returns 10, as this is Decimal, :)
5287
5288 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005289 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005290 """
5291 return Decimal(10)
5292
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005293 def remainder(self, a, b):
5294 """Returns the remainder from integer division.
5295
5296 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00005297 calculating integer division as described for divide-integer, rounded
5298 to precision digits if necessary. The sign of the result, if
5299 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005300
5301 This operation will fail under the same conditions as integer division
5302 (that is, if integer division on the same two operands would fail, the
5303 remainder cannot be calculated).
5304
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005305 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005306 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005307 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005308 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005309 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005310 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005311 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005312 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005313 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005314 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005315 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005316 Decimal('1.0')
Mark Dickinson84230a12010-02-18 14:49:50 +00005317 >>> ExtendedContext.remainder(22, 6)
5318 Decimal('4')
5319 >>> ExtendedContext.remainder(Decimal(22), 6)
5320 Decimal('4')
5321 >>> ExtendedContext.remainder(22, Decimal(6))
5322 Decimal('4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005323 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005324 a = _convert_other(a, raiseit=True)
5325 r = a.__mod__(b, context=self)
5326 if r is NotImplemented:
5327 raise TypeError("Unable to convert %s to Decimal" % b)
5328 else:
5329 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005330
5331 def remainder_near(self, a, b):
5332 """Returns to be "a - b * n", where n is the integer nearest the exact
5333 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00005334 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005335 sign of a.
5336
5337 This operation will fail under the same conditions as integer division
5338 (that is, if integer division on the same two operands would fail, the
5339 remainder cannot be calculated).
5340
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005341 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005342 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005343 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005344 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005345 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005346 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005347 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005348 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005349 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005350 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005351 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005352 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005353 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005354 Decimal('-0.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005355 >>> ExtendedContext.remainder_near(3, 11)
5356 Decimal('3')
5357 >>> ExtendedContext.remainder_near(Decimal(3), 11)
5358 Decimal('3')
5359 >>> ExtendedContext.remainder_near(3, Decimal(11))
5360 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005361 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005362 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005363 return a.remainder_near(b, context=self)
5364
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005365 def rotate(self, a, b):
5366 """Returns a rotated copy of a, b times.
5367
5368 The coefficient of the result is a rotated copy of the digits in
5369 the coefficient of the first operand. The number of places of
5370 rotation is taken from the absolute value of the second operand,
5371 with the rotation being to the left if the second operand is
5372 positive or to the right otherwise.
5373
5374 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005375 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005376 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005377 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005378 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005379 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005380 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005381 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005382 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005383 Decimal('345678912')
Mark Dickinson84230a12010-02-18 14:49:50 +00005384 >>> ExtendedContext.rotate(1333333, 1)
5385 Decimal('13333330')
5386 >>> ExtendedContext.rotate(Decimal(1333333), 1)
5387 Decimal('13333330')
5388 >>> ExtendedContext.rotate(1333333, Decimal(1))
5389 Decimal('13333330')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005390 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005391 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005392 return a.rotate(b, context=self)
5393
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005394 def same_quantum(self, a, b):
5395 """Returns True if the two operands have the same exponent.
5396
5397 The result is never affected by either the sign or the coefficient of
5398 either operand.
5399
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005400 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005401 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005402 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005403 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005404 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005405 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005406 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005407 True
Mark Dickinson84230a12010-02-18 14:49:50 +00005408 >>> ExtendedContext.same_quantum(10000, -1)
5409 True
5410 >>> ExtendedContext.same_quantum(Decimal(10000), -1)
5411 True
5412 >>> ExtendedContext.same_quantum(10000, Decimal(-1))
5413 True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005414 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005415 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005416 return a.same_quantum(b)
5417
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005418 def scaleb (self, a, b):
5419 """Returns the first operand after adding the second value its exp.
5420
5421 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005422 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005423 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005424 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005425 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005426 Decimal('7.50E+3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005427 >>> ExtendedContext.scaleb(1, 4)
5428 Decimal('1E+4')
5429 >>> ExtendedContext.scaleb(Decimal(1), 4)
5430 Decimal('1E+4')
5431 >>> ExtendedContext.scaleb(1, Decimal(4))
5432 Decimal('1E+4')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005433 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005434 a = _convert_other(a, raiseit=True)
5435 return a.scaleb(b, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005436
5437 def shift(self, a, b):
5438 """Returns a shifted copy of a, b times.
5439
5440 The coefficient of the result is a shifted copy of the digits
5441 in the coefficient of the first operand. The number of places
5442 to shift is taken from the absolute value of the second operand,
5443 with the shift being to the left if the second operand is
5444 positive or to the right otherwise. Digits shifted into the
5445 coefficient are zeros.
5446
5447 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005448 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005449 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005450 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005451 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005452 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005453 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005454 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005455 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005456 Decimal('345678900')
Mark Dickinson84230a12010-02-18 14:49:50 +00005457 >>> ExtendedContext.shift(88888888, 2)
5458 Decimal('888888800')
5459 >>> ExtendedContext.shift(Decimal(88888888), 2)
5460 Decimal('888888800')
5461 >>> ExtendedContext.shift(88888888, Decimal(2))
5462 Decimal('888888800')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005463 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005464 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005465 return a.shift(b, context=self)
5466
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005467 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005468 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005469
5470 If the result must be inexact, it is rounded using the round-half-even
5471 algorithm.
5472
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005473 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005474 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005475 >>> ExtendedContext.sqrt(Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005476 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005477 >>> ExtendedContext.sqrt(Decimal('0.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005478 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005479 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005480 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005481 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005482 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005483 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005484 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005485 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005486 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005487 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005488 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005489 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005490 Decimal('3.16227766')
Mark Dickinson84230a12010-02-18 14:49:50 +00005491 >>> ExtendedContext.sqrt(2)
5492 Decimal('1.41421356')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005493 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005494 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005495 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005496 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005497 return a.sqrt(context=self)
5498
5499 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00005500 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005501
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005502 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005503 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005504 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005505 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005506 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005507 Decimal('-0.77')
Mark Dickinson84230a12010-02-18 14:49:50 +00005508 >>> ExtendedContext.subtract(8, 5)
5509 Decimal('3')
5510 >>> ExtendedContext.subtract(Decimal(8), 5)
5511 Decimal('3')
5512 >>> ExtendedContext.subtract(8, Decimal(5))
5513 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005514 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005515 a = _convert_other(a, raiseit=True)
5516 r = a.__sub__(b, context=self)
5517 if r is NotImplemented:
5518 raise TypeError("Unable to convert %s to Decimal" % b)
5519 else:
5520 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005521
5522 def to_eng_string(self, a):
5523 """Converts a number to a string, using scientific notation.
5524
5525 The operation is not affected by the context.
5526 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005527 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005528 return a.to_eng_string(context=self)
5529
5530 def to_sci_string(self, a):
5531 """Converts a number to a string, using scientific notation.
5532
5533 The operation is not affected by the context.
5534 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005535 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005536 return a.__str__(context=self)
5537
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005538 def to_integral_exact(self, a):
5539 """Rounds to an integer.
5540
5541 When the operand has a negative exponent, the result is the same
5542 as using the quantize() operation using the given operand as the
5543 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5544 of the operand as the precision setting; Inexact and Rounded flags
5545 are allowed in this operation. The rounding mode is taken from the
5546 context.
5547
5548 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005549 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005550 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005551 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005552 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005553 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005554 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005555 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005556 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005557 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005558 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005559 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005560 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005561 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005562 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005563 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005564 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005565 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005566 return a.to_integral_exact(context=self)
5567
5568 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005569 """Rounds to an integer.
5570
5571 When the operand has a negative exponent, the result is the same
5572 as using the quantize() operation using the given operand as the
5573 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5574 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00005575 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005576
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005577 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005578 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005579 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005580 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005581 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005582 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005583 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005584 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005585 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005586 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005587 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005588 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005589 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005590 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005591 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005592 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005593 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005594 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005595 return a.to_integral_value(context=self)
5596
5597 # the method name changed, but we provide also the old one, for compatibility
5598 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005599
5600class _WorkRep(object):
5601 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005602 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005603 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005604 # exp: None, int, or string
5605
5606 def __init__(self, value=None):
5607 if value is None:
5608 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005609 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005610 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005611 elif isinstance(value, Decimal):
5612 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005613 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005614 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005615 else:
5616 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005617 self.sign = value[0]
5618 self.int = value[1]
5619 self.exp = value[2]
5620
5621 def __repr__(self):
5622 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5623
5624 __str__ = __repr__
5625
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005626
5627
Christian Heimes2c181612007-12-17 20:04:13 +00005628def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005629 """Normalizes op1, op2 to have the same exp and length of coefficient.
5630
5631 Done during addition.
5632 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005633 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005634 tmp = op2
5635 other = op1
5636 else:
5637 tmp = op1
5638 other = op2
5639
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005640 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5641 # Then adding 10**exp to tmp has the same effect (after rounding)
5642 # as adding any positive quantity smaller than 10**exp; similarly
5643 # for subtraction. So if other is smaller than 10**exp we replace
5644 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00005645 tmp_len = len(str(tmp.int))
5646 other_len = len(str(other.int))
5647 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5648 if other_len + other.exp - 1 < exp:
5649 other.int = 1
5650 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005651
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005652 tmp.int *= 10 ** (tmp.exp - other.exp)
5653 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005654 return op1, op2
5655
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005656##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005657
Raymond Hettingerdb213a22010-11-27 08:09:40 +00005658_nbits = int.bit_length
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005659
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01005660def _decimal_lshift_exact(n, e):
5661 """ Given integers n and e, return n * 10**e if it's an integer, else None.
5662
5663 The computation is designed to avoid computing large powers of 10
5664 unnecessarily.
5665
5666 >>> _decimal_lshift_exact(3, 4)
5667 30000
5668 >>> _decimal_lshift_exact(300, -999999999) # returns None
5669
5670 """
5671 if n == 0:
5672 return 0
5673 elif e >= 0:
5674 return n * 10**e
5675 else:
5676 # val_n = largest power of 10 dividing n.
5677 str_n = str(abs(n))
5678 val_n = len(str_n) - len(str_n.rstrip('0'))
5679 return None if val_n < -e else n // 10**-e
5680
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005681def _sqrt_nearest(n, a):
5682 """Closest integer to the square root of the positive integer n. a is
5683 an initial approximation to the square root. Any positive integer
5684 will do for a, but the closer a is to the square root of n the
5685 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005686
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005687 """
5688 if n <= 0 or a <= 0:
5689 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5690
5691 b=0
5692 while a != b:
5693 b, a = a, a--n//a>>1
5694 return a
5695
5696def _rshift_nearest(x, shift):
5697 """Given an integer x and a nonnegative integer shift, return closest
5698 integer to x / 2**shift; use round-to-even in case of a tie.
5699
5700 """
5701 b, q = 1 << shift, x >> shift
5702 return q + (2*(x & (b-1)) + (q&1) > b)
5703
5704def _div_nearest(a, b):
5705 """Closest integer to a/b, a and b positive integers; rounds to even
5706 in the case of a tie.
5707
5708 """
5709 q, r = divmod(a, b)
5710 return q + (2*r + (q&1) > b)
5711
5712def _ilog(x, M, L = 8):
5713 """Integer approximation to M*log(x/M), with absolute error boundable
5714 in terms only of x/M.
5715
5716 Given positive integers x and M, return an integer approximation to
5717 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5718 between the approximation and the exact result is at most 22. For
5719 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5720 both cases these are upper bounds on the error; it will usually be
5721 much smaller."""
5722
5723 # The basic algorithm is the following: let log1p be the function
5724 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5725 # the reduction
5726 #
5727 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5728 #
5729 # repeatedly until the argument to log1p is small (< 2**-L in
5730 # absolute value). For small y we can use the Taylor series
5731 # expansion
5732 #
5733 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5734 #
5735 # truncating at T such that y**T is small enough. The whole
5736 # computation is carried out in a form of fixed-point arithmetic,
5737 # with a real number z being represented by an integer
5738 # approximation to z*M. To avoid loss of precision, the y below
5739 # is actually an integer approximation to 2**R*y*M, where R is the
5740 # number of reductions performed so far.
5741
5742 y = x-M
5743 # argument reduction; R = number of reductions performed
5744 R = 0
5745 while (R <= L and abs(y) << L-R >= M or
5746 R > L and abs(y) >> R-L >= M):
5747 y = _div_nearest((M*y) << 1,
5748 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5749 R += 1
5750
5751 # Taylor series with T terms
5752 T = -int(-10*len(str(M))//(3*L))
5753 yshift = _rshift_nearest(y, R)
5754 w = _div_nearest(M, T)
5755 for k in range(T-1, 0, -1):
5756 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5757
5758 return _div_nearest(w*y, M)
5759
5760def _dlog10(c, e, p):
5761 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5762 approximation to 10**p * log10(c*10**e), with an absolute error of
5763 at most 1. Assumes that c*10**e is not exactly 1."""
5764
5765 # increase precision by 2; compensate for this by dividing
5766 # final result by 100
5767 p += 2
5768
5769 # write c*10**e as d*10**f with either:
5770 # f >= 0 and 1 <= d <= 10, or
5771 # f <= 0 and 0.1 <= d <= 1.
5772 # Thus for c*10**e close to 1, f = 0
5773 l = len(str(c))
5774 f = e+l - (e+l >= 1)
5775
5776 if p > 0:
5777 M = 10**p
5778 k = e+p-f
5779 if k >= 0:
5780 c *= 10**k
5781 else:
5782 c = _div_nearest(c, 10**-k)
5783
5784 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005785 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005786 log_d = _div_nearest(log_d*M, log_10)
5787 log_tenpower = f*M # exact
5788 else:
5789 log_d = 0 # error < 2.31
Neal Norwitz2f99b242008-08-24 05:48:10 +00005790 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005791
5792 return _div_nearest(log_tenpower+log_d, 100)
5793
5794def _dlog(c, e, p):
5795 """Given integers c, e and p with c > 0, compute an integer
5796 approximation to 10**p * log(c*10**e), with an absolute error of
5797 at most 1. Assumes that c*10**e is not exactly 1."""
5798
5799 # Increase precision by 2. The precision increase is compensated
5800 # for at the end with a division by 100.
5801 p += 2
5802
5803 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5804 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5805 # as 10**p * log(d) + 10**p*f * log(10).
5806 l = len(str(c))
5807 f = e+l - (e+l >= 1)
5808
5809 # compute approximation to 10**p*log(d), with error < 27
5810 if p > 0:
5811 k = e+p-f
5812 if k >= 0:
5813 c *= 10**k
5814 else:
5815 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5816
5817 # _ilog magnifies existing error in c by a factor of at most 10
5818 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5819 else:
5820 # p <= 0: just approximate the whole thing by 0; error < 2.31
5821 log_d = 0
5822
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005823 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005824 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005825 extra = len(str(abs(f)))-1
5826 if p + extra >= 0:
5827 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5828 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5829 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005830 else:
5831 f_log_ten = 0
5832 else:
5833 f_log_ten = 0
5834
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005835 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005836 return _div_nearest(f_log_ten + log_d, 100)
5837
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005838class _Log10Memoize(object):
5839 """Class to compute, store, and allow retrieval of, digits of the
5840 constant log(10) = 2.302585.... This constant is needed by
5841 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5842 def __init__(self):
5843 self.digits = "23025850929940456840179914546843642076011014886"
5844
5845 def getdigits(self, p):
5846 """Given an integer p >= 0, return floor(10**p)*log(10).
5847
5848 For example, self.getdigits(3) returns 2302.
5849 """
5850 # digits are stored as a string, for quick conversion to
5851 # integer in the case that we've already computed enough
5852 # digits; the stored digits should always be correct
5853 # (truncated, not rounded to nearest).
5854 if p < 0:
5855 raise ValueError("p should be nonnegative")
5856
5857 if p >= len(self.digits):
5858 # compute p+3, p+6, p+9, ... digits; continue until at
5859 # least one of the extra digits is nonzero
5860 extra = 3
5861 while True:
5862 # compute p+extra digits, correct to within 1ulp
5863 M = 10**(p+extra+2)
5864 digits = str(_div_nearest(_ilog(10*M, M), 100))
5865 if digits[-extra:] != '0'*extra:
5866 break
5867 extra += 3
5868 # keep all reliable digits so far; remove trailing zeros
5869 # and next nonzero digit
5870 self.digits = digits.rstrip('0')[:-1]
5871 return int(self.digits[:p+1])
5872
5873_log10_digits = _Log10Memoize().getdigits
5874
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005875def _iexp(x, M, L=8):
5876 """Given integers x and M, M > 0, such that x/M is small in absolute
5877 value, compute an integer approximation to M*exp(x/M). For 0 <=
5878 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5879 is usually much smaller)."""
5880
5881 # Algorithm: to compute exp(z) for a real number z, first divide z
5882 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5883 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5884 # series
5885 #
5886 # expm1(x) = x + x**2/2! + x**3/3! + ...
5887 #
5888 # Now use the identity
5889 #
5890 # expm1(2x) = expm1(x)*(expm1(x)+2)
5891 #
5892 # R times to compute the sequence expm1(z/2**R),
5893 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5894
5895 # Find R such that x/2**R/M <= 2**-L
5896 R = _nbits((x<<L)//M)
5897
5898 # Taylor series. (2**L)**T > M
5899 T = -int(-10*len(str(M))//(3*L))
5900 y = _div_nearest(x, T)
5901 Mshift = M<<R
5902 for i in range(T-1, 0, -1):
5903 y = _div_nearest(x*(Mshift + y), Mshift * i)
5904
5905 # Expansion
5906 for k in range(R-1, -1, -1):
5907 Mshift = M<<(k+2)
5908 y = _div_nearest(y*(y+Mshift), Mshift)
5909
5910 return M+y
5911
5912def _dexp(c, e, p):
5913 """Compute an approximation to exp(c*10**e), with p decimal places of
5914 precision.
5915
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005916 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005917
5918 10**(p-1) <= d <= 10**p, and
5919 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5920
5921 In other words, d*10**f is an approximation to exp(c*10**e) with p
5922 digits of precision, and with an error in d of at most 1. This is
5923 almost, but not quite, the same as the error being < 1ulp: when d
5924 = 10**(p-1) the error could be up to 10 ulp."""
5925
5926 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5927 p += 2
5928
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005929 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005930 extra = max(0, e + len(str(c)) - 1)
5931 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005932
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005933 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005934 # rounding down
5935 shift = e+q
5936 if shift >= 0:
5937 cshift = c*10**shift
5938 else:
5939 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005940 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005941
5942 # reduce remainder back to original precision
5943 rem = _div_nearest(rem, 10**extra)
5944
5945 # error in result of _iexp < 120; error after division < 0.62
5946 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5947
5948def _dpower(xc, xe, yc, ye, p):
5949 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5950 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5951
5952 10**(p-1) <= c <= 10**p, and
5953 (c-1)*10**e < x**y < (c+1)*10**e
5954
5955 in other words, c*10**e is an approximation to x**y with p digits
5956 of precision, and with an error in c of at most 1. (This is
5957 almost, but not quite, the same as the error being < 1ulp: when c
5958 == 10**(p-1) we can only guarantee error < 10ulp.)
5959
5960 We assume that: x is positive and not equal to 1, and y is nonzero.
5961 """
5962
5963 # Find b such that 10**(b-1) <= |y| <= 10**b
5964 b = len(str(abs(yc))) + ye
5965
5966 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5967 lxc = _dlog(xc, xe, p+b+1)
5968
5969 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5970 shift = ye-b
5971 if shift >= 0:
5972 pc = lxc*yc*10**shift
5973 else:
5974 pc = _div_nearest(lxc*yc, 10**-shift)
5975
5976 if pc == 0:
5977 # we prefer a result that isn't exactly 1; this makes it
5978 # easier to compute a correctly rounded result in __pow__
5979 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5980 coeff, exp = 10**(p-1)+1, 1-p
5981 else:
5982 coeff, exp = 10**p-1, -p
5983 else:
5984 coeff, exp = _dexp(pc, -(p+1), p+1)
5985 coeff = _div_nearest(coeff, 10)
5986 exp += 1
5987
5988 return coeff, exp
5989
5990def _log10_lb(c, correction = {
5991 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5992 '6': 23, '7': 16, '8': 10, '9': 5}):
5993 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5994 if c <= 0:
5995 raise ValueError("The argument to _log10_lb should be nonnegative.")
5996 str_c = str(c)
5997 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005998
Guido van Rossumd8faa362007-04-27 19:54:29 +00005999##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006000
Mark Dickinsonac256ab2010-04-03 11:08:14 +00006001def _convert_other(other, raiseit=False, allow_float=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006002 """Convert other to Decimal.
6003
6004 Verifies that it's ok to use in an implicit construction.
Mark Dickinsonac256ab2010-04-03 11:08:14 +00006005 If allow_float is true, allow conversion from float; this
6006 is used in the comparison methods (__eq__ and friends).
6007
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006008 """
6009 if isinstance(other, Decimal):
6010 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00006011 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006012 return Decimal(other)
Mark Dickinsonac256ab2010-04-03 11:08:14 +00006013 if allow_float and isinstance(other, float):
6014 return Decimal.from_float(other)
6015
Thomas Wouters1b7f8912007-09-19 03:06:30 +00006016 if raiseit:
6017 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00006018 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006019
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006020def _convert_for_comparison(self, other, equality_op=False):
6021 """Given a Decimal instance self and a Python object other, return
Mark Dickinson1c164a62010-06-11 16:49:20 +00006022 a pair (s, o) of Decimal instances such that "s op o" is
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006023 equivalent to "self op other" for any of the 6 comparison
6024 operators "op".
6025
6026 """
6027 if isinstance(other, Decimal):
6028 return self, other
6029
6030 # Comparison with a Rational instance (also includes integers):
6031 # self op n/d <=> self*d op n (for n and d integers, d positive).
6032 # A NaN or infinity can be left unchanged without affecting the
6033 # comparison result.
6034 if isinstance(other, _numbers.Rational):
6035 if not self._is_special:
6036 self = _dec_from_triple(self._sign,
6037 str(int(self._int) * other.denominator),
6038 self._exp)
6039 return self, Decimal(other.numerator)
6040
6041 # Comparisons with float and complex types. == and != comparisons
6042 # with complex numbers should succeed, returning either True or False
6043 # as appropriate. Other comparisons return NotImplemented.
6044 if equality_op and isinstance(other, _numbers.Complex) and other.imag == 0:
6045 other = other.real
6046 if isinstance(other, float):
Stefan Krah1919b7e2012-03-21 18:25:23 +01006047 context = getcontext()
6048 if equality_op:
6049 context.flags[FloatOperation] = 1
6050 else:
6051 context._raise_error(FloatOperation,
6052 "strict semantics for mixing floats and Decimals are enabled")
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006053 return self, Decimal.from_float(other)
6054 return NotImplemented, NotImplemented
6055
6056
Guido van Rossumd8faa362007-04-27 19:54:29 +00006057##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006058
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006059# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00006060# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006061
6062DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00006063 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006064 traps=[DivisionByZero, Overflow, InvalidOperation],
6065 flags=[],
Stefan Krah1919b7e2012-03-21 18:25:23 +01006066 Emax=999999,
6067 Emin=-999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00006068 capitals=1,
6069 clamp=0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006070)
6071
6072# Pre-made alternate contexts offered by the specification
6073# Don't change these; the user should be able to select these
6074# contexts and be able to reproduce results from other implementations
6075# of the spec.
6076
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00006077BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006078 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006079 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
6080 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006081)
6082
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00006083ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00006084 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006085 traps=[],
6086 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006087)
6088
6089
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006090##### crud for parsing strings #############################################
Christian Heimes23daade02008-02-25 12:39:23 +00006091#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006092# Regular expression used for parsing numeric strings. Additional
6093# comments:
6094#
6095# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
6096# whitespace. But note that the specification disallows whitespace in
6097# a numeric string.
6098#
6099# 2. For finite numbers (not infinities and NaNs) the body of the
6100# number between the optional sign and the optional exponent must have
6101# at least one decimal digit, possibly after the decimal point. The
Mark Dickinson345adc42009-08-02 10:14:23 +00006102# lookahead expression '(?=\d|\.\d)' checks this.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006103
6104import re
Benjamin Peterson41181742008-07-02 20:22:54 +00006105_parser = re.compile(r""" # A numeric string consists of:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006106# \s*
Benjamin Peterson41181742008-07-02 20:22:54 +00006107 (?P<sign>[-+])? # an optional sign, followed by either...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006108 (
Mark Dickinson345adc42009-08-02 10:14:23 +00006109 (?=\d|\.\d) # ...a number (with at least one digit)
6110 (?P<int>\d*) # having a (possibly empty) integer part
6111 (\.(?P<frac>\d*))? # followed by an optional fractional part
6112 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006113 |
Benjamin Peterson41181742008-07-02 20:22:54 +00006114 Inf(inity)? # ...an infinity, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006115 |
Benjamin Peterson41181742008-07-02 20:22:54 +00006116 (?P<signal>s)? # ...an (optionally signaling)
6117 NaN # NaN
Mark Dickinson345adc42009-08-02 10:14:23 +00006118 (?P<diag>\d*) # with (possibly empty) diagnostic info.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006119 )
6120# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00006121 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006122""", re.VERBOSE | re.IGNORECASE).match
6123
Christian Heimescbf3b5c2007-12-03 21:02:03 +00006124_all_zeros = re.compile('0*$').match
6125_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00006126
6127##### PEP3101 support functions ##############################################
Mark Dickinson79f52032009-03-17 23:12:51 +00006128# The functions in this section have little to do with the Decimal
6129# class, and could potentially be reused or adapted for other pure
Christian Heimesf16baeb2008-02-29 14:57:44 +00006130# Python numeric classes that want to implement __format__
6131#
6132# A format specifier for Decimal looks like:
6133#
Eric Smith984bb582010-11-25 16:08:06 +00006134# [[fill]align][sign][#][0][minimumwidth][,][.precision][type]
Christian Heimesf16baeb2008-02-29 14:57:44 +00006135
6136_parse_format_specifier_regex = re.compile(r"""\A
6137(?:
6138 (?P<fill>.)?
6139 (?P<align>[<>=^])
6140)?
6141(?P<sign>[-+ ])?
Eric Smith984bb582010-11-25 16:08:06 +00006142(?P<alt>\#)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006143(?P<zeropad>0)?
6144(?P<minimumwidth>(?!0)\d+)?
Mark Dickinson79f52032009-03-17 23:12:51 +00006145(?P<thousands_sep>,)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006146(?:\.(?P<precision>0|(?!0)\d+))?
Mark Dickinson79f52032009-03-17 23:12:51 +00006147(?P<type>[eEfFgGn%])?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006148\Z
Stefan Krah6edda142013-05-29 15:45:38 +02006149""", re.VERBOSE|re.DOTALL)
Christian Heimesf16baeb2008-02-29 14:57:44 +00006150
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006151del re
6152
Mark Dickinson79f52032009-03-17 23:12:51 +00006153# The locale module is only needed for the 'n' format specifier. The
6154# rest of the PEP 3101 code functions quite happily without it, so we
6155# don't care too much if locale isn't present.
6156try:
6157 import locale as _locale
Brett Cannoncd171c82013-07-04 17:43:24 -04006158except ImportError:
Mark Dickinson79f52032009-03-17 23:12:51 +00006159 pass
6160
6161def _parse_format_specifier(format_spec, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00006162 """Parse and validate a format specifier.
6163
6164 Turns a standard numeric format specifier into a dict, with the
6165 following entries:
6166
6167 fill: fill character to pad field to minimum width
6168 align: alignment type, either '<', '>', '=' or '^'
6169 sign: either '+', '-' or ' '
6170 minimumwidth: nonnegative integer giving minimum width
Mark Dickinson79f52032009-03-17 23:12:51 +00006171 zeropad: boolean, indicating whether to pad with zeros
6172 thousands_sep: string to use as thousands separator, or ''
6173 grouping: grouping for thousands separators, in format
6174 used by localeconv
6175 decimal_point: string to use for decimal point
Christian Heimesf16baeb2008-02-29 14:57:44 +00006176 precision: nonnegative integer giving precision, or None
6177 type: one of the characters 'eEfFgG%', or None
Christian Heimesf16baeb2008-02-29 14:57:44 +00006178
6179 """
6180 m = _parse_format_specifier_regex.match(format_spec)
6181 if m is None:
6182 raise ValueError("Invalid format specifier: " + format_spec)
6183
6184 # get the dictionary
6185 format_dict = m.groupdict()
6186
Mark Dickinson79f52032009-03-17 23:12:51 +00006187 # zeropad; defaults for fill and alignment. If zero padding
6188 # is requested, the fill and align fields should be absent.
Christian Heimesf16baeb2008-02-29 14:57:44 +00006189 fill = format_dict['fill']
6190 align = format_dict['align']
Mark Dickinson79f52032009-03-17 23:12:51 +00006191 format_dict['zeropad'] = (format_dict['zeropad'] is not None)
6192 if format_dict['zeropad']:
6193 if fill is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00006194 raise ValueError("Fill character conflicts with '0'"
6195 " in format specifier: " + format_spec)
Mark Dickinson79f52032009-03-17 23:12:51 +00006196 if align is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00006197 raise ValueError("Alignment conflicts with '0' in "
6198 "format specifier: " + format_spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00006199 format_dict['fill'] = fill or ' '
Mark Dickinson46ab5d02009-09-08 20:22:46 +00006200 # PEP 3101 originally specified that the default alignment should
6201 # be left; it was later agreed that right-aligned makes more sense
6202 # for numeric types. See http://bugs.python.org/issue6857.
6203 format_dict['align'] = align or '>'
Christian Heimesf16baeb2008-02-29 14:57:44 +00006204
Mark Dickinson79f52032009-03-17 23:12:51 +00006205 # default sign handling: '-' for negative, '' for positive
Christian Heimesf16baeb2008-02-29 14:57:44 +00006206 if format_dict['sign'] is None:
6207 format_dict['sign'] = '-'
6208
Christian Heimesf16baeb2008-02-29 14:57:44 +00006209 # minimumwidth defaults to 0; precision remains None if not given
6210 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
6211 if format_dict['precision'] is not None:
6212 format_dict['precision'] = int(format_dict['precision'])
6213
6214 # if format type is 'g' or 'G' then a precision of 0 makes little
6215 # sense; convert it to 1. Same if format type is unspecified.
6216 if format_dict['precision'] == 0:
Stefan Krah1919b7e2012-03-21 18:25:23 +01006217 if format_dict['type'] is None or format_dict['type'] in 'gGn':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006218 format_dict['precision'] = 1
6219
Mark Dickinson79f52032009-03-17 23:12:51 +00006220 # determine thousands separator, grouping, and decimal separator, and
6221 # add appropriate entries to format_dict
6222 if format_dict['type'] == 'n':
6223 # apart from separators, 'n' behaves just like 'g'
6224 format_dict['type'] = 'g'
6225 if _localeconv is None:
6226 _localeconv = _locale.localeconv()
6227 if format_dict['thousands_sep'] is not None:
6228 raise ValueError("Explicit thousands separator conflicts with "
6229 "'n' type in format specifier: " + format_spec)
6230 format_dict['thousands_sep'] = _localeconv['thousands_sep']
6231 format_dict['grouping'] = _localeconv['grouping']
6232 format_dict['decimal_point'] = _localeconv['decimal_point']
6233 else:
6234 if format_dict['thousands_sep'] is None:
6235 format_dict['thousands_sep'] = ''
6236 format_dict['grouping'] = [3, 0]
6237 format_dict['decimal_point'] = '.'
Christian Heimesf16baeb2008-02-29 14:57:44 +00006238
6239 return format_dict
6240
Mark Dickinson79f52032009-03-17 23:12:51 +00006241def _format_align(sign, body, spec):
6242 """Given an unpadded, non-aligned numeric string 'body' and sign
Ezio Melotti42da6632011-03-15 05:18:48 +02006243 string 'sign', add padding and alignment conforming to the given
Mark Dickinson79f52032009-03-17 23:12:51 +00006244 format specifier dictionary 'spec' (as produced by
6245 parse_format_specifier).
Christian Heimesf16baeb2008-02-29 14:57:44 +00006246
6247 """
Christian Heimesf16baeb2008-02-29 14:57:44 +00006248 # how much extra space do we have to play with?
Mark Dickinson79f52032009-03-17 23:12:51 +00006249 minimumwidth = spec['minimumwidth']
6250 fill = spec['fill']
6251 padding = fill*(minimumwidth - len(sign) - len(body))
Christian Heimesf16baeb2008-02-29 14:57:44 +00006252
Mark Dickinson79f52032009-03-17 23:12:51 +00006253 align = spec['align']
Christian Heimesf16baeb2008-02-29 14:57:44 +00006254 if align == '<':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006255 result = sign + body + padding
Mark Dickinsonad416342009-03-17 18:10:15 +00006256 elif align == '>':
6257 result = padding + sign + body
Christian Heimesf16baeb2008-02-29 14:57:44 +00006258 elif align == '=':
6259 result = sign + padding + body
Mark Dickinson79f52032009-03-17 23:12:51 +00006260 elif align == '^':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006261 half = len(padding)//2
6262 result = padding[:half] + sign + body + padding[half:]
Mark Dickinson79f52032009-03-17 23:12:51 +00006263 else:
6264 raise ValueError('Unrecognised alignment field')
Christian Heimesf16baeb2008-02-29 14:57:44 +00006265
Christian Heimesf16baeb2008-02-29 14:57:44 +00006266 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006267
Mark Dickinson79f52032009-03-17 23:12:51 +00006268def _group_lengths(grouping):
6269 """Convert a localeconv-style grouping into a (possibly infinite)
6270 iterable of integers representing group lengths.
6271
6272 """
6273 # The result from localeconv()['grouping'], and the input to this
6274 # function, should be a list of integers in one of the
6275 # following three forms:
6276 #
6277 # (1) an empty list, or
6278 # (2) nonempty list of positive integers + [0]
6279 # (3) list of positive integers + [locale.CHAR_MAX], or
6280
6281 from itertools import chain, repeat
6282 if not grouping:
6283 return []
6284 elif grouping[-1] == 0 and len(grouping) >= 2:
6285 return chain(grouping[:-1], repeat(grouping[-2]))
6286 elif grouping[-1] == _locale.CHAR_MAX:
6287 return grouping[:-1]
6288 else:
6289 raise ValueError('unrecognised format for grouping')
6290
6291def _insert_thousands_sep(digits, spec, min_width=1):
6292 """Insert thousands separators into a digit string.
6293
6294 spec is a dictionary whose keys should include 'thousands_sep' and
6295 'grouping'; typically it's the result of parsing the format
6296 specifier using _parse_format_specifier.
6297
6298 The min_width keyword argument gives the minimum length of the
6299 result, which will be padded on the left with zeros if necessary.
6300
6301 If necessary, the zero padding adds an extra '0' on the left to
6302 avoid a leading thousands separator. For example, inserting
6303 commas every three digits in '123456', with min_width=8, gives
6304 '0,123,456', even though that has length 9.
6305
6306 """
6307
6308 sep = spec['thousands_sep']
6309 grouping = spec['grouping']
6310
6311 groups = []
6312 for l in _group_lengths(grouping):
Mark Dickinson79f52032009-03-17 23:12:51 +00006313 if l <= 0:
6314 raise ValueError("group length should be positive")
6315 # max(..., 1) forces at least 1 digit to the left of a separator
6316 l = min(max(len(digits), min_width, 1), l)
6317 groups.append('0'*(l - len(digits)) + digits[-l:])
6318 digits = digits[:-l]
6319 min_width -= l
6320 if not digits and min_width <= 0:
6321 break
Mark Dickinson7303b592009-03-18 08:25:36 +00006322 min_width -= len(sep)
Mark Dickinson79f52032009-03-17 23:12:51 +00006323 else:
6324 l = max(len(digits), min_width, 1)
6325 groups.append('0'*(l - len(digits)) + digits[-l:])
6326 return sep.join(reversed(groups))
6327
6328def _format_sign(is_negative, spec):
6329 """Determine sign character."""
6330
6331 if is_negative:
6332 return '-'
6333 elif spec['sign'] in ' +':
6334 return spec['sign']
6335 else:
6336 return ''
6337
6338def _format_number(is_negative, intpart, fracpart, exp, spec):
6339 """Format a number, given the following data:
6340
6341 is_negative: true if the number is negative, else false
6342 intpart: string of digits that must appear before the decimal point
6343 fracpart: string of digits that must come after the point
6344 exp: exponent, as an integer
6345 spec: dictionary resulting from parsing the format specifier
6346
6347 This function uses the information in spec to:
6348 insert separators (decimal separator and thousands separators)
6349 format the sign
6350 format the exponent
6351 add trailing '%' for the '%' type
6352 zero-pad if necessary
6353 fill and align if necessary
6354 """
6355
6356 sign = _format_sign(is_negative, spec)
6357
Eric Smith984bb582010-11-25 16:08:06 +00006358 if fracpart or spec['alt']:
Mark Dickinson79f52032009-03-17 23:12:51 +00006359 fracpart = spec['decimal_point'] + fracpart
6360
6361 if exp != 0 or spec['type'] in 'eE':
6362 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
6363 fracpart += "{0}{1:+}".format(echar, exp)
6364 if spec['type'] == '%':
6365 fracpart += '%'
6366
6367 if spec['zeropad']:
6368 min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
6369 else:
6370 min_width = 0
6371 intpart = _insert_thousands_sep(intpart, spec, min_width)
6372
6373 return _format_align(sign, intpart+fracpart, spec)
6374
6375
Guido van Rossumd8faa362007-04-27 19:54:29 +00006376##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006377
Guido van Rossumd8faa362007-04-27 19:54:29 +00006378# Reusable defaults
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006379_Infinity = Decimal('Inf')
6380_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonf9236412009-01-02 23:23:21 +00006381_NaN = Decimal('NaN')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006382_Zero = Decimal(0)
6383_One = Decimal(1)
6384_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006385
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006386# _SignedInfinity[sign] is infinity w/ that sign
6387_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006388
Mark Dickinsondc787d22010-05-23 13:33:13 +00006389# Constants related to the hash implementation; hash(x) is based
6390# on the reduction of x modulo _PyHASH_MODULUS
Mark Dickinsondc787d22010-05-23 13:33:13 +00006391_PyHASH_MODULUS = sys.hash_info.modulus
6392# hash values to use for positive and negative infinities, and nans
6393_PyHASH_INF = sys.hash_info.inf
6394_PyHASH_NAN = sys.hash_info.nan
Mark Dickinsondc787d22010-05-23 13:33:13 +00006395
6396# _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS
6397_PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)
Stefan Krah1919b7e2012-03-21 18:25:23 +01006398del sys
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006399
Stefan Krah1919b7e2012-03-21 18:25:23 +01006400try:
6401 import _decimal
Brett Cannoncd171c82013-07-04 17:43:24 -04006402except ImportError:
Stefan Krah1919b7e2012-03-21 18:25:23 +01006403 pass
6404else:
6405 s1 = set(dir())
6406 s2 = set(dir(_decimal))
6407 for name in s1 - s2:
6408 del globals()[name]
6409 del s1, s2, name
6410 from _decimal import *
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006411
6412if __name__ == '__main__':
Raymond Hettinger6d7e26e2011-02-01 23:54:43 +00006413 import doctest, decimal
6414 doctest.testmod(decimal)