blob: 324e4f91cae84ef3ed2220a20f9daecb307161a2 [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):
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +0200970 """Compare self to other. Return a decimal value:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +0200972 a or b is a NaN ==> Decimal('NaN')
973 a < b ==> Decimal('-1')
974 a == b ==> Decimal('0')
975 a > b ==> Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000976 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000977 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000978
Guido van Rossumd8faa362007-04-27 19:54:29 +0000979 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000980 if (self._is_special or other and other._is_special):
981 ans = self._check_nans(other, context)
982 if ans:
983 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000984
Christian Heimes77c02eb2008-02-09 02:18:51 +0000985 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000986
987 def __hash__(self):
988 """x.__hash__() <==> hash(x)"""
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000989
Mark Dickinsondc787d22010-05-23 13:33:13 +0000990 # In order to make sure that the hash of a Decimal instance
991 # agrees with the hash of a numerically equal integer, float
992 # or Fraction, we follow the rules for numeric hashes outlined
993 # in the documentation. (See library docs, 'Built-in Types').
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000994 if self._is_special:
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000995 if self.is_snan():
Raymond Hettingerd325c4b2010-11-21 04:08:28 +0000996 raise TypeError('Cannot hash a signaling NaN value.')
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000997 elif self.is_nan():
Mark Dickinsondc787d22010-05-23 13:33:13 +0000998 return _PyHASH_NAN
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000999 else:
Mark Dickinsonac256ab2010-04-03 11:08:14 +00001000 if self._sign:
Mark Dickinsondc787d22010-05-23 13:33:13 +00001001 return -_PyHASH_INF
Mark Dickinsonac256ab2010-04-03 11:08:14 +00001002 else:
Mark Dickinsondc787d22010-05-23 13:33:13 +00001003 return _PyHASH_INF
Mark Dickinsonac256ab2010-04-03 11:08:14 +00001004
Mark Dickinsondc787d22010-05-23 13:33:13 +00001005 if self._exp >= 0:
1006 exp_hash = pow(10, self._exp, _PyHASH_MODULUS)
1007 else:
1008 exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS)
1009 hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS
Stefan Krahdc817b22010-11-17 11:16:34 +00001010 ans = hash_ if self >= 0 else -hash_
1011 return -2 if ans == -1 else ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001012
1013 def as_tuple(self):
1014 """Represents the number as a triple tuple.
1015
1016 To show the internals exactly as they are.
1017 """
Christian Heimes25bb7832008-01-11 16:17:00 +00001018 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001019
1020 def __repr__(self):
1021 """Represents the number as an instance of Decimal."""
1022 # Invariant: eval(repr(d)) == d
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001023 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001024
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001025 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001026 """Return string representation of the number in scientific notation.
1027
1028 Captures all of the information in the underlying representation.
1029 """
1030
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001031 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +00001032 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001033 if self._exp == 'F':
1034 return sign + 'Infinity'
1035 elif self._exp == 'n':
1036 return sign + 'NaN' + self._int
1037 else: # self._exp == 'N'
1038 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001039
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001040 # number of digits of self._int to left of decimal point
1041 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001042
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001043 # dotplace is number of digits of self._int to the left of the
1044 # decimal point in the mantissa of the output string (that is,
1045 # after adjusting the exponent)
1046 if self._exp <= 0 and leftdigits > -6:
1047 # no exponent required
1048 dotplace = leftdigits
1049 elif not eng:
1050 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001051 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001052 elif self._int == '0':
1053 # engineering notation, zero
1054 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001056 # engineering notation, nonzero
1057 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001058
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001059 if dotplace <= 0:
1060 intpart = '0'
1061 fracpart = '.' + '0'*(-dotplace) + self._int
1062 elif dotplace >= len(self._int):
1063 intpart = self._int+'0'*(dotplace-len(self._int))
1064 fracpart = ''
1065 else:
1066 intpart = self._int[:dotplace]
1067 fracpart = '.' + self._int[dotplace:]
1068 if leftdigits == dotplace:
1069 exp = ''
1070 else:
1071 if context is None:
1072 context = getcontext()
1073 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1074
1075 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001076
1077 def to_eng_string(self, context=None):
1078 """Convert to engineering-type string.
1079
1080 Engineering notation has an exponent which is a multiple of 3, so there
1081 are up to 3 digits left of the decimal place.
1082
1083 Same rules for when in exponential and when as a value as in __str__.
1084 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001085 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001086
1087 def __neg__(self, context=None):
1088 """Returns a copy with the sign switched.
1089
1090 Rounds, if it has reason.
1091 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001092 if self._is_special:
1093 ans = self._check_nans(context=context)
1094 if ans:
1095 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001096
Mark Dickinson37a79fb2011-03-12 11:12:52 +00001097 if context is None:
1098 context = getcontext()
1099
1100 if not self and context.rounding != ROUND_FLOOR:
1101 # -Decimal('0') is Decimal('0'), not Decimal('-0'), except
1102 # in ROUND_FLOOR rounding mode.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001103 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001104 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001105 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001106
Christian Heimes2c181612007-12-17 20:04:13 +00001107 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001108
1109 def __pos__(self, context=None):
1110 """Returns a copy, unless it is a sNaN.
1111
1112 Rounds the number (if more then precision digits)
1113 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001114 if self._is_special:
1115 ans = self._check_nans(context=context)
1116 if ans:
1117 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001118
Mark Dickinson37a79fb2011-03-12 11:12:52 +00001119 if context is None:
1120 context = getcontext()
1121
1122 if not self and context.rounding != ROUND_FLOOR:
1123 # + (-0) = 0, except in ROUND_FLOOR rounding mode.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001124 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001125 else:
1126 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001127
Christian Heimes2c181612007-12-17 20:04:13 +00001128 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001129
Christian Heimes2c181612007-12-17 20:04:13 +00001130 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001131 """Returns the absolute value of self.
1132
Christian Heimes2c181612007-12-17 20:04:13 +00001133 If the keyword argument 'round' is false, do not round. The
1134 expression self.__abs__(round=False) is equivalent to
1135 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001136 """
Christian Heimes2c181612007-12-17 20:04:13 +00001137 if not round:
1138 return self.copy_abs()
1139
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001140 if self._is_special:
1141 ans = self._check_nans(context=context)
1142 if ans:
1143 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001144
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001145 if self._sign:
1146 ans = self.__neg__(context=context)
1147 else:
1148 ans = self.__pos__(context=context)
1149
1150 return ans
1151
1152 def __add__(self, other, context=None):
1153 """Returns self + other.
1154
1155 -INF + INF (or the reverse) cause InvalidOperation errors.
1156 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001157 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001158 if other is NotImplemented:
1159 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001160
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001161 if context is None:
1162 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001163
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001164 if self._is_special or other._is_special:
1165 ans = self._check_nans(other, context)
1166 if ans:
1167 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001168
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001169 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001170 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001171 if self._sign != other._sign and other._isinfinity():
1172 return context._raise_error(InvalidOperation, '-INF + INF')
1173 return Decimal(self)
1174 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001175 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001176
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001177 exp = min(self._exp, other._exp)
1178 negativezero = 0
1179 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001180 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001181 negativezero = 1
1182
1183 if not self and not other:
1184 sign = min(self._sign, other._sign)
1185 if negativezero:
1186 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001187 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001188 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001189 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001190 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001191 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001192 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001193 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001194 return ans
1195 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001196 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001197 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001198 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001199 return ans
1200
1201 op1 = _WorkRep(self)
1202 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001203 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001204
1205 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001206 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001207 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001208 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001209 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001210 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001211 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001212 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001213 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001214 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001215 if op1.sign == 1:
1216 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001217 op1.sign, op2.sign = op2.sign, op1.sign
1218 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001219 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001220 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001221 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001222 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001223 op1.sign, op2.sign = (0, 0)
1224 else:
1225 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001226 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001227
Raymond Hettinger17931de2004-10-27 06:21:46 +00001228 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001229 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001230 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001231 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001232
1233 result.exp = op1.exp
1234 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001235 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001236 return ans
1237
1238 __radd__ = __add__
1239
1240 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001241 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001242 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001243 if other is NotImplemented:
1244 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001245
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001246 if self._is_special or other._is_special:
1247 ans = self._check_nans(other, context=context)
1248 if ans:
1249 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001250
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001251 # self - other is computed as self + other.copy_negate()
1252 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001253
1254 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001255 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001256 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001257 if other is NotImplemented:
1258 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001259
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001260 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001261
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001262 def __mul__(self, other, context=None):
1263 """Return self * other.
1264
1265 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1266 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001267 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001268 if other is NotImplemented:
1269 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001270
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001271 if context is None:
1272 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001273
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001274 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001275
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001276 if self._is_special or other._is_special:
1277 ans = self._check_nans(other, context)
1278 if ans:
1279 return ans
1280
1281 if self._isinfinity():
1282 if not other:
1283 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001284 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001285
1286 if other._isinfinity():
1287 if not self:
1288 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001289 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001290
1291 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001292
1293 # Special case for multiplying by zero
1294 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001295 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001296 # Fixing in case the exponent is out of bounds
1297 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001298 return ans
1299
1300 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001301 if self._int == '1':
1302 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001303 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001304 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001305 if other._int == '1':
1306 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001307 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001308 return ans
1309
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001310 op1 = _WorkRep(self)
1311 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001312
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001313 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001314 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001315
1316 return ans
1317 __rmul__ = __mul__
1318
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001319 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001320 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001321 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001322 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001323 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001324
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001325 if context is None:
1326 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001327
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001328 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001329
1330 if self._is_special or other._is_special:
1331 ans = self._check_nans(other, context)
1332 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001333 return ans
1334
1335 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001336 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001337
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001338 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001339 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001340
1341 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001342 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001343 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001344
1345 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001346 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001347 if not self:
1348 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001349 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001350
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001351 if not self:
1352 exp = self._exp - other._exp
1353 coeff = 0
1354 else:
1355 # OK, so neither = 0, INF or NaN
1356 shift = len(other._int) - len(self._int) + context.prec + 1
1357 exp = self._exp - other._exp - shift
1358 op1 = _WorkRep(self)
1359 op2 = _WorkRep(other)
1360 if shift >= 0:
1361 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1362 else:
1363 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1364 if remainder:
1365 # result is not exact; adjust to ensure correct rounding
1366 if coeff % 5 == 0:
1367 coeff += 1
1368 else:
1369 # result is exact; get as close to ideal exponent as possible
1370 ideal_exp = self._exp - other._exp
1371 while exp < ideal_exp and coeff % 10 == 0:
1372 coeff //= 10
1373 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001374
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001375 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001376 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001377
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001378 def _divide(self, other, context):
1379 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001380
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001381 Assumes that neither self nor other is a NaN, that self is not
1382 infinite and that other is nonzero.
1383 """
1384 sign = self._sign ^ other._sign
1385 if other._isinfinity():
1386 ideal_exp = self._exp
1387 else:
1388 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001389
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001390 expdiff = self.adjusted() - other.adjusted()
1391 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001392 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001393 self._rescale(ideal_exp, context.rounding))
1394 if expdiff <= context.prec:
1395 op1 = _WorkRep(self)
1396 op2 = _WorkRep(other)
1397 if op1.exp >= op2.exp:
1398 op1.int *= 10**(op1.exp - op2.exp)
1399 else:
1400 op2.int *= 10**(op2.exp - op1.exp)
1401 q, r = divmod(op1.int, op2.int)
1402 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001403 return (_dec_from_triple(sign, str(q), 0),
1404 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001405
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001406 # Here the quotient is too large to be representable
1407 ans = context._raise_error(DivisionImpossible,
1408 'quotient too large in //, % or divmod')
1409 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001410
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001411 def __rtruediv__(self, other, context=None):
1412 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001413 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001414 if other is NotImplemented:
1415 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001416 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001417
1418 def __divmod__(self, other, context=None):
1419 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001420 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001421 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001422 other = _convert_other(other)
1423 if other is NotImplemented:
1424 return other
1425
1426 if context is None:
1427 context = getcontext()
1428
1429 ans = self._check_nans(other, context)
1430 if ans:
1431 return (ans, ans)
1432
1433 sign = self._sign ^ other._sign
1434 if self._isinfinity():
1435 if other._isinfinity():
1436 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1437 return ans, ans
1438 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001439 return (_SignedInfinity[sign],
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001440 context._raise_error(InvalidOperation, 'INF % x'))
1441
1442 if not other:
1443 if not self:
1444 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1445 return ans, ans
1446 else:
1447 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1448 context._raise_error(InvalidOperation, 'x % 0'))
1449
1450 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001451 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001452 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001453
1454 def __rdivmod__(self, other, context=None):
1455 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001456 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001457 if other is NotImplemented:
1458 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001459 return other.__divmod__(self, context=context)
1460
1461 def __mod__(self, other, context=None):
1462 """
1463 self % other
1464 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001465 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001466 if other is NotImplemented:
1467 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001468
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001469 if context is None:
1470 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001471
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001472 ans = self._check_nans(other, context)
1473 if ans:
1474 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001475
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001476 if self._isinfinity():
1477 return context._raise_error(InvalidOperation, 'INF % x')
1478 elif not other:
1479 if self:
1480 return context._raise_error(InvalidOperation, 'x % 0')
1481 else:
1482 return context._raise_error(DivisionUndefined, '0 % 0')
1483
1484 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001485 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001486 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001487
1488 def __rmod__(self, other, context=None):
1489 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001490 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001491 if other is NotImplemented:
1492 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001493 return other.__mod__(self, context=context)
1494
1495 def remainder_near(self, other, context=None):
1496 """
1497 Remainder nearest to 0- abs(remainder-near) <= other/2
1498 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001499 if context is None:
1500 context = getcontext()
1501
1502 other = _convert_other(other, raiseit=True)
1503
1504 ans = self._check_nans(other, context)
1505 if ans:
1506 return ans
1507
1508 # self == +/-infinity -> InvalidOperation
1509 if self._isinfinity():
1510 return context._raise_error(InvalidOperation,
1511 'remainder_near(infinity, x)')
1512
1513 # other == 0 -> either InvalidOperation or DivisionUndefined
1514 if not other:
1515 if self:
1516 return context._raise_error(InvalidOperation,
1517 'remainder_near(x, 0)')
1518 else:
1519 return context._raise_error(DivisionUndefined,
1520 'remainder_near(0, 0)')
1521
1522 # other = +/-infinity -> remainder = self
1523 if other._isinfinity():
1524 ans = Decimal(self)
1525 return ans._fix(context)
1526
1527 # self = 0 -> remainder = self, with ideal exponent
1528 ideal_exponent = min(self._exp, other._exp)
1529 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001530 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001531 return ans._fix(context)
1532
1533 # catch most cases of large or small quotient
1534 expdiff = self.adjusted() - other.adjusted()
1535 if expdiff >= context.prec + 1:
1536 # expdiff >= prec+1 => abs(self/other) > 10**prec
1537 return context._raise_error(DivisionImpossible)
1538 if expdiff <= -2:
1539 # expdiff <= -2 => abs(self/other) < 0.1
1540 ans = self._rescale(ideal_exponent, context.rounding)
1541 return ans._fix(context)
1542
1543 # adjust both arguments to have the same exponent, then divide
1544 op1 = _WorkRep(self)
1545 op2 = _WorkRep(other)
1546 if op1.exp >= op2.exp:
1547 op1.int *= 10**(op1.exp - op2.exp)
1548 else:
1549 op2.int *= 10**(op2.exp - op1.exp)
1550 q, r = divmod(op1.int, op2.int)
1551 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1552 # 10**ideal_exponent. Apply correction to ensure that
1553 # abs(remainder) <= abs(other)/2
1554 if 2*r + (q&1) > op2.int:
1555 r -= op2.int
1556 q += 1
1557
1558 if q >= 10**context.prec:
1559 return context._raise_error(DivisionImpossible)
1560
1561 # result has same sign as self unless r is negative
1562 sign = self._sign
1563 if r < 0:
1564 sign = 1-sign
1565 r = -r
1566
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001567 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001568 return ans._fix(context)
1569
1570 def __floordiv__(self, other, context=None):
1571 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001572 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001573 if other is NotImplemented:
1574 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001575
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001576 if context is None:
1577 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001578
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001579 ans = self._check_nans(other, context)
1580 if ans:
1581 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001582
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001583 if self._isinfinity():
1584 if other._isinfinity():
1585 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001586 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001587 return _SignedInfinity[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001588
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001589 if not other:
1590 if self:
1591 return context._raise_error(DivisionByZero, 'x // 0',
1592 self._sign ^ other._sign)
1593 else:
1594 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001595
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001596 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001597
1598 def __rfloordiv__(self, other, context=None):
1599 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001600 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001601 if other is NotImplemented:
1602 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001603 return other.__floordiv__(self, context=context)
1604
1605 def __float__(self):
1606 """Float representation."""
Mark Dickinsonfc33d4c2012-08-24 18:53:10 +01001607 if self._isnan():
1608 if self.is_snan():
1609 raise ValueError("Cannot convert signaling NaN to float")
1610 s = "-nan" if self._sign else "nan"
1611 else:
1612 s = str(self)
1613 return float(s)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001614
1615 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001616 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001617 if self._is_special:
1618 if self._isnan():
Mark Dickinson825fce32009-09-07 18:08:12 +00001619 raise ValueError("Cannot convert NaN to integer")
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001620 elif self._isinfinity():
Mark Dickinson825fce32009-09-07 18:08:12 +00001621 raise OverflowError("Cannot convert infinity to integer")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001622 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001623 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001624 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001625 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001626 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001627
Christian Heimes969fe572008-01-25 11:23:10 +00001628 __trunc__ = __int__
1629
Christian Heimes0bd4e112008-02-12 22:59:25 +00001630 def real(self):
1631 return self
Mark Dickinson315a20a2009-01-04 21:34:18 +00001632 real = property(real)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001633
Christian Heimes0bd4e112008-02-12 22:59:25 +00001634 def imag(self):
1635 return Decimal(0)
Mark Dickinson315a20a2009-01-04 21:34:18 +00001636 imag = property(imag)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001637
1638 def conjugate(self):
1639 return self
1640
1641 def __complex__(self):
1642 return complex(float(self))
1643
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001644 def _fix_nan(self, context):
1645 """Decapitate the payload of a NaN to fit the context"""
1646 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001647
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001648 # maximum length of payload is precision if clamp=0,
1649 # precision-1 if clamp=1.
1650 max_payload_len = context.prec - context.clamp
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001651 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001652 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1653 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001654 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001655
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001656 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001657 """Round if it is necessary to keep self within prec precision.
1658
1659 Rounds and fixes the exponent. Does not raise on a sNaN.
1660
1661 Arguments:
1662 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001663 context - context used.
1664 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001665
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001666 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001667 if self._isnan():
1668 # decapitate payload if necessary
1669 return self._fix_nan(context)
1670 else:
1671 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001672 return Decimal(self)
1673
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001674 # if self is zero then exponent should be between Etiny and
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001675 # Emax if clamp==0, and between Etiny and Etop if clamp==1.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001676 Etiny = context.Etiny()
1677 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001678 if not self:
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001679 exp_max = [context.Emax, Etop][context.clamp]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001680 new_exp = min(max(self._exp, Etiny), exp_max)
1681 if new_exp != self._exp:
1682 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001683 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001684 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001685 return Decimal(self)
1686
1687 # exp_min is the smallest allowable exponent of the result,
1688 # equal to max(self.adjusted()-context.prec+1, Etiny)
1689 exp_min = len(self._int) + self._exp - context.prec
1690 if exp_min > Etop:
1691 # overflow: exp_min > Etop iff self.adjusted() > Emax
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001692 ans = context._raise_error(Overflow, 'above Emax', self._sign)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001693 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001694 context._raise_error(Rounded)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001695 return ans
1696
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001697 self_is_subnormal = exp_min < Etiny
1698 if self_is_subnormal:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001699 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001700
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001701 # round if self has too many digits
1702 if self._exp < exp_min:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001703 digits = len(self._int) + self._exp - exp_min
1704 if digits < 0:
1705 self = _dec_from_triple(self._sign, '1', exp_min-1)
1706 digits = 0
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001707 rounding_method = self._pick_rounding_function[context.rounding]
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04001708 changed = rounding_method(self, digits)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001709 coeff = self._int[:digits] or '0'
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001710 if changed > 0:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001711 coeff = str(int(coeff)+1)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001712 if len(coeff) > context.prec:
1713 coeff = coeff[:-1]
1714 exp_min += 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001715
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001716 # check whether the rounding pushed the exponent out of range
1717 if exp_min > Etop:
1718 ans = context._raise_error(Overflow, 'above Emax', self._sign)
1719 else:
1720 ans = _dec_from_triple(self._sign, coeff, exp_min)
1721
1722 # raise the appropriate signals, taking care to respect
1723 # the precedence described in the specification
1724 if changed and self_is_subnormal:
1725 context._raise_error(Underflow)
1726 if self_is_subnormal:
1727 context._raise_error(Subnormal)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001728 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001729 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001730 context._raise_error(Rounded)
1731 if not ans:
1732 # raise Clamped on underflow to 0
1733 context._raise_error(Clamped)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001734 return ans
1735
Mark Dickinsonc69160e2010-05-04 14:35:33 +00001736 if self_is_subnormal:
1737 context._raise_error(Subnormal)
1738
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001739 # fold down if clamp == 1 and self has too few digits
1740 if context.clamp == 1 and self._exp > Etop:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001741 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001742 self_padded = self._int + '0'*(self._exp - Etop)
1743 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001744
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001745 # here self was representable to begin with; return unchanged
1746 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001747
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001748 # for each of the rounding functions below:
1749 # self is a finite, nonzero Decimal
1750 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001751 #
1752 # each function returns either -1, 0, or 1, as follows:
1753 # 1 indicates that self should be rounded up (away from zero)
1754 # 0 indicates that self should be truncated, and that all the
1755 # digits to be truncated are zeros (so the value is unchanged)
1756 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001757
1758 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001759 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001760 if _all_zeros(self._int, prec):
1761 return 0
1762 else:
1763 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001764
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001765 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001766 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001767 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001768
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001769 def _round_half_up(self, prec):
1770 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001771 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001772 return 1
1773 elif _all_zeros(self._int, prec):
1774 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001775 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001776 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001777
1778 def _round_half_down(self, prec):
1779 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001780 if _exact_half(self._int, prec):
1781 return -1
1782 else:
1783 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001784
1785 def _round_half_even(self, prec):
1786 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001787 if _exact_half(self._int, prec) and \
1788 (prec == 0 or self._int[prec-1] in '02468'):
1789 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001790 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001791 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001792
1793 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001794 """Rounds up (not away from 0 if negative.)"""
1795 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001796 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001797 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001798 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001799
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001800 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001801 """Rounds down (not towards 0 if negative)"""
1802 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001803 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001804 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001805 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001806
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001807 def _round_05up(self, prec):
1808 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001809 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001810 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001811 else:
1812 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001813
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04001814 _pick_rounding_function = dict(
1815 ROUND_DOWN = _round_down,
1816 ROUND_UP = _round_up,
1817 ROUND_HALF_UP = _round_half_up,
1818 ROUND_HALF_DOWN = _round_half_down,
1819 ROUND_HALF_EVEN = _round_half_even,
1820 ROUND_CEILING = _round_ceiling,
1821 ROUND_FLOOR = _round_floor,
1822 ROUND_05UP = _round_05up,
1823 )
1824
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001825 def __round__(self, n=None):
1826 """Round self to the nearest integer, or to a given precision.
1827
1828 If only one argument is supplied, round a finite Decimal
1829 instance self to the nearest integer. If self is infinite or
1830 a NaN then a Python exception is raised. If self is finite
1831 and lies exactly halfway between two integers then it is
1832 rounded to the integer with even last digit.
1833
1834 >>> round(Decimal('123.456'))
1835 123
1836 >>> round(Decimal('-456.789'))
1837 -457
1838 >>> round(Decimal('-3.0'))
1839 -3
1840 >>> round(Decimal('2.5'))
1841 2
1842 >>> round(Decimal('3.5'))
1843 4
1844 >>> round(Decimal('Inf'))
1845 Traceback (most recent call last):
1846 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001847 OverflowError: cannot round an infinity
1848 >>> round(Decimal('NaN'))
1849 Traceback (most recent call last):
1850 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001851 ValueError: cannot round a NaN
1852
1853 If a second argument n is supplied, self is rounded to n
1854 decimal places using the rounding mode for the current
1855 context.
1856
1857 For an integer n, round(self, -n) is exactly equivalent to
1858 self.quantize(Decimal('1En')).
1859
1860 >>> round(Decimal('123.456'), 0)
1861 Decimal('123')
1862 >>> round(Decimal('123.456'), 2)
1863 Decimal('123.46')
1864 >>> round(Decimal('123.456'), -2)
1865 Decimal('1E+2')
1866 >>> round(Decimal('-Infinity'), 37)
1867 Decimal('NaN')
1868 >>> round(Decimal('sNaN123'), 0)
1869 Decimal('NaN123')
1870
1871 """
1872 if n is not None:
1873 # two-argument form: use the equivalent quantize call
1874 if not isinstance(n, int):
1875 raise TypeError('Second argument to round should be integral')
1876 exp = _dec_from_triple(0, '1', -n)
1877 return self.quantize(exp)
1878
1879 # one-argument form
1880 if self._is_special:
1881 if self.is_nan():
1882 raise ValueError("cannot round a NaN")
1883 else:
1884 raise OverflowError("cannot round an infinity")
1885 return int(self._rescale(0, ROUND_HALF_EVEN))
1886
1887 def __floor__(self):
1888 """Return the floor of self, as an integer.
1889
1890 For a finite Decimal instance self, return the greatest
1891 integer n such that n <= self. If self is infinite or a NaN
1892 then a Python exception is raised.
1893
1894 """
1895 if self._is_special:
1896 if self.is_nan():
1897 raise ValueError("cannot round a NaN")
1898 else:
1899 raise OverflowError("cannot round an infinity")
1900 return int(self._rescale(0, ROUND_FLOOR))
1901
1902 def __ceil__(self):
1903 """Return the ceiling of self, as an integer.
1904
1905 For a finite Decimal instance self, return the least integer n
1906 such that n >= self. If self is infinite or a NaN then a
1907 Python exception is raised.
1908
1909 """
1910 if self._is_special:
1911 if self.is_nan():
1912 raise ValueError("cannot round a NaN")
1913 else:
1914 raise OverflowError("cannot round an infinity")
1915 return int(self._rescale(0, ROUND_CEILING))
1916
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001917 def fma(self, other, third, context=None):
1918 """Fused multiply-add.
1919
1920 Returns self*other+third with no rounding of the intermediate
1921 product self*other.
1922
1923 self and other are multiplied together, with no rounding of
1924 the result. The third operand is then added to the result,
1925 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001926 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001927
1928 other = _convert_other(other, raiseit=True)
Mark Dickinsonb455e582011-05-22 12:53:18 +01001929 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001930
1931 # compute product; raise InvalidOperation if either operand is
1932 # a signaling NaN or if the product is zero times infinity.
1933 if self._is_special or other._is_special:
1934 if context is None:
1935 context = getcontext()
1936 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001937 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001938 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001939 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001940 if self._exp == 'n':
1941 product = self
1942 elif other._exp == 'n':
1943 product = other
1944 elif self._exp == 'F':
1945 if not other:
1946 return context._raise_error(InvalidOperation,
1947 'INF * 0 in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001948 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001949 elif other._exp == 'F':
1950 if not self:
1951 return context._raise_error(InvalidOperation,
1952 '0 * INF in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001953 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001954 else:
1955 product = _dec_from_triple(self._sign ^ other._sign,
1956 str(int(self._int) * int(other._int)),
1957 self._exp + other._exp)
1958
Christian Heimes8b0facf2007-12-04 19:30:01 +00001959 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001960
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001961 def _power_modulo(self, other, modulo, context=None):
1962 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001963
Stefan Krah1919b7e2012-03-21 18:25:23 +01001964 other = _convert_other(other)
1965 if other is NotImplemented:
1966 return other
1967 modulo = _convert_other(modulo)
1968 if modulo is NotImplemented:
1969 return modulo
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001970
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001971 if context is None:
1972 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001973
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001974 # deal with NaNs: if there are any sNaNs then first one wins,
1975 # (i.e. behaviour for NaNs is identical to that of fma)
1976 self_is_nan = self._isnan()
1977 other_is_nan = other._isnan()
1978 modulo_is_nan = modulo._isnan()
1979 if self_is_nan or other_is_nan or modulo_is_nan:
1980 if self_is_nan == 2:
1981 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001982 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001983 if other_is_nan == 2:
1984 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001985 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001986 if modulo_is_nan == 2:
1987 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001988 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001989 if self_is_nan:
1990 return self._fix_nan(context)
1991 if other_is_nan:
1992 return other._fix_nan(context)
1993 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001994
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001995 # check inputs: we apply same restrictions as Python's pow()
1996 if not (self._isinteger() and
1997 other._isinteger() and
1998 modulo._isinteger()):
1999 return context._raise_error(InvalidOperation,
2000 'pow() 3rd argument not allowed '
2001 'unless all arguments are integers')
2002 if other < 0:
2003 return context._raise_error(InvalidOperation,
2004 'pow() 2nd argument cannot be '
2005 'negative when 3rd argument specified')
2006 if not modulo:
2007 return context._raise_error(InvalidOperation,
2008 'pow() 3rd argument cannot be 0')
2009
2010 # additional restriction for decimal: the modulus must be less
2011 # than 10**prec in absolute value
2012 if modulo.adjusted() >= context.prec:
2013 return context._raise_error(InvalidOperation,
2014 'insufficient precision: pow() 3rd '
2015 'argument must not have more than '
2016 'precision digits')
2017
2018 # define 0**0 == NaN, for consistency with two-argument pow
2019 # (even though it hurts!)
2020 if not other and not self:
2021 return context._raise_error(InvalidOperation,
2022 'at least one of pow() 1st argument '
2023 'and 2nd argument must be nonzero ;'
2024 '0**0 is not defined')
2025
2026 # compute sign of result
2027 if other._iseven():
2028 sign = 0
2029 else:
2030 sign = self._sign
2031
2032 # convert modulo to a Python integer, and self and other to
2033 # Decimal integers (i.e. force their exponents to be >= 0)
2034 modulo = abs(int(modulo))
2035 base = _WorkRep(self.to_integral_value())
2036 exponent = _WorkRep(other.to_integral_value())
2037
2038 # compute result using integer pow()
2039 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
2040 for i in range(exponent.exp):
2041 base = pow(base, 10, modulo)
2042 base = pow(base, exponent.int, modulo)
2043
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002044 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002045
2046 def _power_exact(self, other, p):
2047 """Attempt to compute self**other exactly.
2048
2049 Given Decimals self and other and an integer p, attempt to
2050 compute an exact result for the power self**other, with p
2051 digits of precision. Return None if self**other is not
2052 exactly representable in p digits.
2053
2054 Assumes that elimination of special cases has already been
2055 performed: self and other must both be nonspecial; self must
2056 be positive and not numerically equal to 1; other must be
2057 nonzero. For efficiency, other._exp should not be too large,
2058 so that 10**abs(other._exp) is a feasible calculation."""
2059
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002060 # In the comments below, we write x for the value of self and y for the
2061 # value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc
2062 # and yc positive integers not divisible by 10.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002063
2064 # The main purpose of this method is to identify the *failure*
2065 # of x**y to be exactly representable with as little effort as
2066 # possible. So we look for cheap and easy tests that
2067 # eliminate the possibility of x**y being exact. Only if all
2068 # these tests are passed do we go on to actually compute x**y.
2069
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002070 # Here's the main idea. Express y as a rational number m/n, with m and
2071 # n relatively prime and n>0. Then for x**y to be exactly
2072 # representable (at *any* precision), xc must be the nth power of a
2073 # positive integer and xe must be divisible by n. If y is negative
2074 # then additionally xc must be a power of either 2 or 5, hence a power
2075 # of 2**n or 5**n.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002076 #
2077 # There's a limit to how small |y| can be: if y=m/n as above
2078 # then:
2079 #
2080 # (1) if xc != 1 then for the result to be representable we
2081 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
2082 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
2083 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
2084 # representable.
2085 #
2086 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
2087 # |y| < 1/|xe| then the result is not representable.
2088 #
2089 # Note that since x is not equal to 1, at least one of (1) and
2090 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2091 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2092 #
2093 # There's also a limit to how large y can be, at least if it's
2094 # positive: the normalized result will have coefficient xc**y,
2095 # so if it's representable then xc**y < 10**p, and y <
2096 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
2097 # not exactly representable.
2098
2099 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2100 # so |y| < 1/xe and the result is not representable.
2101 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2102 # < 1/nbits(xc).
2103
2104 x = _WorkRep(self)
2105 xc, xe = x.int, x.exp
2106 while xc % 10 == 0:
2107 xc //= 10
2108 xe += 1
2109
2110 y = _WorkRep(other)
2111 yc, ye = y.int, y.exp
2112 while yc % 10 == 0:
2113 yc //= 10
2114 ye += 1
2115
2116 # case where xc == 1: result is 10**(xe*y), with xe*y
2117 # required to be an integer
2118 if xc == 1:
Mark Dickinsona1236312010-07-08 19:03:34 +00002119 xe *= yc
2120 # result is now 10**(xe * 10**ye); xe * 10**ye must be integral
2121 while xe % 10 == 0:
2122 xe //= 10
2123 ye += 1
2124 if ye < 0:
2125 return None
2126 exponent = xe * 10**ye
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002127 if y.sign == 1:
2128 exponent = -exponent
2129 # if other is a nonnegative integer, use ideal exponent
2130 if other._isinteger() and other._sign == 0:
2131 ideal_exponent = self._exp*int(other)
2132 zeros = min(exponent-ideal_exponent, p-1)
2133 else:
2134 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002135 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002136
2137 # case where y is negative: xc must be either a power
2138 # of 2 or a power of 5.
2139 if y.sign == 1:
2140 last_digit = xc % 10
2141 if last_digit in (2,4,6,8):
2142 # quick test for power of 2
2143 if xc & -xc != xc:
2144 return None
2145 # now xc is a power of 2; e is its exponent
2146 e = _nbits(xc)-1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002147
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002148 # We now have:
2149 #
2150 # x = 2**e * 10**xe, e > 0, and y < 0.
2151 #
2152 # The exact result is:
2153 #
2154 # x**y = 5**(-e*y) * 10**(e*y + xe*y)
2155 #
2156 # provided that both e*y and xe*y are integers. Note that if
2157 # 5**(-e*y) >= 10**p, then the result can't be expressed
2158 # exactly with p digits of precision.
2159 #
2160 # Using the above, we can guard against large values of ye.
2161 # 93/65 is an upper bound for log(10)/log(5), so if
2162 #
2163 # ye >= len(str(93*p//65))
2164 #
2165 # then
2166 #
2167 # -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5),
2168 #
2169 # so 5**(-e*y) >= 10**p, and the coefficient of the result
2170 # can't be expressed in p digits.
2171
2172 # emax >= largest e such that 5**e < 10**p.
2173 emax = p*93//65
2174 if ye >= len(str(emax)):
2175 return None
2176
2177 # Find -e*y and -xe*y; both must be integers
2178 e = _decimal_lshift_exact(e * yc, ye)
2179 xe = _decimal_lshift_exact(xe * yc, ye)
2180 if e is None or xe is None:
2181 return None
2182
2183 if e > emax:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002184 return None
2185 xc = 5**e
2186
2187 elif last_digit == 5:
2188 # e >= log_5(xc) if xc is a power of 5; we have
2189 # equality all the way up to xc=5**2658
2190 e = _nbits(xc)*28//65
2191 xc, remainder = divmod(5**e, xc)
2192 if remainder:
2193 return None
2194 while xc % 5 == 0:
2195 xc //= 5
2196 e -= 1
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01002197
2198 # Guard against large values of ye, using the same logic as in
2199 # the 'xc is a power of 2' branch. 10/3 is an upper bound for
2200 # log(10)/log(2).
2201 emax = p*10//3
2202 if ye >= len(str(emax)):
2203 return None
2204
2205 e = _decimal_lshift_exact(e * yc, ye)
2206 xe = _decimal_lshift_exact(xe * yc, ye)
2207 if e is None or xe is None:
2208 return None
2209
2210 if e > emax:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002211 return None
2212 xc = 2**e
2213 else:
2214 return None
2215
2216 if xc >= 10**p:
2217 return None
2218 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002219 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002220
2221 # now y is positive; find m and n such that y = m/n
2222 if ye >= 0:
2223 m, n = yc*10**ye, 1
2224 else:
2225 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2226 return None
2227 xc_bits = _nbits(xc)
2228 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2229 return None
2230 m, n = yc, 10**(-ye)
2231 while m % 2 == n % 2 == 0:
2232 m //= 2
2233 n //= 2
2234 while m % 5 == n % 5 == 0:
2235 m //= 5
2236 n //= 5
2237
2238 # compute nth root of xc*10**xe
2239 if n > 1:
2240 # if 1 < xc < 2**n then xc isn't an nth power
2241 if xc != 1 and xc_bits <= n:
2242 return None
2243
2244 xe, rem = divmod(xe, n)
2245 if rem != 0:
2246 return None
2247
2248 # compute nth root of xc using Newton's method
2249 a = 1 << -(-_nbits(xc)//n) # initial estimate
2250 while True:
2251 q, r = divmod(xc, a**(n-1))
2252 if a <= q:
2253 break
2254 else:
2255 a = (a*(n-1) + q)//n
2256 if not (a == q and r == 0):
2257 return None
2258 xc = a
2259
2260 # now xc*10**xe is the nth root of the original xc*10**xe
2261 # compute mth power of xc*10**xe
2262
2263 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2264 # 10**p and the result is not representable.
2265 if xc > 1 and m > p*100//_log10_lb(xc):
2266 return None
2267 xc = xc**m
2268 xe *= m
2269 if xc > 10**p:
2270 return None
2271
2272 # by this point the result *is* exactly representable
2273 # adjust the exponent to get as close as possible to the ideal
2274 # exponent, if necessary
2275 str_xc = str(xc)
2276 if other._isinteger() and other._sign == 0:
2277 ideal_exponent = self._exp*int(other)
2278 zeros = min(xe-ideal_exponent, p-len(str_xc))
2279 else:
2280 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002281 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002282
2283 def __pow__(self, other, modulo=None, context=None):
2284 """Return self ** other [ % modulo].
2285
2286 With two arguments, compute self**other.
2287
2288 With three arguments, compute (self**other) % modulo. For the
2289 three argument form, the following restrictions on the
2290 arguments hold:
2291
2292 - all three arguments must be integral
2293 - other must be nonnegative
2294 - either self or other (or both) must be nonzero
2295 - modulo must be nonzero and must have at most p digits,
2296 where p is the context precision.
2297
2298 If any of these restrictions is violated the InvalidOperation
2299 flag is raised.
2300
2301 The result of pow(self, other, modulo) is identical to the
2302 result that would be obtained by computing (self**other) %
2303 modulo with unbounded precision, but is computed more
2304 efficiently. It is always exact.
2305 """
2306
2307 if modulo is not None:
2308 return self._power_modulo(other, modulo, context)
2309
2310 other = _convert_other(other)
2311 if other is NotImplemented:
2312 return other
2313
2314 if context is None:
2315 context = getcontext()
2316
2317 # either argument is a NaN => result is NaN
2318 ans = self._check_nans(other, context)
2319 if ans:
2320 return ans
2321
2322 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2323 if not other:
2324 if not self:
2325 return context._raise_error(InvalidOperation, '0 ** 0')
2326 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002327 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002328
2329 # result has sign 1 iff self._sign is 1 and other is an odd integer
2330 result_sign = 0
2331 if self._sign == 1:
2332 if other._isinteger():
2333 if not other._iseven():
2334 result_sign = 1
2335 else:
2336 # -ve**noninteger = NaN
2337 # (-0)**noninteger = 0**noninteger
2338 if self:
2339 return context._raise_error(InvalidOperation,
2340 'x ** y with x negative and y not an integer')
2341 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002342 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002343
2344 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2345 if not self:
2346 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002347 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002348 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002349 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002350
2351 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002352 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002353 if other._sign == 0:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002354 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002355 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002356 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002357
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002358 # 1**other = 1, but the choice of exponent and the flags
2359 # depend on the exponent of self, and on whether other is a
2360 # positive integer, a negative integer, or neither
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002361 if self == _One:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002362 if other._isinteger():
2363 # exp = max(self._exp*max(int(other), 0),
2364 # 1-context.prec) but evaluating int(other) directly
2365 # is dangerous until we know other is small (other
2366 # could be 1e999999999)
2367 if other._sign == 1:
2368 multiplier = 0
2369 elif other > context.prec:
2370 multiplier = context.prec
2371 else:
2372 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002373
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002374 exp = self._exp * multiplier
2375 if exp < 1-context.prec:
2376 exp = 1-context.prec
2377 context._raise_error(Rounded)
2378 else:
2379 context._raise_error(Inexact)
2380 context._raise_error(Rounded)
2381 exp = 1-context.prec
2382
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002383 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002384
2385 # compute adjusted exponent of self
2386 self_adj = self.adjusted()
2387
2388 # self ** infinity is infinity if self > 1, 0 if self < 1
2389 # self ** -infinity is infinity if self < 1, 0 if self > 1
2390 if other._isinfinity():
2391 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002392 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002393 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002394 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002395
2396 # from here on, the result always goes through the call
2397 # to _fix at the end of this function.
2398 ans = None
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002399 exact = False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002400
2401 # crude test to catch cases of extreme overflow/underflow. If
2402 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2403 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2404 # self**other >= 10**(Emax+1), so overflow occurs. The test
2405 # for underflow is similar.
2406 bound = self._log10_exp_bound() + other.adjusted()
2407 if (self_adj >= 0) == (other._sign == 0):
2408 # self > 1 and other +ve, or self < 1 and other -ve
2409 # possibility of overflow
2410 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002411 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002412 else:
2413 # self > 1 and other -ve, or self < 1 and other +ve
2414 # possibility of underflow to 0
2415 Etiny = context.Etiny()
2416 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002417 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002418
2419 # try for an exact result with precision +1
2420 if ans is None:
2421 ans = self._power_exact(other, context.prec + 1)
Mark Dickinsone42f1bb2010-07-08 19:09:16 +00002422 if ans is not None:
2423 if result_sign == 1:
2424 ans = _dec_from_triple(1, ans._int, ans._exp)
2425 exact = True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002426
2427 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2428 if ans is None:
2429 p = context.prec
2430 x = _WorkRep(self)
2431 xc, xe = x.int, x.exp
2432 y = _WorkRep(other)
2433 yc, ye = y.int, y.exp
2434 if y.sign == 1:
2435 yc = -yc
2436
2437 # compute correctly rounded result: start with precision +3,
2438 # then increase precision until result is unambiguously roundable
2439 extra = 3
2440 while True:
2441 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2442 if coeff % (5*10**(len(str(coeff))-p-1)):
2443 break
2444 extra += 3
2445
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002446 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002447
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002448 # unlike exp, ln and log10, the power function respects the
2449 # rounding mode; no need to switch to ROUND_HALF_EVEN here
2450
2451 # There's a difficulty here when 'other' is not an integer and
2452 # the result is exact. In this case, the specification
2453 # requires that the Inexact flag be raised (in spite of
2454 # exactness), but since the result is exact _fix won't do this
2455 # for us. (Correspondingly, the Underflow signal should also
2456 # be raised for subnormal results.) We can't directly raise
2457 # these signals either before or after calling _fix, since
2458 # that would violate the precedence for signals. So we wrap
2459 # the ._fix call in a temporary context, and reraise
2460 # afterwards.
2461 if exact and not other._isinteger():
2462 # pad with zeros up to length context.prec+1 if necessary; this
2463 # ensures that the Rounded signal will be raised.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002464 if len(ans._int) <= context.prec:
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002465 expdiff = context.prec + 1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002466 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2467 ans._exp-expdiff)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002468
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002469 # create a copy of the current context, with cleared flags/traps
2470 newcontext = context.copy()
2471 newcontext.clear_flags()
2472 for exception in _signals:
2473 newcontext.traps[exception] = 0
2474
2475 # round in the new context
2476 ans = ans._fix(newcontext)
2477
2478 # raise Inexact, and if necessary, Underflow
2479 newcontext._raise_error(Inexact)
2480 if newcontext.flags[Subnormal]:
2481 newcontext._raise_error(Underflow)
2482
2483 # propagate signals to the original context; _fix could
2484 # have raised any of Overflow, Underflow, Subnormal,
2485 # Inexact, Rounded, Clamped. Overflow needs the correct
2486 # arguments. Note that the order of the exceptions is
2487 # important here.
2488 if newcontext.flags[Overflow]:
2489 context._raise_error(Overflow, 'above Emax', ans._sign)
2490 for exception in Underflow, Subnormal, Inexact, Rounded, Clamped:
2491 if newcontext.flags[exception]:
2492 context._raise_error(exception)
2493
2494 else:
2495 ans = ans._fix(context)
2496
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002497 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002498
2499 def __rpow__(self, other, context=None):
2500 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002501 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002502 if other is NotImplemented:
2503 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002504 return other.__pow__(self, context=context)
2505
2506 def normalize(self, context=None):
2507 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002508
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002509 if context is None:
2510 context = getcontext()
2511
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002512 if self._is_special:
2513 ans = self._check_nans(context=context)
2514 if ans:
2515 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002516
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002517 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002518 if dup._isinfinity():
2519 return dup
2520
2521 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002522 return _dec_from_triple(dup._sign, '0', 0)
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00002523 exp_max = [context.Emax, context.Etop()][context.clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002524 end = len(dup._int)
2525 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002526 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002527 exp += 1
2528 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002529 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002530
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002531 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002532 """Quantize self so its exponent is the same as that of exp.
2533
2534 Similar to self._rescale(exp._exp) but with error checking.
2535 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002536 exp = _convert_other(exp, raiseit=True)
2537
2538 if context is None:
2539 context = getcontext()
2540 if rounding is None:
2541 rounding = context.rounding
2542
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002543 if self._is_special or exp._is_special:
2544 ans = self._check_nans(exp, context)
2545 if ans:
2546 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002547
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002548 if exp._isinfinity() or self._isinfinity():
2549 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002550 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002551 return context._raise_error(InvalidOperation,
2552 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002553
2554 # if we're not watching exponents, do a simple rescale
2555 if not watchexp:
2556 ans = self._rescale(exp._exp, rounding)
2557 # raise Inexact and Rounded where appropriate
2558 if ans._exp > self._exp:
2559 context._raise_error(Rounded)
2560 if ans != self:
2561 context._raise_error(Inexact)
2562 return ans
2563
2564 # exp._exp should be between Etiny and Emax
2565 if not (context.Etiny() <= exp._exp <= context.Emax):
2566 return context._raise_error(InvalidOperation,
2567 'target exponent out of bounds in quantize')
2568
2569 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002570 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002571 return ans._fix(context)
2572
2573 self_adjusted = self.adjusted()
2574 if self_adjusted > context.Emax:
2575 return context._raise_error(InvalidOperation,
2576 'exponent of quantize result too large for current context')
2577 if self_adjusted - exp._exp + 1 > context.prec:
2578 return context._raise_error(InvalidOperation,
2579 'quantize result has too many digits for current context')
2580
2581 ans = self._rescale(exp._exp, rounding)
2582 if ans.adjusted() > context.Emax:
2583 return context._raise_error(InvalidOperation,
2584 'exponent of quantize result too large for current context')
2585 if len(ans._int) > context.prec:
2586 return context._raise_error(InvalidOperation,
2587 'quantize result has too many digits for current context')
2588
2589 # raise appropriate flags
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002590 if ans and ans.adjusted() < context.Emin:
2591 context._raise_error(Subnormal)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002592 if ans._exp > self._exp:
2593 if ans != self:
2594 context._raise_error(Inexact)
2595 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002596
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002597 # call to fix takes care of any necessary folddown, and
2598 # signals Clamped if necessary
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002599 ans = ans._fix(context)
2600 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002601
Stefan Krah040e3112012-12-15 22:33:33 +01002602 def same_quantum(self, other, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002603 """Return True if self and other have the same exponent; otherwise
2604 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002605
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002606 If either operand is a special value, the following rules are used:
2607 * return True if both operands are infinities
2608 * return True if both operands are NaNs
2609 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002610 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002611 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002612 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002613 return (self.is_nan() and other.is_nan() or
2614 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002615 return self._exp == other._exp
2616
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002617 def _rescale(self, exp, rounding):
2618 """Rescale self so that the exponent is exp, either by padding with zeros
2619 or by truncating digits, using the given rounding mode.
2620
2621 Specials are returned without change. This operation is
2622 quiet: it raises no flags, and uses no information from the
2623 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002624
2625 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002626 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002627 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002628 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002629 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002630 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002631 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002632
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002633 if self._exp >= exp:
2634 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002635 return _dec_from_triple(self._sign,
2636 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002637
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002638 # too many digits; round and lose data. If self.adjusted() <
2639 # exp-1, replace self by 10**(exp-1) before rounding
2640 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002641 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002642 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002643 digits = 0
Alexander Belopolsky1a20c122011-04-12 23:03:39 -04002644 this_function = self._pick_rounding_function[rounding]
2645 changed = this_function(self, digits)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002646 coeff = self._int[:digits] or '0'
2647 if changed == 1:
2648 coeff = str(int(coeff)+1)
2649 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002650
Christian Heimesf16baeb2008-02-29 14:57:44 +00002651 def _round(self, places, rounding):
2652 """Round a nonzero, nonspecial Decimal to a fixed number of
2653 significant figures, using the given rounding mode.
2654
2655 Infinities, NaNs and zeros are returned unaltered.
2656
2657 This operation is quiet: it raises no flags, and uses no
2658 information from the context.
2659
2660 """
2661 if places <= 0:
2662 raise ValueError("argument should be at least 1 in _round")
2663 if self._is_special or not self:
2664 return Decimal(self)
2665 ans = self._rescale(self.adjusted()+1-places, rounding)
2666 # it can happen that the rescale alters the adjusted exponent;
2667 # for example when rounding 99.97 to 3 significant figures.
2668 # When this happens we end up with an extra 0 at the end of
2669 # the number; a second rescale fixes this.
2670 if ans.adjusted() != self.adjusted():
2671 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2672 return ans
2673
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002674 def to_integral_exact(self, rounding=None, context=None):
2675 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002676
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002677 If no rounding mode is specified, take the rounding mode from
2678 the context. This method raises the Rounded and Inexact flags
2679 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002680
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002681 See also: to_integral_value, which does exactly the same as
2682 this method except that it doesn't raise Inexact or Rounded.
2683 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002684 if self._is_special:
2685 ans = self._check_nans(context=context)
2686 if ans:
2687 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002688 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002689 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002690 return Decimal(self)
2691 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002692 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002693 if context is None:
2694 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002695 if rounding is None:
2696 rounding = context.rounding
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002697 ans = self._rescale(0, rounding)
2698 if ans != self:
2699 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00002700 context._raise_error(Rounded)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002701 return ans
2702
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002703 def to_integral_value(self, rounding=None, context=None):
2704 """Rounds to the nearest integer, without raising inexact, rounded."""
2705 if context is None:
2706 context = getcontext()
2707 if rounding is None:
2708 rounding = context.rounding
2709 if self._is_special:
2710 ans = self._check_nans(context=context)
2711 if ans:
2712 return ans
2713 return Decimal(self)
2714 if self._exp >= 0:
2715 return Decimal(self)
2716 else:
2717 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002718
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002719 # the method name changed, but we provide also the old one, for compatibility
2720 to_integral = to_integral_value
2721
2722 def sqrt(self, context=None):
2723 """Return the square root of self."""
Christian Heimes0348fb62008-03-26 12:55:56 +00002724 if context is None:
2725 context = getcontext()
2726
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002727 if self._is_special:
2728 ans = self._check_nans(context=context)
2729 if ans:
2730 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002731
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002732 if self._isinfinity() and self._sign == 0:
2733 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002734
2735 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002736 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002737 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002738 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002739
2740 if self._sign == 1:
2741 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2742
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002743 # At this point self represents a positive number. Let p be
2744 # the desired precision and express self in the form c*100**e
2745 # with c a positive real number and e an integer, c and e
2746 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2747 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2748 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2749 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2750 # the closest integer to sqrt(c) with the even integer chosen
2751 # in the case of a tie.
2752 #
2753 # To ensure correct rounding in all cases, we use the
2754 # following trick: we compute the square root to an extra
2755 # place (precision p+1 instead of precision p), rounding down.
2756 # Then, if the result is inexact and its last digit is 0 or 5,
2757 # we increase the last digit to 1 or 6 respectively; if it's
2758 # exact we leave the last digit alone. Now the final round to
2759 # p places (or fewer in the case of underflow) will round
2760 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002761
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002762 # use an extra digit of precision
2763 prec = context.prec+1
2764
2765 # write argument in the form c*100**e where e = self._exp//2
2766 # is the 'ideal' exponent, to be used if the square root is
2767 # exactly representable. l is the number of 'digits' of c in
2768 # base 100, so that 100**(l-1) <= c < 100**l.
2769 op = _WorkRep(self)
2770 e = op.exp >> 1
2771 if op.exp & 1:
2772 c = op.int * 10
2773 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002774 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002775 c = op.int
2776 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002777
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002778 # rescale so that c has exactly prec base 100 'digits'
2779 shift = prec-l
2780 if shift >= 0:
2781 c *= 100**shift
2782 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002783 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002784 c, remainder = divmod(c, 100**-shift)
2785 exact = not remainder
2786 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002787
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002788 # find n = floor(sqrt(c)) using Newton's method
2789 n = 10**prec
2790 while True:
2791 q = c//n
2792 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002793 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002794 else:
2795 n = n + q >> 1
2796 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002797
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002798 if exact:
2799 # result is exact; rescale to use ideal exponent e
2800 if shift >= 0:
2801 # assert n % 10**shift == 0
2802 n //= 10**shift
2803 else:
2804 n *= 10**-shift
2805 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002806 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002807 # result is not exact; fix last digit as described above
2808 if n % 5 == 0:
2809 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002810
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002811 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002812
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002813 # round, and fit to current context
2814 context = context._shallow_copy()
2815 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002816 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002817 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002818
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002819 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002820
2821 def max(self, other, context=None):
2822 """Returns the larger value.
2823
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002824 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002825 NaN (and signals if one is sNaN). Also rounds.
2826 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002827 other = _convert_other(other, raiseit=True)
2828
2829 if context is None:
2830 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002831
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002832 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002833 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002834 # number is always returned
2835 sn = self._isnan()
2836 on = other._isnan()
2837 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002838 if on == 1 and sn == 0:
2839 return self._fix(context)
2840 if sn == 1 and on == 0:
2841 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002842 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002843
Christian Heimes77c02eb2008-02-09 02:18:51 +00002844 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002845 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002846 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002847 # then an ordering is applied:
2848 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002849 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002850 # positive sign and min returns the operand with the negative sign
2851 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002852 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002853 # the result. This is exactly the ordering used in compare_total.
2854 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002855
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002856 if c == -1:
2857 ans = other
2858 else:
2859 ans = self
2860
Christian Heimes2c181612007-12-17 20:04:13 +00002861 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002862
2863 def min(self, other, context=None):
2864 """Returns the smaller value.
2865
Guido van Rossumd8faa362007-04-27 19:54:29 +00002866 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002867 NaN (and signals if one is sNaN). Also rounds.
2868 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002869 other = _convert_other(other, raiseit=True)
2870
2871 if context is None:
2872 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002873
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002874 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002875 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002876 # number is always returned
2877 sn = self._isnan()
2878 on = other._isnan()
2879 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002880 if on == 1 and sn == 0:
2881 return self._fix(context)
2882 if sn == 1 and on == 0:
2883 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002884 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002885
Christian Heimes77c02eb2008-02-09 02:18:51 +00002886 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002887 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002888 c = self.compare_total(other)
2889
2890 if c == -1:
2891 ans = self
2892 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002893 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002894
Christian Heimes2c181612007-12-17 20:04:13 +00002895 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002896
2897 def _isinteger(self):
2898 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002899 if self._is_special:
2900 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002901 if self._exp >= 0:
2902 return True
2903 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002904 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002905
2906 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002907 """Returns True if self is even. Assumes self is an integer."""
2908 if not self or self._exp > 0:
2909 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002910 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002911
2912 def adjusted(self):
2913 """Return the adjusted exponent of self"""
2914 try:
2915 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002916 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002917 except TypeError:
2918 return 0
2919
Stefan Krah040e3112012-12-15 22:33:33 +01002920 def canonical(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002921 """Returns the same Decimal object.
2922
2923 As we do not have different encodings for the same number, the
2924 received object already is in its canonical form.
2925 """
2926 return self
2927
2928 def compare_signal(self, other, context=None):
2929 """Compares self to the other operand numerically.
2930
2931 It's pretty much like compare(), but all NaNs signal, with signaling
2932 NaNs taking precedence over quiet NaNs.
2933 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002934 other = _convert_other(other, raiseit = True)
2935 ans = self._compare_check_nans(other, context)
2936 if ans:
2937 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002938 return self.compare(other, context=context)
2939
Stefan Krah040e3112012-12-15 22:33:33 +01002940 def compare_total(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002941 """Compares self to other using the abstract representations.
2942
2943 This is not like the standard compare, which use their numerical
2944 value. Note that a total ordering is defined for all possible abstract
2945 representations.
2946 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00002947 other = _convert_other(other, raiseit=True)
2948
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002949 # if one is negative and the other is positive, it's easy
2950 if self._sign and not other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002951 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002952 if not self._sign and other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002953 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002954 sign = self._sign
2955
2956 # let's handle both NaN types
2957 self_nan = self._isnan()
2958 other_nan = other._isnan()
2959 if self_nan or other_nan:
2960 if self_nan == other_nan:
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002961 # compare payloads as though they're integers
2962 self_key = len(self._int), self._int
2963 other_key = len(other._int), other._int
2964 if self_key < other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002965 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002966 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002967 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002968 return _NegativeOne
Mark Dickinsond314e1b2009-08-28 13:39:53 +00002969 if self_key > other_key:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002970 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002971 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002972 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002973 return _One
2974 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002975
2976 if sign:
2977 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002978 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002979 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002980 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002981 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002982 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002983 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002984 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002985 else:
2986 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002987 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002988 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002989 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002990 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002991 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002992 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002993 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002994
2995 if self < other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002996 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002997 if self > other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002998 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002999
3000 if self._exp < other._exp:
3001 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003002 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003003 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003004 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003005 if self._exp > other._exp:
3006 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003007 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003008 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003009 return _One
3010 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003011
3012
Stefan Krah040e3112012-12-15 22:33:33 +01003013 def compare_total_mag(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003014 """Compares self to other using abstract repr., ignoring sign.
3015
3016 Like compare_total, but with operand's sign ignored and assumed to be 0.
3017 """
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003018 other = _convert_other(other, raiseit=True)
3019
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003020 s = self.copy_abs()
3021 o = other.copy_abs()
3022 return s.compare_total(o)
3023
3024 def copy_abs(self):
3025 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003026 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003027
3028 def copy_negate(self):
3029 """Returns a copy with the sign inverted."""
3030 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003031 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003032 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003033 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003034
Stefan Krah040e3112012-12-15 22:33:33 +01003035 def copy_sign(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003036 """Returns self with the sign of other."""
Mark Dickinson84230a12010-02-18 14:49:50 +00003037 other = _convert_other(other, raiseit=True)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003038 return _dec_from_triple(other._sign, self._int,
3039 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003040
3041 def exp(self, context=None):
3042 """Returns e ** self."""
3043
3044 if context is None:
3045 context = getcontext()
3046
3047 # exp(NaN) = NaN
3048 ans = self._check_nans(context=context)
3049 if ans:
3050 return ans
3051
3052 # exp(-Infinity) = 0
3053 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003054 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003055
3056 # exp(0) = 1
3057 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003058 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003059
3060 # exp(Infinity) = Infinity
3061 if self._isinfinity() == 1:
3062 return Decimal(self)
3063
3064 # the result is now guaranteed to be inexact (the true
3065 # mathematical result is transcendental). There's no need to
3066 # raise Rounded and Inexact here---they'll always be raised as
3067 # a result of the call to _fix.
3068 p = context.prec
3069 adj = self.adjusted()
3070
3071 # we only need to do any computation for quite a small range
3072 # of adjusted exponents---for example, -29 <= adj <= 10 for
3073 # the default context. For smaller exponent the result is
3074 # indistinguishable from 1 at the given precision, while for
3075 # larger exponent the result either overflows or underflows.
3076 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
3077 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003078 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003079 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
3080 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003081 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003082 elif self._sign == 0 and adj < -p:
3083 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003084 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003085 elif self._sign == 1 and adj < -p-1:
3086 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003087 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003088 # general case
3089 else:
3090 op = _WorkRep(self)
3091 c, e = op.int, op.exp
3092 if op.sign == 1:
3093 c = -c
3094
3095 # compute correctly rounded result: increase precision by
3096 # 3 digits at a time until we get an unambiguously
3097 # roundable result
3098 extra = 3
3099 while True:
3100 coeff, exp = _dexp(c, e, p+extra)
3101 if coeff % (5*10**(len(str(coeff))-p-1)):
3102 break
3103 extra += 3
3104
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003105 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003106
3107 # at this stage, ans should round correctly with *any*
3108 # rounding mode, not just with ROUND_HALF_EVEN
3109 context = context._shallow_copy()
3110 rounding = context._set_rounding(ROUND_HALF_EVEN)
3111 ans = ans._fix(context)
3112 context.rounding = rounding
3113
3114 return ans
3115
3116 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003117 """Return True if self is canonical; otherwise return False.
3118
3119 Currently, the encoding of a Decimal instance is always
3120 canonical, so this method returns True for any Decimal.
3121 """
3122 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003123
3124 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003125 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003126
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003127 A Decimal instance is considered finite if it is neither
3128 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003129 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003130 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003131
3132 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003133 """Return True if self is infinite; otherwise return False."""
3134 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003135
3136 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003137 """Return True if self is a qNaN or sNaN; otherwise return False."""
3138 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003139
3140 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003141 """Return True if self is a normal number; otherwise return False."""
3142 if self._is_special or not self:
3143 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003144 if context is None:
3145 context = getcontext()
Mark Dickinson06bb6742009-10-20 13:38:04 +00003146 return context.Emin <= self.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003147
3148 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003149 """Return True if self is a quiet NaN; otherwise return False."""
3150 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003151
3152 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003153 """Return True if self is negative; otherwise return False."""
3154 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003155
3156 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003157 """Return True if self is a signaling NaN; otherwise return False."""
3158 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003159
3160 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003161 """Return True if self is subnormal; otherwise return False."""
3162 if self._is_special or not self:
3163 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003164 if context is None:
3165 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003166 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003167
3168 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003169 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003170 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003171
3172 def _ln_exp_bound(self):
3173 """Compute a lower bound for the adjusted exponent of self.ln().
3174 In other words, compute r such that self.ln() >= 10**r. Assumes
3175 that self is finite and positive and that self != 1.
3176 """
3177
3178 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
3179 adj = self._exp + len(self._int) - 1
3180 if adj >= 1:
3181 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
3182 return len(str(adj*23//10)) - 1
3183 if adj <= -2:
3184 # argument <= 0.1
3185 return len(str((-1-adj)*23//10)) - 1
3186 op = _WorkRep(self)
3187 c, e = op.int, op.exp
3188 if adj == 0:
3189 # 1 < self < 10
3190 num = str(c-10**-e)
3191 den = str(c)
3192 return len(num) - len(den) - (num < den)
3193 # adj == -1, 0.1 <= self < 1
3194 return e + len(str(10**-e - c)) - 1
3195
3196
3197 def ln(self, context=None):
3198 """Returns the natural (base e) logarithm of self."""
3199
3200 if context is None:
3201 context = getcontext()
3202
3203 # ln(NaN) = NaN
3204 ans = self._check_nans(context=context)
3205 if ans:
3206 return ans
3207
3208 # ln(0.0) == -Infinity
3209 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003210 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003211
3212 # ln(Infinity) = Infinity
3213 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003214 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003215
3216 # ln(1.0) == 0.0
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003217 if self == _One:
3218 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003219
3220 # ln(negative) raises InvalidOperation
3221 if self._sign == 1:
3222 return context._raise_error(InvalidOperation,
3223 'ln of a negative value')
3224
3225 # result is irrational, so necessarily inexact
3226 op = _WorkRep(self)
3227 c, e = op.int, op.exp
3228 p = context.prec
3229
3230 # correctly rounded result: repeatedly increase precision by 3
3231 # until we get an unambiguously roundable result
3232 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3233 while True:
3234 coeff = _dlog(c, e, places)
3235 # assert len(str(abs(coeff)))-p >= 1
3236 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3237 break
3238 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003239 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003240
3241 context = context._shallow_copy()
3242 rounding = context._set_rounding(ROUND_HALF_EVEN)
3243 ans = ans._fix(context)
3244 context.rounding = rounding
3245 return ans
3246
3247 def _log10_exp_bound(self):
3248 """Compute a lower bound for the adjusted exponent of self.log10().
3249 In other words, find r such that self.log10() >= 10**r.
3250 Assumes that self is finite and positive and that self != 1.
3251 """
3252
3253 # For x >= 10 or x < 0.1 we only need a bound on the integer
3254 # part of log10(self), and this comes directly from the
3255 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3256 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3257 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3258
3259 adj = self._exp + len(self._int) - 1
3260 if adj >= 1:
3261 # self >= 10
3262 return len(str(adj))-1
3263 if adj <= -2:
3264 # self < 0.1
3265 return len(str(-1-adj))-1
3266 op = _WorkRep(self)
3267 c, e = op.int, op.exp
3268 if adj == 0:
3269 # 1 < self < 10
3270 num = str(c-10**-e)
3271 den = str(231*c)
3272 return len(num) - len(den) - (num < den) + 2
3273 # adj == -1, 0.1 <= self < 1
3274 num = str(10**-e-c)
3275 return len(num) + e - (num < "231") - 1
3276
3277 def log10(self, context=None):
3278 """Returns the base 10 logarithm of self."""
3279
3280 if context is None:
3281 context = getcontext()
3282
3283 # log10(NaN) = NaN
3284 ans = self._check_nans(context=context)
3285 if ans:
3286 return ans
3287
3288 # log10(0.0) == -Infinity
3289 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003290 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003291
3292 # log10(Infinity) = Infinity
3293 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003294 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003295
3296 # log10(negative or -Infinity) raises InvalidOperation
3297 if self._sign == 1:
3298 return context._raise_error(InvalidOperation,
3299 'log10 of a negative value')
3300
3301 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003302 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003303 # answer may need rounding
3304 ans = Decimal(self._exp + len(self._int) - 1)
3305 else:
3306 # result is irrational, so necessarily inexact
3307 op = _WorkRep(self)
3308 c, e = op.int, op.exp
3309 p = context.prec
3310
3311 # correctly rounded result: repeatedly increase precision
3312 # until result is unambiguously roundable
3313 places = p-self._log10_exp_bound()+2
3314 while True:
3315 coeff = _dlog10(c, e, places)
3316 # assert len(str(abs(coeff)))-p >= 1
3317 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3318 break
3319 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003320 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003321
3322 context = context._shallow_copy()
3323 rounding = context._set_rounding(ROUND_HALF_EVEN)
3324 ans = ans._fix(context)
3325 context.rounding = rounding
3326 return ans
3327
3328 def logb(self, context=None):
3329 """ Returns the exponent of the magnitude of self's MSD.
3330
3331 The result is the integer which is the exponent of the magnitude
3332 of the most significant digit of self (as though it were truncated
3333 to a single digit while maintaining the value of that digit and
3334 without limiting the resulting exponent).
3335 """
3336 # logb(NaN) = NaN
3337 ans = self._check_nans(context=context)
3338 if ans:
3339 return ans
3340
3341 if context is None:
3342 context = getcontext()
3343
3344 # logb(+/-Inf) = +Inf
3345 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003346 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003347
3348 # logb(0) = -Inf, DivisionByZero
3349 if not self:
3350 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3351
3352 # otherwise, simply return the adjusted exponent of self, as a
3353 # Decimal. Note that no attempt is made to fit the result
3354 # into the current context.
Mark Dickinson56df8872009-10-07 19:23:50 +00003355 ans = Decimal(self.adjusted())
3356 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003357
3358 def _islogical(self):
3359 """Return True if self is a logical operand.
3360
Christian Heimes679db4a2008-01-18 09:56:22 +00003361 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003362 an exponent of 0, and a coefficient whose digits must all be
3363 either 0 or 1.
3364 """
3365 if self._sign != 0 or self._exp != 0:
3366 return False
3367 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003368 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003369 return False
3370 return True
3371
3372 def _fill_logical(self, context, opa, opb):
3373 dif = context.prec - len(opa)
3374 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003375 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003376 elif dif < 0:
3377 opa = opa[-context.prec:]
3378 dif = context.prec - len(opb)
3379 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003380 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003381 elif dif < 0:
3382 opb = opb[-context.prec:]
3383 return opa, opb
3384
3385 def logical_and(self, other, context=None):
3386 """Applies an 'and' operation between self and other's digits."""
3387 if context is None:
3388 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003389
3390 other = _convert_other(other, raiseit=True)
3391
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003392 if not self._islogical() or not other._islogical():
3393 return context._raise_error(InvalidOperation)
3394
3395 # fill to context.prec
3396 (opa, opb) = self._fill_logical(context, self._int, other._int)
3397
3398 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003399 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3400 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003401
3402 def logical_invert(self, context=None):
3403 """Invert all its digits."""
3404 if context is None:
3405 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003406 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3407 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003408
3409 def logical_or(self, other, context=None):
3410 """Applies an 'or' operation between self and other's digits."""
3411 if context is None:
3412 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003413
3414 other = _convert_other(other, raiseit=True)
3415
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003416 if not self._islogical() or not other._islogical():
3417 return context._raise_error(InvalidOperation)
3418
3419 # fill to context.prec
3420 (opa, opb) = self._fill_logical(context, self._int, other._int)
3421
3422 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003423 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003424 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003425
3426 def logical_xor(self, other, context=None):
3427 """Applies an 'xor' operation between self and other's digits."""
3428 if context is None:
3429 context = getcontext()
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003430
3431 other = _convert_other(other, raiseit=True)
3432
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003433 if not self._islogical() or not other._islogical():
3434 return context._raise_error(InvalidOperation)
3435
3436 # fill to context.prec
3437 (opa, opb) = self._fill_logical(context, self._int, other._int)
3438
3439 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003440 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003441 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003442
3443 def max_mag(self, other, context=None):
3444 """Compares the values numerically with their sign ignored."""
3445 other = _convert_other(other, raiseit=True)
3446
3447 if context is None:
3448 context = getcontext()
3449
3450 if self._is_special or other._is_special:
3451 # If one operand is a quiet NaN and the other is number, then the
3452 # number is always returned
3453 sn = self._isnan()
3454 on = other._isnan()
3455 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003456 if on == 1 and sn == 0:
3457 return self._fix(context)
3458 if sn == 1 and on == 0:
3459 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003460 return self._check_nans(other, context)
3461
Christian Heimes77c02eb2008-02-09 02:18:51 +00003462 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003463 if c == 0:
3464 c = self.compare_total(other)
3465
3466 if c == -1:
3467 ans = other
3468 else:
3469 ans = self
3470
Christian Heimes2c181612007-12-17 20:04:13 +00003471 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003472
3473 def min_mag(self, other, context=None):
3474 """Compares the values numerically with their sign ignored."""
3475 other = _convert_other(other, raiseit=True)
3476
3477 if context is None:
3478 context = getcontext()
3479
3480 if self._is_special or other._is_special:
3481 # If one operand is a quiet NaN and the other is number, then the
3482 # number is always returned
3483 sn = self._isnan()
3484 on = other._isnan()
3485 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003486 if on == 1 and sn == 0:
3487 return self._fix(context)
3488 if sn == 1 and on == 0:
3489 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003490 return self._check_nans(other, context)
3491
Christian Heimes77c02eb2008-02-09 02:18:51 +00003492 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003493 if c == 0:
3494 c = self.compare_total(other)
3495
3496 if c == -1:
3497 ans = self
3498 else:
3499 ans = other
3500
Christian Heimes2c181612007-12-17 20:04:13 +00003501 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003502
3503 def next_minus(self, context=None):
3504 """Returns the largest representable number smaller than itself."""
3505 if context is None:
3506 context = getcontext()
3507
3508 ans = self._check_nans(context=context)
3509 if ans:
3510 return ans
3511
3512 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003513 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003514 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003515 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003516
3517 context = context.copy()
3518 context._set_rounding(ROUND_FLOOR)
3519 context._ignore_all_flags()
3520 new_self = self._fix(context)
3521 if new_self != self:
3522 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003523 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3524 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003525
3526 def next_plus(self, context=None):
3527 """Returns the smallest representable number larger than itself."""
3528 if context is None:
3529 context = getcontext()
3530
3531 ans = self._check_nans(context=context)
3532 if ans:
3533 return ans
3534
3535 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003536 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003537 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003538 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003539
3540 context = context.copy()
3541 context._set_rounding(ROUND_CEILING)
3542 context._ignore_all_flags()
3543 new_self = self._fix(context)
3544 if new_self != self:
3545 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003546 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3547 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003548
3549 def next_toward(self, other, context=None):
3550 """Returns the number closest to self, in the direction towards other.
3551
3552 The result is the closest representable number to self
3553 (excluding self) that is in the direction towards other,
3554 unless both have the same value. If the two operands are
3555 numerically equal, then the result is a copy of self with the
3556 sign set to be the same as the sign of other.
3557 """
3558 other = _convert_other(other, raiseit=True)
3559
3560 if context is None:
3561 context = getcontext()
3562
3563 ans = self._check_nans(other, context)
3564 if ans:
3565 return ans
3566
Christian Heimes77c02eb2008-02-09 02:18:51 +00003567 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003568 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003569 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003570
3571 if comparison == -1:
3572 ans = self.next_plus(context)
3573 else: # comparison == 1
3574 ans = self.next_minus(context)
3575
3576 # decide which flags to raise using value of ans
3577 if ans._isinfinity():
3578 context._raise_error(Overflow,
3579 'Infinite result from next_toward',
3580 ans._sign)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003581 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00003582 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003583 elif ans.adjusted() < context.Emin:
3584 context._raise_error(Underflow)
3585 context._raise_error(Subnormal)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003586 context._raise_error(Inexact)
Mark Dickinsonc69160e2010-05-04 14:35:33 +00003587 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003588 # if precision == 1 then we don't raise Clamped for a
3589 # result 0E-Etiny.
3590 if not ans:
3591 context._raise_error(Clamped)
3592
3593 return ans
3594
3595 def number_class(self, context=None):
3596 """Returns an indication of the class of self.
3597
3598 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003599 sNaN
3600 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003601 -Infinity
3602 -Normal
3603 -Subnormal
3604 -Zero
3605 +Zero
3606 +Subnormal
3607 +Normal
3608 +Infinity
3609 """
3610 if self.is_snan():
3611 return "sNaN"
3612 if self.is_qnan():
3613 return "NaN"
3614 inf = self._isinfinity()
3615 if inf == 1:
3616 return "+Infinity"
3617 if inf == -1:
3618 return "-Infinity"
3619 if self.is_zero():
3620 if self._sign:
3621 return "-Zero"
3622 else:
3623 return "+Zero"
3624 if context is None:
3625 context = getcontext()
3626 if self.is_subnormal(context=context):
3627 if self._sign:
3628 return "-Subnormal"
3629 else:
3630 return "+Subnormal"
3631 # just a normal, regular, boring number, :)
3632 if self._sign:
3633 return "-Normal"
3634 else:
3635 return "+Normal"
3636
3637 def radix(self):
3638 """Just returns 10, as this is Decimal, :)"""
3639 return Decimal(10)
3640
3641 def rotate(self, other, context=None):
3642 """Returns a rotated copy of self, value-of-other times."""
3643 if context is None:
3644 context = getcontext()
3645
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003646 other = _convert_other(other, raiseit=True)
3647
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003648 ans = self._check_nans(other, context)
3649 if ans:
3650 return ans
3651
3652 if other._exp != 0:
3653 return context._raise_error(InvalidOperation)
3654 if not (-context.prec <= int(other) <= context.prec):
3655 return context._raise_error(InvalidOperation)
3656
3657 if self._isinfinity():
3658 return Decimal(self)
3659
3660 # get values, pad if necessary
3661 torot = int(other)
3662 rotdig = self._int
3663 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003664 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003665 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003666 elif topad < 0:
3667 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003668
3669 # let's rotate!
3670 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003671 return _dec_from_triple(self._sign,
3672 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003673
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003674 def scaleb(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003675 """Returns self operand after adding the second value to its exp."""
3676 if context is None:
3677 context = getcontext()
3678
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003679 other = _convert_other(other, raiseit=True)
3680
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003681 ans = self._check_nans(other, context)
3682 if ans:
3683 return ans
3684
3685 if other._exp != 0:
3686 return context._raise_error(InvalidOperation)
3687 liminf = -2 * (context.Emax + context.prec)
3688 limsup = 2 * (context.Emax + context.prec)
3689 if not (liminf <= int(other) <= limsup):
3690 return context._raise_error(InvalidOperation)
3691
3692 if self._isinfinity():
3693 return Decimal(self)
3694
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003695 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003696 d = d._fix(context)
3697 return d
3698
3699 def shift(self, other, context=None):
3700 """Returns a shifted copy of self, value-of-other times."""
3701 if context is None:
3702 context = getcontext()
3703
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003704 other = _convert_other(other, raiseit=True)
3705
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003706 ans = self._check_nans(other, context)
3707 if ans:
3708 return ans
3709
3710 if other._exp != 0:
3711 return context._raise_error(InvalidOperation)
3712 if not (-context.prec <= int(other) <= context.prec):
3713 return context._raise_error(InvalidOperation)
3714
3715 if self._isinfinity():
3716 return Decimal(self)
3717
3718 # get values, pad if necessary
3719 torot = int(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003720 rotdig = self._int
3721 topad = context.prec - len(rotdig)
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003722 if topad > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003723 rotdig = '0'*topad + rotdig
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003724 elif topad < 0:
3725 rotdig = rotdig[-topad:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003726
3727 # let's shift!
3728 if torot < 0:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003729 shifted = rotdig[:torot]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003730 else:
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003731 shifted = rotdig + '0'*torot
3732 shifted = shifted[-context.prec:]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003733
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003734 return _dec_from_triple(self._sign,
Mark Dickinsona2d1fe02009-10-29 12:23:02 +00003735 shifted.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003736
Guido van Rossumd8faa362007-04-27 19:54:29 +00003737 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003738 def __reduce__(self):
3739 return (self.__class__, (str(self),))
3740
3741 def __copy__(self):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003742 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003743 return self # I'm immutable; therefore I am my own clone
3744 return self.__class__(str(self))
3745
3746 def __deepcopy__(self, memo):
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00003747 if type(self) is Decimal:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003748 return self # My components are also immutable
3749 return self.__class__(str(self))
3750
Mark Dickinson79f52032009-03-17 23:12:51 +00003751 # PEP 3101 support. the _localeconv keyword argument should be
3752 # considered private: it's provided for ease of testing only.
3753 def __format__(self, specifier, context=None, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00003754 """Format a Decimal instance according to the given specifier.
3755
3756 The specifier should be a standard format specifier, with the
3757 form described in PEP 3101. Formatting types 'e', 'E', 'f',
Mark Dickinson79f52032009-03-17 23:12:51 +00003758 'F', 'g', 'G', 'n' and '%' are supported. If the formatting
3759 type is omitted it defaults to 'g' or 'G', depending on the
3760 value of context.capitals.
Christian Heimesf16baeb2008-02-29 14:57:44 +00003761 """
3762
3763 # Note: PEP 3101 says that if the type is not present then
3764 # there should be at least one digit after the decimal point.
3765 # We take the liberty of ignoring this requirement for
3766 # Decimal---it's presumably there to make sure that
3767 # format(float, '') behaves similarly to str(float).
3768 if context is None:
3769 context = getcontext()
3770
Mark Dickinson79f52032009-03-17 23:12:51 +00003771 spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003772
Mark Dickinson79f52032009-03-17 23:12:51 +00003773 # special values don't care about the type or precision
Christian Heimesf16baeb2008-02-29 14:57:44 +00003774 if self._is_special:
Mark Dickinson79f52032009-03-17 23:12:51 +00003775 sign = _format_sign(self._sign, spec)
3776 body = str(self.copy_abs())
Stefan Krah298131a2014-08-26 20:46:49 +02003777 if spec['type'] == '%':
3778 body += '%'
Mark Dickinson79f52032009-03-17 23:12:51 +00003779 return _format_align(sign, body, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003780
3781 # a type of None defaults to 'g' or 'G', depending on context
Christian Heimesf16baeb2008-02-29 14:57:44 +00003782 if spec['type'] is None:
3783 spec['type'] = ['g', 'G'][context.capitals]
Mark Dickinson79f52032009-03-17 23:12:51 +00003784
3785 # if type is '%', adjust exponent of self accordingly
3786 if spec['type'] == '%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003787 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3788
3789 # round if necessary, taking rounding mode from the context
3790 rounding = context.rounding
3791 precision = spec['precision']
3792 if precision is not None:
3793 if spec['type'] in 'eE':
3794 self = self._round(precision+1, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003795 elif spec['type'] in 'fF%':
3796 self = self._rescale(-precision, rounding)
Mark Dickinson79f52032009-03-17 23:12:51 +00003797 elif spec['type'] in 'gG' and len(self._int) > precision:
3798 self = self._round(precision, rounding)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003799 # special case: zeros with a positive exponent can't be
3800 # represented in fixed point; rescale them to 0e0.
Mark Dickinson79f52032009-03-17 23:12:51 +00003801 if not self and self._exp > 0 and spec['type'] in 'fF%':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003802 self = self._rescale(0, rounding)
3803
3804 # figure out placement of the decimal point
3805 leftdigits = self._exp + len(self._int)
Mark Dickinson79f52032009-03-17 23:12:51 +00003806 if spec['type'] in 'eE':
Christian Heimesf16baeb2008-02-29 14:57:44 +00003807 if not self and precision is not None:
3808 dotplace = 1 - precision
3809 else:
3810 dotplace = 1
Mark Dickinson79f52032009-03-17 23:12:51 +00003811 elif spec['type'] in 'fF%':
3812 dotplace = leftdigits
Christian Heimesf16baeb2008-02-29 14:57:44 +00003813 elif spec['type'] in 'gG':
3814 if self._exp <= 0 and leftdigits > -6:
3815 dotplace = leftdigits
3816 else:
3817 dotplace = 1
3818
Mark Dickinson79f52032009-03-17 23:12:51 +00003819 # find digits before and after decimal point, and get exponent
3820 if dotplace < 0:
3821 intpart = '0'
3822 fracpart = '0'*(-dotplace) + self._int
3823 elif dotplace > len(self._int):
3824 intpart = self._int + '0'*(dotplace-len(self._int))
3825 fracpart = ''
Christian Heimesf16baeb2008-02-29 14:57:44 +00003826 else:
Mark Dickinson79f52032009-03-17 23:12:51 +00003827 intpart = self._int[:dotplace] or '0'
3828 fracpart = self._int[dotplace:]
3829 exp = leftdigits-dotplace
Christian Heimesf16baeb2008-02-29 14:57:44 +00003830
Mark Dickinson79f52032009-03-17 23:12:51 +00003831 # done with the decimal-specific stuff; hand over the rest
3832 # of the formatting to the _format_number function
3833 return _format_number(self._sign, intpart, fracpart, exp, spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00003834
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003835def _dec_from_triple(sign, coefficient, exponent, special=False):
3836 """Create a decimal instance directly, without any validation,
3837 normalization (e.g. removal of leading zeros) or argument
3838 conversion.
3839
3840 This function is for *internal use only*.
3841 """
3842
3843 self = object.__new__(Decimal)
3844 self._sign = sign
3845 self._int = coefficient
3846 self._exp = exponent
3847 self._is_special = special
3848
3849 return self
3850
Raymond Hettinger82417ca2009-02-03 03:54:28 +00003851# Register Decimal as a kind of Number (an abstract base class).
3852# However, do not register it as Real (because Decimals are not
3853# interoperable with floats).
3854_numbers.Number.register(Decimal)
3855
3856
Guido van Rossumd8faa362007-04-27 19:54:29 +00003857##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003858
Thomas Wouters89f507f2006-12-13 04:49:30 +00003859class _ContextManager(object):
3860 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003861
Thomas Wouters89f507f2006-12-13 04:49:30 +00003862 Sets a copy of the supplied context in __enter__() and restores
3863 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003864 """
3865 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003866 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003867 def __enter__(self):
3868 self.saved_context = getcontext()
3869 setcontext(self.new_context)
3870 return self.new_context
3871 def __exit__(self, t, v, tb):
3872 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003873
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003874class Context(object):
3875 """Contains the context for a Decimal instance.
3876
3877 Contains:
3878 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003879 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003880 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003881 raised when it is caused. Otherwise, a value is
3882 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003883 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003884 (Whether or not the trap_enabler is set)
3885 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003886 Emin - Minimum exponent
3887 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003888 capitals - If 1, 1*10^1 is printed as 1E+1.
3889 If 0, printed as 1e1
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00003890 clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003891 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003892
Stefan Krah1919b7e2012-03-21 18:25:23 +01003893 def __init__(self, prec=None, rounding=None, Emin=None, Emax=None,
3894 capitals=None, clamp=None, flags=None, traps=None,
3895 _ignored_flags=None):
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003896 # Set defaults; for everything except flags and _ignored_flags,
3897 # inherit from DefaultContext.
3898 try:
3899 dc = DefaultContext
3900 except NameError:
3901 pass
3902
3903 self.prec = prec if prec is not None else dc.prec
3904 self.rounding = rounding if rounding is not None else dc.rounding
3905 self.Emin = Emin if Emin is not None else dc.Emin
3906 self.Emax = Emax if Emax is not None else dc.Emax
3907 self.capitals = capitals if capitals is not None else dc.capitals
3908 self.clamp = clamp if clamp is not None else dc.clamp
3909
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003910 if _ignored_flags is None:
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003911 self._ignored_flags = []
3912 else:
3913 self._ignored_flags = _ignored_flags
3914
3915 if traps is None:
3916 self.traps = dc.traps.copy()
3917 elif not isinstance(traps, dict):
Stefan Krah1919b7e2012-03-21 18:25:23 +01003918 self.traps = dict((s, int(s in traps)) for s in _signals + traps)
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003919 else:
3920 self.traps = traps
3921
3922 if flags is None:
3923 self.flags = dict.fromkeys(_signals, 0)
3924 elif not isinstance(flags, dict):
Stefan Krah1919b7e2012-03-21 18:25:23 +01003925 self.flags = dict((s, int(s in flags)) for s in _signals + flags)
Mark Dickinson0dd8f782010-07-08 21:15:36 +00003926 else:
3927 self.flags = flags
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003928
Stefan Krah1919b7e2012-03-21 18:25:23 +01003929 def _set_integer_check(self, name, value, vmin, vmax):
3930 if not isinstance(value, int):
3931 raise TypeError("%s must be an integer" % name)
3932 if vmin == '-inf':
3933 if value > vmax:
3934 raise ValueError("%s must be in [%s, %d]. got: %s" % (name, vmin, vmax, value))
3935 elif vmax == 'inf':
3936 if value < vmin:
3937 raise ValueError("%s must be in [%d, %s]. got: %s" % (name, vmin, vmax, value))
3938 else:
3939 if value < vmin or value > vmax:
3940 raise ValueError("%s must be in [%d, %d]. got %s" % (name, vmin, vmax, value))
3941 return object.__setattr__(self, name, value)
3942
3943 def _set_signal_dict(self, name, d):
3944 if not isinstance(d, dict):
3945 raise TypeError("%s must be a signal dict" % d)
3946 for key in d:
3947 if not key in _signals:
3948 raise KeyError("%s is not a valid signal dict" % d)
3949 for key in _signals:
3950 if not key in d:
3951 raise KeyError("%s is not a valid signal dict" % d)
3952 return object.__setattr__(self, name, d)
3953
3954 def __setattr__(self, name, value):
3955 if name == 'prec':
3956 return self._set_integer_check(name, value, 1, 'inf')
3957 elif name == 'Emin':
3958 return self._set_integer_check(name, value, '-inf', 0)
3959 elif name == 'Emax':
3960 return self._set_integer_check(name, value, 0, 'inf')
3961 elif name == 'capitals':
3962 return self._set_integer_check(name, value, 0, 1)
3963 elif name == 'clamp':
3964 return self._set_integer_check(name, value, 0, 1)
3965 elif name == 'rounding':
3966 if not value in _rounding_modes:
3967 # raise TypeError even for strings to have consistency
3968 # among various implementations.
3969 raise TypeError("%s: invalid rounding mode" % value)
3970 return object.__setattr__(self, name, value)
3971 elif name == 'flags' or name == 'traps':
3972 return self._set_signal_dict(name, value)
3973 elif name == '_ignored_flags':
3974 return object.__setattr__(self, name, value)
3975 else:
3976 raise AttributeError(
3977 "'decimal.Context' object has no attribute '%s'" % name)
3978
3979 def __delattr__(self, name):
3980 raise AttributeError("%s cannot be deleted" % name)
3981
3982 # Support for pickling, copy, and deepcopy
3983 def __reduce__(self):
3984 flags = [sig for sig, v in self.flags.items() if v]
3985 traps = [sig for sig, v in self.traps.items() if v]
3986 return (self.__class__,
3987 (self.prec, self.rounding, self.Emin, self.Emax,
3988 self.capitals, self.clamp, flags, traps))
3989
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003990 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003991 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003992 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003993 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00003994 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, '
3995 'clamp=%(clamp)d'
Guido van Rossumd8faa362007-04-27 19:54:29 +00003996 % vars(self))
3997 names = [f.__name__ for f, v in self.flags.items() if v]
3998 s.append('flags=[' + ', '.join(names) + ']')
3999 names = [t.__name__ for t, v in self.traps.items() if v]
4000 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00004001 return ', '.join(s) + ')'
4002
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00004003 def clear_flags(self):
4004 """Reset all flags to zero"""
4005 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00004006 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00004007
Stefan Krah1919b7e2012-03-21 18:25:23 +01004008 def clear_traps(self):
4009 """Reset all traps to zero"""
4010 for flag in self.traps:
4011 self.traps[flag] = 0
4012
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004013 def _shallow_copy(self):
4014 """Returns a shallow copy from self."""
Stefan Krah1919b7e2012-03-21 18:25:23 +01004015 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
4016 self.capitals, self.clamp, self.flags, self.traps,
4017 self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004018 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004019
4020 def copy(self):
4021 """Returns a deep copy from self."""
Stefan Krah1919b7e2012-03-21 18:25:23 +01004022 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
4023 self.capitals, self.clamp,
4024 self.flags.copy(), self.traps.copy(),
4025 self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00004026 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004027 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004028
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004029 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004030 """Handles an error
4031
4032 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00004033 Otherwise, it sets the flag, then, if the corresponding
Stefan Krah2eb4a072010-05-19 15:52:31 +00004034 trap_enabler is set, it reraises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00004035 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004036 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004037 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004038 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00004039 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004040 return error().handle(self, *args)
4041
Raymond Hettinger86173da2008-02-01 20:38:12 +00004042 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00004043 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00004044 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004045 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004046
4047 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00004048 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00004049 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004050
4051 def _ignore_all_flags(self):
4052 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00004053 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004054
4055 def _ignore_flags(self, *flags):
4056 """Ignore the flags, if they are raised"""
4057 # Do not mutate-- This way, copies of a context leave the original
4058 # alone.
4059 self._ignored_flags = (self._ignored_flags + list(flags))
4060 return list(flags)
4061
4062 def _regard_flags(self, *flags):
4063 """Stop ignoring the flags, if they are raised"""
4064 if flags and isinstance(flags[0], (tuple,list)):
4065 flags = flags[0]
4066 for flag in flags:
4067 self._ignored_flags.remove(flag)
4068
Nick Coghland1abd252008-07-15 15:46:38 +00004069 # We inherit object.__hash__, so we must deny this explicitly
4070 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00004071
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004072 def Etiny(self):
4073 """Returns Etiny (= Emin - prec + 1)"""
4074 return int(self.Emin - self.prec + 1)
4075
4076 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004077 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004078 return int(self.Emax - self.prec + 1)
4079
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004080 def _set_rounding(self, type):
4081 """Sets the rounding type.
4082
4083 Sets the rounding type, and returns the current (previous)
4084 rounding type. Often used like:
4085
4086 context = context.copy()
4087 # so you don't change the calling context
4088 # if an error occurs in the middle.
4089 rounding = context._set_rounding(ROUND_UP)
4090 val = self.__sub__(other, context=context)
4091 context._set_rounding(rounding)
4092
4093 This will make it round up for that operation.
4094 """
4095 rounding = self.rounding
4096 self.rounding= type
4097 return rounding
4098
Raymond Hettingerfed52962004-07-14 15:41:57 +00004099 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00004100 """Creates a new Decimal instance but using self as context.
4101
4102 This method implements the to-number operation of the
4103 IBM Decimal specification."""
4104
4105 if isinstance(num, str) and num != num.strip():
4106 return self._raise_error(ConversionSyntax,
4107 "no trailing or leading whitespace is "
4108 "permitted.")
4109
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004110 d = Decimal(num, context=self)
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00004111 if d._isnan() and len(d._int) > self.prec - self.clamp:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004112 return self._raise_error(ConversionSyntax,
4113 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00004114 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004115
Raymond Hettinger771ed762009-01-03 19:20:32 +00004116 def create_decimal_from_float(self, f):
4117 """Creates a new Decimal instance from a float but rounding using self
4118 as the context.
4119
4120 >>> context = Context(prec=5, rounding=ROUND_DOWN)
4121 >>> context.create_decimal_from_float(3.1415926535897932)
4122 Decimal('3.1415')
4123 >>> context = Context(prec=5, traps=[Inexact])
4124 >>> context.create_decimal_from_float(3.1415926535897932)
4125 Traceback (most recent call last):
4126 ...
4127 decimal.Inexact: None
4128
4129 """
4130 d = Decimal.from_float(f) # An exact conversion
4131 return d._fix(self) # Apply the context rounding
4132
Guido van Rossumd8faa362007-04-27 19:54:29 +00004133 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004134 def abs(self, a):
4135 """Returns the absolute value of the operand.
4136
4137 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00004138 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004139 the plus operation on the operand.
4140
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004141 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004142 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004143 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004144 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004145 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004146 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004147 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004148 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00004149 >>> ExtendedContext.abs(-1)
4150 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004151 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004152 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004153 return a.__abs__(context=self)
4154
4155 def add(self, a, b):
4156 """Return the sum of the two operands.
4157
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004158 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004159 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004160 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004161 Decimal('1.02E+4')
Mark Dickinson84230a12010-02-18 14:49:50 +00004162 >>> ExtendedContext.add(1, Decimal(2))
4163 Decimal('3')
4164 >>> ExtendedContext.add(Decimal(8), 5)
4165 Decimal('13')
4166 >>> ExtendedContext.add(5, 5)
4167 Decimal('10')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004168 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004169 a = _convert_other(a, raiseit=True)
4170 r = a.__add__(b, context=self)
4171 if r is NotImplemented:
4172 raise TypeError("Unable to convert %s to Decimal" % b)
4173 else:
4174 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004175
4176 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00004177 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004178
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004179 def canonical(self, a):
4180 """Returns the same Decimal object.
4181
4182 As we do not have different encodings for the same number, the
4183 received object already is in its canonical form.
4184
4185 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004186 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004187 """
Stefan Krah1919b7e2012-03-21 18:25:23 +01004188 if not isinstance(a, Decimal):
4189 raise TypeError("canonical requires a Decimal as an argument.")
Stefan Krah040e3112012-12-15 22:33:33 +01004190 return a.canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004191
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004192 def compare(self, a, b):
4193 """Compares values numerically.
4194
4195 If the signs of the operands differ, a value representing each operand
4196 ('-1' if the operand is less than zero, '0' if the operand is zero or
4197 negative zero, or '1' if the operand is greater than zero) is used in
4198 place of that operand for the comparison instead of the actual
4199 operand.
4200
4201 The comparison is then effected by subtracting the second operand from
4202 the first and then returning a value according to the result of the
4203 subtraction: '-1' if the result is less than zero, '0' if the result is
4204 zero or negative zero, or '1' if the result is greater than zero.
4205
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004206 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004207 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004208 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004209 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004210 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004211 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004212 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004213 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004214 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004215 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004216 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004217 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004218 >>> ExtendedContext.compare(1, 2)
4219 Decimal('-1')
4220 >>> ExtendedContext.compare(Decimal(1), 2)
4221 Decimal('-1')
4222 >>> ExtendedContext.compare(1, Decimal(2))
4223 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004224 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004225 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004226 return a.compare(b, context=self)
4227
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004228 def compare_signal(self, a, b):
4229 """Compares the values of the two operands numerically.
4230
4231 It's pretty much like compare(), but all NaNs signal, with signaling
4232 NaNs taking precedence over quiet NaNs.
4233
4234 >>> c = ExtendedContext
4235 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004236 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004237 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004238 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004239 >>> c.flags[InvalidOperation] = 0
4240 >>> print(c.flags[InvalidOperation])
4241 0
4242 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004243 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004244 >>> print(c.flags[InvalidOperation])
4245 1
4246 >>> c.flags[InvalidOperation] = 0
4247 >>> print(c.flags[InvalidOperation])
4248 0
4249 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004250 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004251 >>> print(c.flags[InvalidOperation])
4252 1
Mark Dickinson84230a12010-02-18 14:49:50 +00004253 >>> c.compare_signal(-1, 2)
4254 Decimal('-1')
4255 >>> c.compare_signal(Decimal(-1), 2)
4256 Decimal('-1')
4257 >>> c.compare_signal(-1, Decimal(2))
4258 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004259 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004260 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004261 return a.compare_signal(b, context=self)
4262
4263 def compare_total(self, a, b):
4264 """Compares two operands using their abstract representation.
4265
4266 This is not like the standard compare, which use their numerical
4267 value. Note that a total ordering is defined for all possible abstract
4268 representations.
4269
4270 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004271 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004272 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004273 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004274 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004275 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004276 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004277 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004278 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004279 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004280 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004281 Decimal('-1')
Mark Dickinson84230a12010-02-18 14:49:50 +00004282 >>> ExtendedContext.compare_total(1, 2)
4283 Decimal('-1')
4284 >>> ExtendedContext.compare_total(Decimal(1), 2)
4285 Decimal('-1')
4286 >>> ExtendedContext.compare_total(1, Decimal(2))
4287 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004288 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004289 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004290 return a.compare_total(b)
4291
4292 def compare_total_mag(self, a, b):
4293 """Compares two operands using their abstract representation ignoring sign.
4294
4295 Like compare_total, but with operand's sign ignored and assumed to be 0.
4296 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004297 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004298 return a.compare_total_mag(b)
4299
4300 def copy_abs(self, a):
4301 """Returns a copy of the operand with the sign set to 0.
4302
4303 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004304 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004305 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004306 Decimal('100')
Mark Dickinson84230a12010-02-18 14:49:50 +00004307 >>> ExtendedContext.copy_abs(-1)
4308 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004309 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004310 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004311 return a.copy_abs()
4312
4313 def copy_decimal(self, a):
Mark Dickinson84230a12010-02-18 14:49:50 +00004314 """Returns a copy of the decimal object.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004315
4316 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004317 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004318 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004319 Decimal('-1.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00004320 >>> ExtendedContext.copy_decimal(1)
4321 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004322 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004323 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004324 return Decimal(a)
4325
4326 def copy_negate(self, a):
4327 """Returns a copy of the operand with the sign inverted.
4328
4329 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004330 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004331 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004332 Decimal('101.5')
Mark Dickinson84230a12010-02-18 14:49:50 +00004333 >>> ExtendedContext.copy_negate(1)
4334 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004335 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004336 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004337 return a.copy_negate()
4338
4339 def copy_sign(self, a, b):
4340 """Copies the second operand's sign to the first one.
4341
4342 In detail, it returns a copy of the first operand with the sign
4343 equal to the sign of the second operand.
4344
4345 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004346 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004347 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004348 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004349 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004350 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004351 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004352 Decimal('-1.50')
Mark Dickinson84230a12010-02-18 14:49:50 +00004353 >>> ExtendedContext.copy_sign(1, -2)
4354 Decimal('-1')
4355 >>> ExtendedContext.copy_sign(Decimal(1), -2)
4356 Decimal('-1')
4357 >>> ExtendedContext.copy_sign(1, Decimal(-2))
4358 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004359 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004360 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004361 return a.copy_sign(b)
4362
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004363 def divide(self, a, b):
4364 """Decimal division in a specified context.
4365
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004366 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004367 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004368 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004369 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004370 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004371 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004372 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004373 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004374 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004375 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004376 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004377 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004378 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004379 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004380 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004381 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004382 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004383 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004384 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004385 Decimal('1.20E+6')
Mark Dickinson84230a12010-02-18 14:49:50 +00004386 >>> ExtendedContext.divide(5, 5)
4387 Decimal('1')
4388 >>> ExtendedContext.divide(Decimal(5), 5)
4389 Decimal('1')
4390 >>> ExtendedContext.divide(5, Decimal(5))
4391 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004392 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004393 a = _convert_other(a, raiseit=True)
4394 r = a.__truediv__(b, context=self)
4395 if r is NotImplemented:
4396 raise TypeError("Unable to convert %s to Decimal" % b)
4397 else:
4398 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004399
4400 def divide_int(self, a, b):
4401 """Divides two numbers and returns the integer part of the result.
4402
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004403 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004404 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004405 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004406 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004407 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004408 Decimal('3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004409 >>> ExtendedContext.divide_int(10, 3)
4410 Decimal('3')
4411 >>> ExtendedContext.divide_int(Decimal(10), 3)
4412 Decimal('3')
4413 >>> ExtendedContext.divide_int(10, Decimal(3))
4414 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004415 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004416 a = _convert_other(a, raiseit=True)
4417 r = a.__floordiv__(b, context=self)
4418 if r is NotImplemented:
4419 raise TypeError("Unable to convert %s to Decimal" % b)
4420 else:
4421 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004422
4423 def divmod(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004424 """Return (a // b, a % b).
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004425
4426 >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
4427 (Decimal('2'), Decimal('2'))
4428 >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
4429 (Decimal('2'), Decimal('0'))
Mark Dickinson84230a12010-02-18 14:49:50 +00004430 >>> ExtendedContext.divmod(8, 4)
4431 (Decimal('2'), Decimal('0'))
4432 >>> ExtendedContext.divmod(Decimal(8), 4)
4433 (Decimal('2'), Decimal('0'))
4434 >>> ExtendedContext.divmod(8, Decimal(4))
4435 (Decimal('2'), Decimal('0'))
Mark Dickinsonc53796e2010-01-06 16:22:15 +00004436 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004437 a = _convert_other(a, raiseit=True)
4438 r = a.__divmod__(b, context=self)
4439 if r is NotImplemented:
4440 raise TypeError("Unable to convert %s to Decimal" % b)
4441 else:
4442 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004443
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004444 def exp(self, a):
4445 """Returns e ** a.
4446
4447 >>> c = ExtendedContext.copy()
4448 >>> c.Emin = -999
4449 >>> c.Emax = 999
4450 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004451 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004452 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004453 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004454 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004455 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004456 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004457 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004458 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004459 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004460 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004461 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004462 >>> c.exp(10)
4463 Decimal('22026.4658')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004464 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004465 a =_convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004466 return a.exp(context=self)
4467
4468 def fma(self, a, b, c):
4469 """Returns a multiplied by b, plus c.
4470
4471 The first two operands are multiplied together, using multiply,
4472 the third operand is then added to the result of that
4473 multiplication, using add, all with only one final rounding.
4474
4475 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004476 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004477 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004478 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004479 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004480 Decimal('1.38435736E+12')
Mark Dickinson84230a12010-02-18 14:49:50 +00004481 >>> ExtendedContext.fma(1, 3, 4)
4482 Decimal('7')
4483 >>> ExtendedContext.fma(1, Decimal(3), 4)
4484 Decimal('7')
4485 >>> ExtendedContext.fma(1, 3, Decimal(4))
4486 Decimal('7')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004487 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004488 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004489 return a.fma(b, c, context=self)
4490
4491 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004492 """Return True if the operand is canonical; otherwise return False.
4493
4494 Currently, the encoding of a Decimal instance is always
4495 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004496
4497 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004498 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004499 """
Stefan Krah1919b7e2012-03-21 18:25:23 +01004500 if not isinstance(a, Decimal):
4501 raise TypeError("is_canonical requires a Decimal as an argument.")
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004502 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004503
4504 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004505 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004506
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004507 A Decimal instance is considered finite if it is neither
4508 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004509
4510 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004511 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004512 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004513 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004514 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004515 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004516 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004517 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004518 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004519 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004520 >>> ExtendedContext.is_finite(1)
4521 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004522 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004523 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004524 return a.is_finite()
4525
4526 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004527 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004528
4529 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004530 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004531 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004532 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004533 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004534 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004535 >>> ExtendedContext.is_infinite(1)
4536 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004537 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004538 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004539 return a.is_infinite()
4540
4541 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004542 """Return True if the operand is a qNaN or sNaN;
4543 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004544
4545 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004546 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004547 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004548 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004549 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004550 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004551 >>> ExtendedContext.is_nan(1)
4552 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004553 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004554 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004555 return a.is_nan()
4556
4557 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004558 """Return True if the operand is a normal number;
4559 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004560
4561 >>> c = ExtendedContext.copy()
4562 >>> c.Emin = -999
4563 >>> c.Emax = 999
4564 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004565 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004566 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004567 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004568 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004569 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004570 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004571 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004572 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004573 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004574 >>> c.is_normal(1)
4575 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004576 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004577 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004578 return a.is_normal(context=self)
4579
4580 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004581 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004582
4583 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004584 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004585 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004586 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004587 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004588 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004589 >>> ExtendedContext.is_qnan(1)
4590 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004591 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004592 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004593 return a.is_qnan()
4594
4595 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004596 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004597
4598 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004599 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004600 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004601 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004602 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004603 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004604 >>> ExtendedContext.is_signed(8)
4605 False
4606 >>> ExtendedContext.is_signed(-8)
4607 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004608 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004609 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004610 return a.is_signed()
4611
4612 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004613 """Return True if the operand is a signaling NaN;
4614 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004615
4616 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004617 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004618 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004619 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004620 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004621 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004622 >>> ExtendedContext.is_snan(1)
4623 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004624 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004625 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004626 return a.is_snan()
4627
4628 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004629 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004630
4631 >>> c = ExtendedContext.copy()
4632 >>> c.Emin = -999
4633 >>> c.Emax = 999
4634 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004635 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004636 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004637 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004638 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004639 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004640 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004641 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004642 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004643 False
Mark Dickinson84230a12010-02-18 14:49:50 +00004644 >>> c.is_subnormal(1)
4645 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004646 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004647 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004648 return a.is_subnormal(context=self)
4649
4650 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004651 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004652
4653 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004654 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004655 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004656 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004657 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004658 True
Mark Dickinson84230a12010-02-18 14:49:50 +00004659 >>> ExtendedContext.is_zero(1)
4660 False
4661 >>> ExtendedContext.is_zero(0)
4662 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004663 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004664 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004665 return a.is_zero()
4666
4667 def ln(self, a):
4668 """Returns the natural (base e) logarithm of the operand.
4669
4670 >>> c = ExtendedContext.copy()
4671 >>> c.Emin = -999
4672 >>> c.Emax = 999
4673 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004674 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004675 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004676 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004677 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004678 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004679 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004680 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004681 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004682 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004683 >>> c.ln(1)
4684 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004685 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004686 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004687 return a.ln(context=self)
4688
4689 def log10(self, a):
4690 """Returns the base 10 logarithm of the operand.
4691
4692 >>> c = ExtendedContext.copy()
4693 >>> c.Emin = -999
4694 >>> c.Emax = 999
4695 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004696 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004697 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004698 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004699 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004700 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004701 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004702 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004703 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004704 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004705 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004706 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004707 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004708 Decimal('Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004709 >>> c.log10(0)
4710 Decimal('-Infinity')
4711 >>> c.log10(1)
4712 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004713 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004714 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004715 return a.log10(context=self)
4716
4717 def logb(self, a):
4718 """ Returns the exponent of the magnitude of the operand's MSD.
4719
4720 The result is the integer which is the exponent of the magnitude
4721 of the most significant digit of the operand (as though the
4722 operand were truncated to a single digit while maintaining the
4723 value of that digit and without limiting the resulting exponent).
4724
4725 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004726 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004727 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004728 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004729 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004730 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004731 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004732 Decimal('-Infinity')
Mark Dickinson84230a12010-02-18 14:49:50 +00004733 >>> ExtendedContext.logb(1)
4734 Decimal('0')
4735 >>> ExtendedContext.logb(10)
4736 Decimal('1')
4737 >>> ExtendedContext.logb(100)
4738 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004739 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004740 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004741 return a.logb(context=self)
4742
4743 def logical_and(self, a, b):
4744 """Applies the logical operation 'and' between each operand's digits.
4745
4746 The operands must be both logical numbers.
4747
4748 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004749 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004750 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004751 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004752 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004753 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004754 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004755 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004756 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004757 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004758 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004759 Decimal('10')
Mark Dickinson84230a12010-02-18 14:49:50 +00004760 >>> ExtendedContext.logical_and(110, 1101)
4761 Decimal('100')
4762 >>> ExtendedContext.logical_and(Decimal(110), 1101)
4763 Decimal('100')
4764 >>> ExtendedContext.logical_and(110, Decimal(1101))
4765 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004766 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004767 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004768 return a.logical_and(b, context=self)
4769
4770 def logical_invert(self, a):
4771 """Invert all the digits in the operand.
4772
4773 The operand must be a logical number.
4774
4775 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004776 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004777 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004778 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004779 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004780 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004781 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004782 Decimal('10101010')
Mark Dickinson84230a12010-02-18 14:49:50 +00004783 >>> ExtendedContext.logical_invert(1101)
4784 Decimal('111110010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004785 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004786 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004787 return a.logical_invert(context=self)
4788
4789 def logical_or(self, a, b):
4790 """Applies the logical operation 'or' between each operand's digits.
4791
4792 The operands must be both logical numbers.
4793
4794 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004795 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004796 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004797 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004798 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004799 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004800 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004801 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004802 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004803 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004804 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004805 Decimal('1110')
Mark Dickinson84230a12010-02-18 14:49:50 +00004806 >>> ExtendedContext.logical_or(110, 1101)
4807 Decimal('1111')
4808 >>> ExtendedContext.logical_or(Decimal(110), 1101)
4809 Decimal('1111')
4810 >>> ExtendedContext.logical_or(110, Decimal(1101))
4811 Decimal('1111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004812 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004813 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004814 return a.logical_or(b, context=self)
4815
4816 def logical_xor(self, a, b):
4817 """Applies the logical operation 'xor' between each operand's digits.
4818
4819 The operands must be both logical numbers.
4820
4821 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004822 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004823 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004824 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004825 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004826 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004827 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004828 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004829 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004830 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004831 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004832 Decimal('1101')
Mark Dickinson84230a12010-02-18 14:49:50 +00004833 >>> ExtendedContext.logical_xor(110, 1101)
4834 Decimal('1011')
4835 >>> ExtendedContext.logical_xor(Decimal(110), 1101)
4836 Decimal('1011')
4837 >>> ExtendedContext.logical_xor(110, Decimal(1101))
4838 Decimal('1011')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004839 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004840 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004841 return a.logical_xor(b, context=self)
4842
Mark Dickinson84230a12010-02-18 14:49:50 +00004843 def max(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004844 """max compares two values numerically and returns the maximum.
4845
4846 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004847 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004848 operation. If they are numerically equal then the left-hand operand
4849 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004850 infinity) of the two operands is chosen as the result.
4851
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004852 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004853 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004854 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004855 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004856 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004857 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004858 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004859 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004860 >>> ExtendedContext.max(1, 2)
4861 Decimal('2')
4862 >>> ExtendedContext.max(Decimal(1), 2)
4863 Decimal('2')
4864 >>> ExtendedContext.max(1, Decimal(2))
4865 Decimal('2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004866 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004867 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004868 return a.max(b, context=self)
4869
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004870 def max_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004871 """Compares the values numerically with their sign ignored.
4872
4873 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
4874 Decimal('7')
4875 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
4876 Decimal('-10')
4877 >>> ExtendedContext.max_mag(1, -2)
4878 Decimal('-2')
4879 >>> ExtendedContext.max_mag(Decimal(1), -2)
4880 Decimal('-2')
4881 >>> ExtendedContext.max_mag(1, Decimal(-2))
4882 Decimal('-2')
4883 """
4884 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004885 return a.max_mag(b, context=self)
4886
Mark Dickinson84230a12010-02-18 14:49:50 +00004887 def min(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004888 """min compares two values numerically and returns the minimum.
4889
4890 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004891 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004892 operation. If they are numerically equal then the left-hand operand
4893 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004894 infinity) of the two operands is chosen as the result.
4895
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004896 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004897 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004898 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004899 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004900 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004901 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004902 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004903 Decimal('7')
Mark Dickinson84230a12010-02-18 14:49:50 +00004904 >>> ExtendedContext.min(1, 2)
4905 Decimal('1')
4906 >>> ExtendedContext.min(Decimal(1), 2)
4907 Decimal('1')
4908 >>> ExtendedContext.min(1, Decimal(29))
4909 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004910 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004911 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004912 return a.min(b, context=self)
4913
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004914 def min_mag(self, a, b):
Mark Dickinson84230a12010-02-18 14:49:50 +00004915 """Compares the values numerically with their sign ignored.
4916
4917 >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
4918 Decimal('-2')
4919 >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
4920 Decimal('-3')
4921 >>> ExtendedContext.min_mag(1, -2)
4922 Decimal('1')
4923 >>> ExtendedContext.min_mag(Decimal(1), -2)
4924 Decimal('1')
4925 >>> ExtendedContext.min_mag(1, Decimal(-2))
4926 Decimal('1')
4927 """
4928 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004929 return a.min_mag(b, context=self)
4930
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004931 def minus(self, a):
4932 """Minus corresponds to unary prefix minus in Python.
4933
4934 The operation is evaluated using the same rules as subtract; the
4935 operation minus(a) is calculated as subtract('0', a) where the '0'
4936 has the same exponent as the operand.
4937
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004938 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004939 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004940 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004941 Decimal('1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00004942 >>> ExtendedContext.minus(1)
4943 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004944 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004945 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004946 return a.__neg__(context=self)
4947
4948 def multiply(self, a, b):
4949 """multiply multiplies two operands.
4950
4951 If either operand is a special value then the general rules apply.
Mark Dickinson84230a12010-02-18 14:49:50 +00004952 Otherwise, the operands are multiplied together
4953 ('long multiplication'), resulting in a number which may be as long as
4954 the sum of the lengths of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004955
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004956 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004957 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004958 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004959 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004960 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004961 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004962 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004963 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004964 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004965 Decimal('4.28135971E+11')
Mark Dickinson84230a12010-02-18 14:49:50 +00004966 >>> ExtendedContext.multiply(7, 7)
4967 Decimal('49')
4968 >>> ExtendedContext.multiply(Decimal(7), 7)
4969 Decimal('49')
4970 >>> ExtendedContext.multiply(7, Decimal(7))
4971 Decimal('49')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004972 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004973 a = _convert_other(a, raiseit=True)
4974 r = a.__mul__(b, context=self)
4975 if r is NotImplemented:
4976 raise TypeError("Unable to convert %s to Decimal" % b)
4977 else:
4978 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004979
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004980 def next_minus(self, a):
4981 """Returns the largest representable number smaller than a.
4982
4983 >>> c = ExtendedContext.copy()
4984 >>> c.Emin = -999
4985 >>> c.Emax = 999
4986 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004987 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004988 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004989 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004990 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004991 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004992 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004993 Decimal('9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00004994 >>> c.next_minus(1)
4995 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004996 """
Mark Dickinson84230a12010-02-18 14:49:50 +00004997 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004998 return a.next_minus(context=self)
4999
5000 def next_plus(self, a):
5001 """Returns the smallest representable number larger than a.
5002
5003 >>> c = ExtendedContext.copy()
5004 >>> c.Emin = -999
5005 >>> c.Emax = 999
5006 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005007 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005008 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005009 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005010 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005011 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005012 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005013 Decimal('-9.99999999E+999')
Mark Dickinson84230a12010-02-18 14:49:50 +00005014 >>> c.next_plus(1)
5015 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005016 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005017 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005018 return a.next_plus(context=self)
5019
5020 def next_toward(self, a, b):
5021 """Returns the number closest to a, in direction towards b.
5022
5023 The result is the closest representable number from the first
5024 operand (but not the first operand) that is in the direction
5025 towards the second operand, unless the operands have the same
5026 value.
5027
5028 >>> c = ExtendedContext.copy()
5029 >>> c.Emin = -999
5030 >>> c.Emax = 999
5031 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005032 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005033 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005034 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005035 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005036 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005037 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005038 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005039 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005040 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005041 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005042 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005043 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005044 Decimal('-0.00')
Mark Dickinson84230a12010-02-18 14:49:50 +00005045 >>> c.next_toward(0, 1)
5046 Decimal('1E-1007')
5047 >>> c.next_toward(Decimal(0), 1)
5048 Decimal('1E-1007')
5049 >>> c.next_toward(0, Decimal(1))
5050 Decimal('1E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005051 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005052 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005053 return a.next_toward(b, context=self)
5054
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005055 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00005056 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005057
5058 Essentially a plus operation with all trailing zeros removed from the
5059 result.
5060
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005061 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005062 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005063 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005064 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005065 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005066 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005067 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005068 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005069 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005070 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005071 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005072 Decimal('0')
Mark Dickinson84230a12010-02-18 14:49:50 +00005073 >>> ExtendedContext.normalize(6)
5074 Decimal('6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005075 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005076 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005077 return a.normalize(context=self)
5078
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005079 def number_class(self, a):
5080 """Returns an indication of the class of the operand.
5081
5082 The class is one of the following strings:
5083 -sNaN
5084 -NaN
5085 -Infinity
5086 -Normal
5087 -Subnormal
5088 -Zero
5089 +Zero
5090 +Subnormal
5091 +Normal
5092 +Infinity
5093
Stefan Krah1919b7e2012-03-21 18:25:23 +01005094 >>> c = ExtendedContext.copy()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005095 >>> c.Emin = -999
5096 >>> c.Emax = 999
5097 >>> c.number_class(Decimal('Infinity'))
5098 '+Infinity'
5099 >>> c.number_class(Decimal('1E-10'))
5100 '+Normal'
5101 >>> c.number_class(Decimal('2.50'))
5102 '+Normal'
5103 >>> c.number_class(Decimal('0.1E-999'))
5104 '+Subnormal'
5105 >>> c.number_class(Decimal('0'))
5106 '+Zero'
5107 >>> c.number_class(Decimal('-0'))
5108 '-Zero'
5109 >>> c.number_class(Decimal('-0.1E-999'))
5110 '-Subnormal'
5111 >>> c.number_class(Decimal('-1E-10'))
5112 '-Normal'
5113 >>> c.number_class(Decimal('-2.50'))
5114 '-Normal'
5115 >>> c.number_class(Decimal('-Infinity'))
5116 '-Infinity'
5117 >>> c.number_class(Decimal('NaN'))
5118 'NaN'
5119 >>> c.number_class(Decimal('-NaN'))
5120 'NaN'
5121 >>> c.number_class(Decimal('sNaN'))
5122 'sNaN'
Mark Dickinson84230a12010-02-18 14:49:50 +00005123 >>> c.number_class(123)
5124 '+Normal'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005125 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005126 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005127 return a.number_class(context=self)
5128
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005129 def plus(self, a):
5130 """Plus corresponds to unary prefix plus in Python.
5131
5132 The operation is evaluated using the same rules as add; the
5133 operation plus(a) is calculated as add('0', a) where the '0'
5134 has the same exponent as the operand.
5135
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005136 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005137 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005138 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005139 Decimal('-1.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005140 >>> ExtendedContext.plus(-1)
5141 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005142 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005143 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005144 return a.__pos__(context=self)
5145
5146 def power(self, a, b, modulo=None):
5147 """Raises a to the power of b, to modulo if given.
5148
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005149 With two arguments, compute a**b. If a is negative then b
5150 must be integral. The result will be inexact unless b is
5151 integral and the result is finite and can be expressed exactly
5152 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005153
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005154 With three arguments, compute (a**b) % modulo. For the
5155 three argument form, the following restrictions on the
5156 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005157
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005158 - all three arguments must be integral
5159 - b must be nonnegative
5160 - at least one of a or b must be nonzero
5161 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005162
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005163 The result of pow(a, b, modulo) is identical to the result
5164 that would be obtained by computing (a**b) % modulo with
5165 unbounded precision, but is computed more efficiently. It is
5166 always exact.
5167
5168 >>> c = ExtendedContext.copy()
5169 >>> c.Emin = -999
5170 >>> c.Emax = 999
5171 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005172 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005173 >>> c.power(Decimal('-2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005174 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005175 >>> c.power(Decimal('2'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005176 Decimal('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005177 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005178 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005179 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005180 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005181 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005182 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005183 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005184 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005185 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005186 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005187 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005188 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005189 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005190 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005191 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005192 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005193 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005194 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005195 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005196 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005197
5198 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005199 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005200 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005201 Decimal('-11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005202 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005203 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005204 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005205 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005206 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005207 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005208 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005209 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005210 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005211 Decimal('1')
Mark Dickinson84230a12010-02-18 14:49:50 +00005212 >>> ExtendedContext.power(7, 7)
5213 Decimal('823543')
5214 >>> ExtendedContext.power(Decimal(7), 7)
5215 Decimal('823543')
5216 >>> ExtendedContext.power(7, Decimal(7), 2)
5217 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005218 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005219 a = _convert_other(a, raiseit=True)
5220 r = a.__pow__(b, modulo, context=self)
5221 if r is NotImplemented:
5222 raise TypeError("Unable to convert %s to Decimal" % b)
5223 else:
5224 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005225
5226 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005227 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005228
5229 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00005230 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005231 exponent is being increased), multiplied by a positive power of ten (if
5232 the exponent is being decreased), or is unchanged (if the exponent is
5233 already equal to that of the right-hand operand).
5234
5235 Unlike other operations, if the length of the coefficient after the
5236 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00005237 operation condition is raised. This guarantees that, unless there is
5238 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005239 equal to that of the right-hand operand.
5240
5241 Also unlike other operations, quantize will never raise Underflow, even
5242 if the result is subnormal and inexact.
5243
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005244 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005245 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005246 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005247 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005248 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005249 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005250 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005251 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005252 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005253 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005254 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005255 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005256 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005257 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005258 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005259 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005260 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005261 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005262 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005263 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005264 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005265 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005266 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005267 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005268 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005269 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005270 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005271 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005272 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005273 Decimal('2E+2')
Mark Dickinson84230a12010-02-18 14:49:50 +00005274 >>> ExtendedContext.quantize(1, 2)
5275 Decimal('1')
5276 >>> ExtendedContext.quantize(Decimal(1), 2)
5277 Decimal('1')
5278 >>> ExtendedContext.quantize(1, Decimal(2))
5279 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005280 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005281 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005282 return a.quantize(b, context=self)
5283
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005284 def radix(self):
5285 """Just returns 10, as this is Decimal, :)
5286
5287 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005288 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005289 """
5290 return Decimal(10)
5291
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005292 def remainder(self, a, b):
5293 """Returns the remainder from integer division.
5294
5295 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00005296 calculating integer division as described for divide-integer, rounded
5297 to precision digits if necessary. The sign of the result, if
5298 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005299
5300 This operation will fail under the same conditions as integer division
5301 (that is, if integer division on the same two operands would fail, the
5302 remainder cannot be calculated).
5303
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005304 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005305 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005306 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005307 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005308 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005309 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005310 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005311 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005312 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005313 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005314 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005315 Decimal('1.0')
Mark Dickinson84230a12010-02-18 14:49:50 +00005316 >>> ExtendedContext.remainder(22, 6)
5317 Decimal('4')
5318 >>> ExtendedContext.remainder(Decimal(22), 6)
5319 Decimal('4')
5320 >>> ExtendedContext.remainder(22, Decimal(6))
5321 Decimal('4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005322 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005323 a = _convert_other(a, raiseit=True)
5324 r = a.__mod__(b, context=self)
5325 if r is NotImplemented:
5326 raise TypeError("Unable to convert %s to Decimal" % b)
5327 else:
5328 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005329
5330 def remainder_near(self, a, b):
5331 """Returns to be "a - b * n", where n is the integer nearest the exact
5332 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00005333 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005334 sign of a.
5335
5336 This operation will fail under the same conditions as integer division
5337 (that is, if integer division on the same two operands would fail, the
5338 remainder cannot be calculated).
5339
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005340 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005341 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005342 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005343 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005344 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005345 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005346 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005347 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005348 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005349 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005350 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005351 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005352 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005353 Decimal('-0.3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005354 >>> ExtendedContext.remainder_near(3, 11)
5355 Decimal('3')
5356 >>> ExtendedContext.remainder_near(Decimal(3), 11)
5357 Decimal('3')
5358 >>> ExtendedContext.remainder_near(3, Decimal(11))
5359 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005360 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005361 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005362 return a.remainder_near(b, context=self)
5363
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005364 def rotate(self, a, b):
5365 """Returns a rotated copy of a, b times.
5366
5367 The coefficient of the result is a rotated copy of the digits in
5368 the coefficient of the first operand. The number of places of
5369 rotation is taken from the absolute value of the second operand,
5370 with the rotation being to the left if the second operand is
5371 positive or to the right otherwise.
5372
5373 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005374 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005375 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005376 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005377 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005378 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005379 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005380 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005381 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005382 Decimal('345678912')
Mark Dickinson84230a12010-02-18 14:49:50 +00005383 >>> ExtendedContext.rotate(1333333, 1)
5384 Decimal('13333330')
5385 >>> ExtendedContext.rotate(Decimal(1333333), 1)
5386 Decimal('13333330')
5387 >>> ExtendedContext.rotate(1333333, Decimal(1))
5388 Decimal('13333330')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005389 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005390 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005391 return a.rotate(b, context=self)
5392
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005393 def same_quantum(self, a, b):
5394 """Returns True if the two operands have the same exponent.
5395
5396 The result is never affected by either the sign or the coefficient of
5397 either operand.
5398
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005399 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005400 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005401 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005402 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005403 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005404 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005405 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005406 True
Mark Dickinson84230a12010-02-18 14:49:50 +00005407 >>> ExtendedContext.same_quantum(10000, -1)
5408 True
5409 >>> ExtendedContext.same_quantum(Decimal(10000), -1)
5410 True
5411 >>> ExtendedContext.same_quantum(10000, Decimal(-1))
5412 True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005413 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005414 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005415 return a.same_quantum(b)
5416
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005417 def scaleb (self, a, b):
5418 """Returns the first operand after adding the second value its exp.
5419
5420 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005421 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005422 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005423 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005424 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005425 Decimal('7.50E+3')
Mark Dickinson84230a12010-02-18 14:49:50 +00005426 >>> ExtendedContext.scaleb(1, 4)
5427 Decimal('1E+4')
5428 >>> ExtendedContext.scaleb(Decimal(1), 4)
5429 Decimal('1E+4')
5430 >>> ExtendedContext.scaleb(1, Decimal(4))
5431 Decimal('1E+4')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005432 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005433 a = _convert_other(a, raiseit=True)
5434 return a.scaleb(b, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005435
5436 def shift(self, a, b):
5437 """Returns a shifted copy of a, b times.
5438
5439 The coefficient of the result is a shifted copy of the digits
5440 in the coefficient of the first operand. The number of places
5441 to shift is taken from the absolute value of the second operand,
5442 with the shift being to the left if the second operand is
5443 positive or to the right otherwise. Digits shifted into the
5444 coefficient are zeros.
5445
5446 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005447 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005448 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005449 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005450 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005451 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005452 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005453 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005454 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005455 Decimal('345678900')
Mark Dickinson84230a12010-02-18 14:49:50 +00005456 >>> ExtendedContext.shift(88888888, 2)
5457 Decimal('888888800')
5458 >>> ExtendedContext.shift(Decimal(88888888), 2)
5459 Decimal('888888800')
5460 >>> ExtendedContext.shift(88888888, Decimal(2))
5461 Decimal('888888800')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005462 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005463 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005464 return a.shift(b, context=self)
5465
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005466 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00005467 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005468
5469 If the result must be inexact, it is rounded using the round-half-even
5470 algorithm.
5471
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005472 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005473 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005474 >>> ExtendedContext.sqrt(Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005475 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005476 >>> ExtendedContext.sqrt(Decimal('0.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005477 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005478 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005479 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005480 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005481 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005482 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005483 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005484 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005485 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005486 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005487 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005488 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005489 Decimal('3.16227766')
Mark Dickinson84230a12010-02-18 14:49:50 +00005490 >>> ExtendedContext.sqrt(2)
5491 Decimal('1.41421356')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005492 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005493 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005494 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005495 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005496 return a.sqrt(context=self)
5497
5498 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00005499 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005500
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005501 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005502 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005503 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005504 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005505 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005506 Decimal('-0.77')
Mark Dickinson84230a12010-02-18 14:49:50 +00005507 >>> ExtendedContext.subtract(8, 5)
5508 Decimal('3')
5509 >>> ExtendedContext.subtract(Decimal(8), 5)
5510 Decimal('3')
5511 >>> ExtendedContext.subtract(8, Decimal(5))
5512 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005513 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005514 a = _convert_other(a, raiseit=True)
5515 r = a.__sub__(b, context=self)
5516 if r is NotImplemented:
5517 raise TypeError("Unable to convert %s to Decimal" % b)
5518 else:
5519 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005520
5521 def to_eng_string(self, a):
5522 """Converts a number to a string, using scientific notation.
5523
5524 The operation is not affected by the context.
5525 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005526 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005527 return a.to_eng_string(context=self)
5528
5529 def to_sci_string(self, a):
5530 """Converts a number to a string, using scientific notation.
5531
5532 The operation is not affected by the context.
5533 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005534 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005535 return a.__str__(context=self)
5536
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005537 def to_integral_exact(self, a):
5538 """Rounds to an integer.
5539
5540 When the operand has a negative exponent, the result is the same
5541 as using the quantize() operation using the given operand as the
5542 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5543 of the operand as the precision setting; Inexact and Rounded flags
5544 are allowed in this operation. The rounding mode is taken from the
5545 context.
5546
5547 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005548 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005549 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005550 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005551 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005552 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005553 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005554 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005555 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005556 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005557 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005558 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005559 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005560 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005561 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005562 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005563 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005564 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005565 return a.to_integral_exact(context=self)
5566
5567 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005568 """Rounds to an integer.
5569
5570 When the operand has a negative exponent, the result is the same
5571 as using the quantize() operation using the given operand as the
5572 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5573 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00005574 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005575
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005576 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005577 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005578 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005579 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005580 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005581 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005582 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005583 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005584 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005585 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005586 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005587 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005588 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005589 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005590 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005591 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005592 """
Mark Dickinson84230a12010-02-18 14:49:50 +00005593 a = _convert_other(a, raiseit=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005594 return a.to_integral_value(context=self)
5595
5596 # the method name changed, but we provide also the old one, for compatibility
5597 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005598
5599class _WorkRep(object):
5600 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005601 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005602 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005603 # exp: None, int, or string
5604
5605 def __init__(self, value=None):
5606 if value is None:
5607 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005608 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005609 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005610 elif isinstance(value, Decimal):
5611 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005612 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005613 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005614 else:
5615 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005616 self.sign = value[0]
5617 self.int = value[1]
5618 self.exp = value[2]
5619
5620 def __repr__(self):
5621 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5622
5623 __str__ = __repr__
5624
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005625
5626
Christian Heimes2c181612007-12-17 20:04:13 +00005627def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005628 """Normalizes op1, op2 to have the same exp and length of coefficient.
5629
5630 Done during addition.
5631 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005632 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005633 tmp = op2
5634 other = op1
5635 else:
5636 tmp = op1
5637 other = op2
5638
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005639 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5640 # Then adding 10**exp to tmp has the same effect (after rounding)
5641 # as adding any positive quantity smaller than 10**exp; similarly
5642 # for subtraction. So if other is smaller than 10**exp we replace
5643 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00005644 tmp_len = len(str(tmp.int))
5645 other_len = len(str(other.int))
5646 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5647 if other_len + other.exp - 1 < exp:
5648 other.int = 1
5649 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005650
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005651 tmp.int *= 10 ** (tmp.exp - other.exp)
5652 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005653 return op1, op2
5654
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005655##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005656
Raymond Hettingerdb213a22010-11-27 08:09:40 +00005657_nbits = int.bit_length
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005658
Mark Dickinson7ce0fa82011-06-04 18:14:23 +01005659def _decimal_lshift_exact(n, e):
5660 """ Given integers n and e, return n * 10**e if it's an integer, else None.
5661
5662 The computation is designed to avoid computing large powers of 10
5663 unnecessarily.
5664
5665 >>> _decimal_lshift_exact(3, 4)
5666 30000
5667 >>> _decimal_lshift_exact(300, -999999999) # returns None
5668
5669 """
5670 if n == 0:
5671 return 0
5672 elif e >= 0:
5673 return n * 10**e
5674 else:
5675 # val_n = largest power of 10 dividing n.
5676 str_n = str(abs(n))
5677 val_n = len(str_n) - len(str_n.rstrip('0'))
5678 return None if val_n < -e else n // 10**-e
5679
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005680def _sqrt_nearest(n, a):
5681 """Closest integer to the square root of the positive integer n. a is
5682 an initial approximation to the square root. Any positive integer
5683 will do for a, but the closer a is to the square root of n the
5684 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005685
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005686 """
5687 if n <= 0 or a <= 0:
5688 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5689
5690 b=0
5691 while a != b:
5692 b, a = a, a--n//a>>1
5693 return a
5694
5695def _rshift_nearest(x, shift):
5696 """Given an integer x and a nonnegative integer shift, return closest
5697 integer to x / 2**shift; use round-to-even in case of a tie.
5698
5699 """
5700 b, q = 1 << shift, x >> shift
5701 return q + (2*(x & (b-1)) + (q&1) > b)
5702
5703def _div_nearest(a, b):
5704 """Closest integer to a/b, a and b positive integers; rounds to even
5705 in the case of a tie.
5706
5707 """
5708 q, r = divmod(a, b)
5709 return q + (2*r + (q&1) > b)
5710
5711def _ilog(x, M, L = 8):
5712 """Integer approximation to M*log(x/M), with absolute error boundable
5713 in terms only of x/M.
5714
5715 Given positive integers x and M, return an integer approximation to
5716 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5717 between the approximation and the exact result is at most 22. For
5718 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5719 both cases these are upper bounds on the error; it will usually be
5720 much smaller."""
5721
5722 # The basic algorithm is the following: let log1p be the function
5723 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5724 # the reduction
5725 #
5726 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5727 #
5728 # repeatedly until the argument to log1p is small (< 2**-L in
5729 # absolute value). For small y we can use the Taylor series
5730 # expansion
5731 #
5732 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5733 #
5734 # truncating at T such that y**T is small enough. The whole
5735 # computation is carried out in a form of fixed-point arithmetic,
5736 # with a real number z being represented by an integer
5737 # approximation to z*M. To avoid loss of precision, the y below
5738 # is actually an integer approximation to 2**R*y*M, where R is the
5739 # number of reductions performed so far.
5740
5741 y = x-M
5742 # argument reduction; R = number of reductions performed
5743 R = 0
5744 while (R <= L and abs(y) << L-R >= M or
5745 R > L and abs(y) >> R-L >= M):
5746 y = _div_nearest((M*y) << 1,
5747 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5748 R += 1
5749
5750 # Taylor series with T terms
5751 T = -int(-10*len(str(M))//(3*L))
5752 yshift = _rshift_nearest(y, R)
5753 w = _div_nearest(M, T)
5754 for k in range(T-1, 0, -1):
5755 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5756
5757 return _div_nearest(w*y, M)
5758
5759def _dlog10(c, e, p):
5760 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5761 approximation to 10**p * log10(c*10**e), with an absolute error of
5762 at most 1. Assumes that c*10**e is not exactly 1."""
5763
5764 # increase precision by 2; compensate for this by dividing
5765 # final result by 100
5766 p += 2
5767
5768 # write c*10**e as d*10**f with either:
5769 # f >= 0 and 1 <= d <= 10, or
5770 # f <= 0 and 0.1 <= d <= 1.
5771 # Thus for c*10**e close to 1, f = 0
5772 l = len(str(c))
5773 f = e+l - (e+l >= 1)
5774
5775 if p > 0:
5776 M = 10**p
5777 k = e+p-f
5778 if k >= 0:
5779 c *= 10**k
5780 else:
5781 c = _div_nearest(c, 10**-k)
5782
5783 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005784 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005785 log_d = _div_nearest(log_d*M, log_10)
5786 log_tenpower = f*M # exact
5787 else:
5788 log_d = 0 # error < 2.31
Neal Norwitz2f99b242008-08-24 05:48:10 +00005789 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005790
5791 return _div_nearest(log_tenpower+log_d, 100)
5792
5793def _dlog(c, e, p):
5794 """Given integers c, e and p with c > 0, compute an integer
5795 approximation to 10**p * log(c*10**e), with an absolute error of
5796 at most 1. Assumes that c*10**e is not exactly 1."""
5797
5798 # Increase precision by 2. The precision increase is compensated
5799 # for at the end with a division by 100.
5800 p += 2
5801
5802 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5803 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5804 # as 10**p * log(d) + 10**p*f * log(10).
5805 l = len(str(c))
5806 f = e+l - (e+l >= 1)
5807
5808 # compute approximation to 10**p*log(d), with error < 27
5809 if p > 0:
5810 k = e+p-f
5811 if k >= 0:
5812 c *= 10**k
5813 else:
5814 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5815
5816 # _ilog magnifies existing error in c by a factor of at most 10
5817 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5818 else:
5819 # p <= 0: just approximate the whole thing by 0; error < 2.31
5820 log_d = 0
5821
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005822 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005823 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005824 extra = len(str(abs(f)))-1
5825 if p + extra >= 0:
5826 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5827 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5828 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005829 else:
5830 f_log_ten = 0
5831 else:
5832 f_log_ten = 0
5833
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005834 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005835 return _div_nearest(f_log_ten + log_d, 100)
5836
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005837class _Log10Memoize(object):
5838 """Class to compute, store, and allow retrieval of, digits of the
5839 constant log(10) = 2.302585.... This constant is needed by
5840 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5841 def __init__(self):
5842 self.digits = "23025850929940456840179914546843642076011014886"
5843
5844 def getdigits(self, p):
5845 """Given an integer p >= 0, return floor(10**p)*log(10).
5846
5847 For example, self.getdigits(3) returns 2302.
5848 """
5849 # digits are stored as a string, for quick conversion to
5850 # integer in the case that we've already computed enough
5851 # digits; the stored digits should always be correct
5852 # (truncated, not rounded to nearest).
5853 if p < 0:
5854 raise ValueError("p should be nonnegative")
5855
5856 if p >= len(self.digits):
5857 # compute p+3, p+6, p+9, ... digits; continue until at
5858 # least one of the extra digits is nonzero
5859 extra = 3
5860 while True:
5861 # compute p+extra digits, correct to within 1ulp
5862 M = 10**(p+extra+2)
5863 digits = str(_div_nearest(_ilog(10*M, M), 100))
5864 if digits[-extra:] != '0'*extra:
5865 break
5866 extra += 3
5867 # keep all reliable digits so far; remove trailing zeros
5868 # and next nonzero digit
5869 self.digits = digits.rstrip('0')[:-1]
5870 return int(self.digits[:p+1])
5871
5872_log10_digits = _Log10Memoize().getdigits
5873
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005874def _iexp(x, M, L=8):
5875 """Given integers x and M, M > 0, such that x/M is small in absolute
5876 value, compute an integer approximation to M*exp(x/M). For 0 <=
5877 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5878 is usually much smaller)."""
5879
5880 # Algorithm: to compute exp(z) for a real number z, first divide z
5881 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5882 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5883 # series
5884 #
5885 # expm1(x) = x + x**2/2! + x**3/3! + ...
5886 #
5887 # Now use the identity
5888 #
5889 # expm1(2x) = expm1(x)*(expm1(x)+2)
5890 #
5891 # R times to compute the sequence expm1(z/2**R),
5892 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5893
5894 # Find R such that x/2**R/M <= 2**-L
5895 R = _nbits((x<<L)//M)
5896
5897 # Taylor series. (2**L)**T > M
5898 T = -int(-10*len(str(M))//(3*L))
5899 y = _div_nearest(x, T)
5900 Mshift = M<<R
5901 for i in range(T-1, 0, -1):
5902 y = _div_nearest(x*(Mshift + y), Mshift * i)
5903
5904 # Expansion
5905 for k in range(R-1, -1, -1):
5906 Mshift = M<<(k+2)
5907 y = _div_nearest(y*(y+Mshift), Mshift)
5908
5909 return M+y
5910
5911def _dexp(c, e, p):
5912 """Compute an approximation to exp(c*10**e), with p decimal places of
5913 precision.
5914
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005915 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005916
5917 10**(p-1) <= d <= 10**p, and
5918 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5919
5920 In other words, d*10**f is an approximation to exp(c*10**e) with p
5921 digits of precision, and with an error in d of at most 1. This is
5922 almost, but not quite, the same as the error being < 1ulp: when d
5923 = 10**(p-1) the error could be up to 10 ulp."""
5924
5925 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5926 p += 2
5927
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005928 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005929 extra = max(0, e + len(str(c)) - 1)
5930 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005931
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005932 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005933 # rounding down
5934 shift = e+q
5935 if shift >= 0:
5936 cshift = c*10**shift
5937 else:
5938 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005939 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005940
5941 # reduce remainder back to original precision
5942 rem = _div_nearest(rem, 10**extra)
5943
5944 # error in result of _iexp < 120; error after division < 0.62
5945 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5946
5947def _dpower(xc, xe, yc, ye, p):
5948 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5949 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5950
5951 10**(p-1) <= c <= 10**p, and
5952 (c-1)*10**e < x**y < (c+1)*10**e
5953
5954 in other words, c*10**e is an approximation to x**y with p digits
5955 of precision, and with an error in c of at most 1. (This is
5956 almost, but not quite, the same as the error being < 1ulp: when c
5957 == 10**(p-1) we can only guarantee error < 10ulp.)
5958
5959 We assume that: x is positive and not equal to 1, and y is nonzero.
5960 """
5961
5962 # Find b such that 10**(b-1) <= |y| <= 10**b
5963 b = len(str(abs(yc))) + ye
5964
5965 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5966 lxc = _dlog(xc, xe, p+b+1)
5967
5968 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5969 shift = ye-b
5970 if shift >= 0:
5971 pc = lxc*yc*10**shift
5972 else:
5973 pc = _div_nearest(lxc*yc, 10**-shift)
5974
5975 if pc == 0:
5976 # we prefer a result that isn't exactly 1; this makes it
5977 # easier to compute a correctly rounded result in __pow__
5978 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5979 coeff, exp = 10**(p-1)+1, 1-p
5980 else:
5981 coeff, exp = 10**p-1, -p
5982 else:
5983 coeff, exp = _dexp(pc, -(p+1), p+1)
5984 coeff = _div_nearest(coeff, 10)
5985 exp += 1
5986
5987 return coeff, exp
5988
5989def _log10_lb(c, correction = {
5990 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5991 '6': 23, '7': 16, '8': 10, '9': 5}):
5992 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5993 if c <= 0:
5994 raise ValueError("The argument to _log10_lb should be nonnegative.")
5995 str_c = str(c)
5996 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005997
Guido van Rossumd8faa362007-04-27 19:54:29 +00005998##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005999
Mark Dickinsonac256ab2010-04-03 11:08:14 +00006000def _convert_other(other, raiseit=False, allow_float=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006001 """Convert other to Decimal.
6002
6003 Verifies that it's ok to use in an implicit construction.
Mark Dickinsonac256ab2010-04-03 11:08:14 +00006004 If allow_float is true, allow conversion from float; this
6005 is used in the comparison methods (__eq__ and friends).
6006
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006007 """
6008 if isinstance(other, Decimal):
6009 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00006010 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006011 return Decimal(other)
Mark Dickinsonac256ab2010-04-03 11:08:14 +00006012 if allow_float and isinstance(other, float):
6013 return Decimal.from_float(other)
6014
Thomas Wouters1b7f8912007-09-19 03:06:30 +00006015 if raiseit:
6016 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00006017 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00006018
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006019def _convert_for_comparison(self, other, equality_op=False):
6020 """Given a Decimal instance self and a Python object other, return
Mark Dickinson1c164a62010-06-11 16:49:20 +00006021 a pair (s, o) of Decimal instances such that "s op o" is
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006022 equivalent to "self op other" for any of the 6 comparison
6023 operators "op".
6024
6025 """
6026 if isinstance(other, Decimal):
6027 return self, other
6028
6029 # Comparison with a Rational instance (also includes integers):
6030 # self op n/d <=> self*d op n (for n and d integers, d positive).
6031 # A NaN or infinity can be left unchanged without affecting the
6032 # comparison result.
6033 if isinstance(other, _numbers.Rational):
6034 if not self._is_special:
6035 self = _dec_from_triple(self._sign,
6036 str(int(self._int) * other.denominator),
6037 self._exp)
6038 return self, Decimal(other.numerator)
6039
6040 # Comparisons with float and complex types. == and != comparisons
6041 # with complex numbers should succeed, returning either True or False
6042 # as appropriate. Other comparisons return NotImplemented.
6043 if equality_op and isinstance(other, _numbers.Complex) and other.imag == 0:
6044 other = other.real
6045 if isinstance(other, float):
Stefan Krah1919b7e2012-03-21 18:25:23 +01006046 context = getcontext()
6047 if equality_op:
6048 context.flags[FloatOperation] = 1
6049 else:
6050 context._raise_error(FloatOperation,
6051 "strict semantics for mixing floats and Decimals are enabled")
Mark Dickinson08ade6f2010-06-11 10:44:52 +00006052 return self, Decimal.from_float(other)
6053 return NotImplemented, NotImplemented
6054
6055
Guido van Rossumd8faa362007-04-27 19:54:29 +00006056##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006057
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006058# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00006059# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006060
6061DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00006062 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006063 traps=[DivisionByZero, Overflow, InvalidOperation],
6064 flags=[],
Stefan Krah1919b7e2012-03-21 18:25:23 +01006065 Emax=999999,
6066 Emin=-999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00006067 capitals=1,
6068 clamp=0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006069)
6070
6071# Pre-made alternate contexts offered by the specification
6072# Don't change these; the user should be able to select these
6073# contexts and be able to reproduce results from other implementations
6074# of the spec.
6075
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00006076BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006077 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006078 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
6079 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006080)
6081
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00006082ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00006083 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00006084 traps=[],
6085 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006086)
6087
6088
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006089##### crud for parsing strings #############################################
Christian Heimes23daade02008-02-25 12:39:23 +00006090#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006091# Regular expression used for parsing numeric strings. Additional
6092# comments:
6093#
6094# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
6095# whitespace. But note that the specification disallows whitespace in
6096# a numeric string.
6097#
6098# 2. For finite numbers (not infinities and NaNs) the body of the
6099# number between the optional sign and the optional exponent must have
6100# at least one decimal digit, possibly after the decimal point. The
Mark Dickinson345adc42009-08-02 10:14:23 +00006101# lookahead expression '(?=\d|\.\d)' checks this.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006102
6103import re
Benjamin Peterson41181742008-07-02 20:22:54 +00006104_parser = re.compile(r""" # A numeric string consists of:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006105# \s*
Benjamin Peterson41181742008-07-02 20:22:54 +00006106 (?P<sign>[-+])? # an optional sign, followed by either...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006107 (
Mark Dickinson345adc42009-08-02 10:14:23 +00006108 (?=\d|\.\d) # ...a number (with at least one digit)
6109 (?P<int>\d*) # having a (possibly empty) integer part
6110 (\.(?P<frac>\d*))? # followed by an optional fractional part
6111 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006112 |
Benjamin Peterson41181742008-07-02 20:22:54 +00006113 Inf(inity)? # ...an infinity, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006114 |
Benjamin Peterson41181742008-07-02 20:22:54 +00006115 (?P<signal>s)? # ...an (optionally signaling)
6116 NaN # NaN
Mark Dickinson345adc42009-08-02 10:14:23 +00006117 (?P<diag>\d*) # with (possibly empty) diagnostic info.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006118 )
6119# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00006120 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006121""", re.VERBOSE | re.IGNORECASE).match
6122
Christian Heimescbf3b5c2007-12-03 21:02:03 +00006123_all_zeros = re.compile('0*$').match
6124_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00006125
6126##### PEP3101 support functions ##############################################
Mark Dickinson79f52032009-03-17 23:12:51 +00006127# The functions in this section have little to do with the Decimal
6128# class, and could potentially be reused or adapted for other pure
Christian Heimesf16baeb2008-02-29 14:57:44 +00006129# Python numeric classes that want to implement __format__
6130#
6131# A format specifier for Decimal looks like:
6132#
Eric Smith984bb582010-11-25 16:08:06 +00006133# [[fill]align][sign][#][0][minimumwidth][,][.precision][type]
Christian Heimesf16baeb2008-02-29 14:57:44 +00006134
6135_parse_format_specifier_regex = re.compile(r"""\A
6136(?:
6137 (?P<fill>.)?
6138 (?P<align>[<>=^])
6139)?
6140(?P<sign>[-+ ])?
Eric Smith984bb582010-11-25 16:08:06 +00006141(?P<alt>\#)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006142(?P<zeropad>0)?
6143(?P<minimumwidth>(?!0)\d+)?
Mark Dickinson79f52032009-03-17 23:12:51 +00006144(?P<thousands_sep>,)?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006145(?:\.(?P<precision>0|(?!0)\d+))?
Mark Dickinson79f52032009-03-17 23:12:51 +00006146(?P<type>[eEfFgGn%])?
Christian Heimesf16baeb2008-02-29 14:57:44 +00006147\Z
Stefan Krah6edda142013-05-29 15:45:38 +02006148""", re.VERBOSE|re.DOTALL)
Christian Heimesf16baeb2008-02-29 14:57:44 +00006149
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006150del re
6151
Mark Dickinson79f52032009-03-17 23:12:51 +00006152# The locale module is only needed for the 'n' format specifier. The
6153# rest of the PEP 3101 code functions quite happily without it, so we
6154# don't care too much if locale isn't present.
6155try:
6156 import locale as _locale
Brett Cannoncd171c82013-07-04 17:43:24 -04006157except ImportError:
Mark Dickinson79f52032009-03-17 23:12:51 +00006158 pass
6159
6160def _parse_format_specifier(format_spec, _localeconv=None):
Christian Heimesf16baeb2008-02-29 14:57:44 +00006161 """Parse and validate a format specifier.
6162
6163 Turns a standard numeric format specifier into a dict, with the
6164 following entries:
6165
6166 fill: fill character to pad field to minimum width
6167 align: alignment type, either '<', '>', '=' or '^'
6168 sign: either '+', '-' or ' '
6169 minimumwidth: nonnegative integer giving minimum width
Mark Dickinson79f52032009-03-17 23:12:51 +00006170 zeropad: boolean, indicating whether to pad with zeros
6171 thousands_sep: string to use as thousands separator, or ''
6172 grouping: grouping for thousands separators, in format
6173 used by localeconv
6174 decimal_point: string to use for decimal point
Christian Heimesf16baeb2008-02-29 14:57:44 +00006175 precision: nonnegative integer giving precision, or None
6176 type: one of the characters 'eEfFgG%', or None
Christian Heimesf16baeb2008-02-29 14:57:44 +00006177
6178 """
6179 m = _parse_format_specifier_regex.match(format_spec)
6180 if m is None:
6181 raise ValueError("Invalid format specifier: " + format_spec)
6182
6183 # get the dictionary
6184 format_dict = m.groupdict()
6185
Mark Dickinson79f52032009-03-17 23:12:51 +00006186 # zeropad; defaults for fill and alignment. If zero padding
6187 # is requested, the fill and align fields should be absent.
Christian Heimesf16baeb2008-02-29 14:57:44 +00006188 fill = format_dict['fill']
6189 align = format_dict['align']
Mark Dickinson79f52032009-03-17 23:12:51 +00006190 format_dict['zeropad'] = (format_dict['zeropad'] is not None)
6191 if format_dict['zeropad']:
6192 if fill is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00006193 raise ValueError("Fill character conflicts with '0'"
6194 " in format specifier: " + format_spec)
Mark Dickinson79f52032009-03-17 23:12:51 +00006195 if align is not None:
Christian Heimesf16baeb2008-02-29 14:57:44 +00006196 raise ValueError("Alignment conflicts with '0' in "
6197 "format specifier: " + format_spec)
Christian Heimesf16baeb2008-02-29 14:57:44 +00006198 format_dict['fill'] = fill or ' '
Mark Dickinson46ab5d02009-09-08 20:22:46 +00006199 # PEP 3101 originally specified that the default alignment should
6200 # be left; it was later agreed that right-aligned makes more sense
6201 # for numeric types. See http://bugs.python.org/issue6857.
6202 format_dict['align'] = align or '>'
Christian Heimesf16baeb2008-02-29 14:57:44 +00006203
Mark Dickinson79f52032009-03-17 23:12:51 +00006204 # default sign handling: '-' for negative, '' for positive
Christian Heimesf16baeb2008-02-29 14:57:44 +00006205 if format_dict['sign'] is None:
6206 format_dict['sign'] = '-'
6207
Christian Heimesf16baeb2008-02-29 14:57:44 +00006208 # minimumwidth defaults to 0; precision remains None if not given
6209 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
6210 if format_dict['precision'] is not None:
6211 format_dict['precision'] = int(format_dict['precision'])
6212
6213 # if format type is 'g' or 'G' then a precision of 0 makes little
6214 # sense; convert it to 1. Same if format type is unspecified.
6215 if format_dict['precision'] == 0:
Stefan Krah1919b7e2012-03-21 18:25:23 +01006216 if format_dict['type'] is None or format_dict['type'] in 'gGn':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006217 format_dict['precision'] = 1
6218
Mark Dickinson79f52032009-03-17 23:12:51 +00006219 # determine thousands separator, grouping, and decimal separator, and
6220 # add appropriate entries to format_dict
6221 if format_dict['type'] == 'n':
6222 # apart from separators, 'n' behaves just like 'g'
6223 format_dict['type'] = 'g'
6224 if _localeconv is None:
6225 _localeconv = _locale.localeconv()
6226 if format_dict['thousands_sep'] is not None:
6227 raise ValueError("Explicit thousands separator conflicts with "
6228 "'n' type in format specifier: " + format_spec)
6229 format_dict['thousands_sep'] = _localeconv['thousands_sep']
6230 format_dict['grouping'] = _localeconv['grouping']
6231 format_dict['decimal_point'] = _localeconv['decimal_point']
6232 else:
6233 if format_dict['thousands_sep'] is None:
6234 format_dict['thousands_sep'] = ''
6235 format_dict['grouping'] = [3, 0]
6236 format_dict['decimal_point'] = '.'
Christian Heimesf16baeb2008-02-29 14:57:44 +00006237
6238 return format_dict
6239
Mark Dickinson79f52032009-03-17 23:12:51 +00006240def _format_align(sign, body, spec):
6241 """Given an unpadded, non-aligned numeric string 'body' and sign
Ezio Melotti42da6632011-03-15 05:18:48 +02006242 string 'sign', add padding and alignment conforming to the given
Mark Dickinson79f52032009-03-17 23:12:51 +00006243 format specifier dictionary 'spec' (as produced by
6244 parse_format_specifier).
Christian Heimesf16baeb2008-02-29 14:57:44 +00006245
6246 """
Christian Heimesf16baeb2008-02-29 14:57:44 +00006247 # how much extra space do we have to play with?
Mark Dickinson79f52032009-03-17 23:12:51 +00006248 minimumwidth = spec['minimumwidth']
6249 fill = spec['fill']
6250 padding = fill*(minimumwidth - len(sign) - len(body))
Christian Heimesf16baeb2008-02-29 14:57:44 +00006251
Mark Dickinson79f52032009-03-17 23:12:51 +00006252 align = spec['align']
Christian Heimesf16baeb2008-02-29 14:57:44 +00006253 if align == '<':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006254 result = sign + body + padding
Mark Dickinsonad416342009-03-17 18:10:15 +00006255 elif align == '>':
6256 result = padding + sign + body
Christian Heimesf16baeb2008-02-29 14:57:44 +00006257 elif align == '=':
6258 result = sign + padding + body
Mark Dickinson79f52032009-03-17 23:12:51 +00006259 elif align == '^':
Christian Heimesf16baeb2008-02-29 14:57:44 +00006260 half = len(padding)//2
6261 result = padding[:half] + sign + body + padding[half:]
Mark Dickinson79f52032009-03-17 23:12:51 +00006262 else:
6263 raise ValueError('Unrecognised alignment field')
Christian Heimesf16baeb2008-02-29 14:57:44 +00006264
Christian Heimesf16baeb2008-02-29 14:57:44 +00006265 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00006266
Mark Dickinson79f52032009-03-17 23:12:51 +00006267def _group_lengths(grouping):
6268 """Convert a localeconv-style grouping into a (possibly infinite)
6269 iterable of integers representing group lengths.
6270
6271 """
6272 # The result from localeconv()['grouping'], and the input to this
6273 # function, should be a list of integers in one of the
6274 # following three forms:
6275 #
6276 # (1) an empty list, or
6277 # (2) nonempty list of positive integers + [0]
6278 # (3) list of positive integers + [locale.CHAR_MAX], or
6279
6280 from itertools import chain, repeat
6281 if not grouping:
6282 return []
6283 elif grouping[-1] == 0 and len(grouping) >= 2:
6284 return chain(grouping[:-1], repeat(grouping[-2]))
6285 elif grouping[-1] == _locale.CHAR_MAX:
6286 return grouping[:-1]
6287 else:
6288 raise ValueError('unrecognised format for grouping')
6289
6290def _insert_thousands_sep(digits, spec, min_width=1):
6291 """Insert thousands separators into a digit string.
6292
6293 spec is a dictionary whose keys should include 'thousands_sep' and
6294 'grouping'; typically it's the result of parsing the format
6295 specifier using _parse_format_specifier.
6296
6297 The min_width keyword argument gives the minimum length of the
6298 result, which will be padded on the left with zeros if necessary.
6299
6300 If necessary, the zero padding adds an extra '0' on the left to
6301 avoid a leading thousands separator. For example, inserting
6302 commas every three digits in '123456', with min_width=8, gives
6303 '0,123,456', even though that has length 9.
6304
6305 """
6306
6307 sep = spec['thousands_sep']
6308 grouping = spec['grouping']
6309
6310 groups = []
6311 for l in _group_lengths(grouping):
Mark Dickinson79f52032009-03-17 23:12:51 +00006312 if l <= 0:
6313 raise ValueError("group length should be positive")
6314 # max(..., 1) forces at least 1 digit to the left of a separator
6315 l = min(max(len(digits), min_width, 1), l)
6316 groups.append('0'*(l - len(digits)) + digits[-l:])
6317 digits = digits[:-l]
6318 min_width -= l
6319 if not digits and min_width <= 0:
6320 break
Mark Dickinson7303b592009-03-18 08:25:36 +00006321 min_width -= len(sep)
Mark Dickinson79f52032009-03-17 23:12:51 +00006322 else:
6323 l = max(len(digits), min_width, 1)
6324 groups.append('0'*(l - len(digits)) + digits[-l:])
6325 return sep.join(reversed(groups))
6326
6327def _format_sign(is_negative, spec):
6328 """Determine sign character."""
6329
6330 if is_negative:
6331 return '-'
6332 elif spec['sign'] in ' +':
6333 return spec['sign']
6334 else:
6335 return ''
6336
6337def _format_number(is_negative, intpart, fracpart, exp, spec):
6338 """Format a number, given the following data:
6339
6340 is_negative: true if the number is negative, else false
6341 intpart: string of digits that must appear before the decimal point
6342 fracpart: string of digits that must come after the point
6343 exp: exponent, as an integer
6344 spec: dictionary resulting from parsing the format specifier
6345
6346 This function uses the information in spec to:
6347 insert separators (decimal separator and thousands separators)
6348 format the sign
6349 format the exponent
6350 add trailing '%' for the '%' type
6351 zero-pad if necessary
6352 fill and align if necessary
6353 """
6354
6355 sign = _format_sign(is_negative, spec)
6356
Eric Smith984bb582010-11-25 16:08:06 +00006357 if fracpart or spec['alt']:
Mark Dickinson79f52032009-03-17 23:12:51 +00006358 fracpart = spec['decimal_point'] + fracpart
6359
6360 if exp != 0 or spec['type'] in 'eE':
6361 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
6362 fracpart += "{0}{1:+}".format(echar, exp)
6363 if spec['type'] == '%':
6364 fracpart += '%'
6365
6366 if spec['zeropad']:
6367 min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
6368 else:
6369 min_width = 0
6370 intpart = _insert_thousands_sep(intpart, spec, min_width)
6371
6372 return _format_align(sign, intpart+fracpart, spec)
6373
6374
Guido van Rossumd8faa362007-04-27 19:54:29 +00006375##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006376
Guido van Rossumd8faa362007-04-27 19:54:29 +00006377# Reusable defaults
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006378_Infinity = Decimal('Inf')
6379_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonf9236412009-01-02 23:23:21 +00006380_NaN = Decimal('NaN')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006381_Zero = Decimal(0)
6382_One = Decimal(1)
6383_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006384
Mark Dickinson627cf6a2009-01-03 12:11:47 +00006385# _SignedInfinity[sign] is infinity w/ that sign
6386_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006387
Mark Dickinsondc787d22010-05-23 13:33:13 +00006388# Constants related to the hash implementation; hash(x) is based
6389# on the reduction of x modulo _PyHASH_MODULUS
Mark Dickinsondc787d22010-05-23 13:33:13 +00006390_PyHASH_MODULUS = sys.hash_info.modulus
6391# hash values to use for positive and negative infinities, and nans
6392_PyHASH_INF = sys.hash_info.inf
6393_PyHASH_NAN = sys.hash_info.nan
Mark Dickinsondc787d22010-05-23 13:33:13 +00006394
6395# _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS
6396_PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)
Stefan Krah1919b7e2012-03-21 18:25:23 +01006397del sys
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006398
Stefan Krah1919b7e2012-03-21 18:25:23 +01006399try:
6400 import _decimal
Brett Cannoncd171c82013-07-04 17:43:24 -04006401except ImportError:
Stefan Krah1919b7e2012-03-21 18:25:23 +01006402 pass
6403else:
6404 s1 = set(dir())
6405 s2 = set(dir(_decimal))
6406 for name in s1 - s2:
6407 del globals()[name]
6408 del s1, s2, name
6409 from _decimal import *
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006410
6411if __name__ == '__main__':
Raymond Hettinger6d7e26e2011-02-01 23:54:43 +00006412 import doctest, decimal
6413 doctest.testmod(decimal)