blob: 75a1d5ec3f06ad679d97e15d846c1f33d079c167 [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
Raymond Hettinger27dbcf22004-08-19 22:39:55 +000010# This module is currently Py2.3 compatible and should be kept that way
11# unless a major compelling advantage arises. IOW, 2.3 compatibility is
12# strongly preferred, but not guaranteed.
13
14# Also, this module should be kept in sync with the latest updates of
15# the IBM specification as it evolves. Those updates will be treated
16# as bug fixes (deviation from the spec is a compatibility, usability
17# bug) and will be backported. At this point the spec is stabilizing
18# and the updates are becoming fewer, smaller, and less significant.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000019
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000020"""
21This is a Py2.3 implementation of decimal floating point arithmetic based on
22the General Decimal Arithmetic Specification:
23
24 www2.hursley.ibm.com/decimal/decarith.html
25
Raymond Hettinger0ea241e2004-07-04 13:53:24 +000026and IEEE standard 854-1987:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000027
28 www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
29
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000030Decimal floating point has finite precision with arbitrarily large bounds.
31
Guido van Rossumd8faa362007-04-27 19:54:29 +000032The purpose of this module is to support arithmetic using familiar
33"schoolhouse" rules and to avoid some of the tricky representation
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000034issues associated with binary floating point. The package is especially
35useful for financial applications or for contexts where users have
36expectations that are at odds with binary floating point (for instance,
37in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
Christian Heimes68f5fbe2008-02-14 08:27:37 +000038of the expected Decimal('0.00') returned by decimal floating point).
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000039
40Here are some examples of using the decimal module:
41
42>>> from decimal import *
Raymond Hettingerbd7f76d2004-07-08 00:49:18 +000043>>> setcontext(ExtendedContext)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000044>>> Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000045Decimal('0')
46>>> Decimal('1')
47Decimal('1')
48>>> Decimal('-.0123')
49Decimal('-0.0123')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000050>>> Decimal(123456)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000051Decimal('123456')
52>>> Decimal('123.45e12345678901234567890')
53Decimal('1.2345E+12345678901234567892')
54>>> Decimal('1.33') + Decimal('1.27')
55Decimal('2.60')
56>>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
57Decimal('-2.20')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000058>>> dig = Decimal(1)
Guido van Rossum7131f842007-02-09 20:13:25 +000059>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000600.333333333
61>>> getcontext().prec = 18
Guido van Rossum7131f842007-02-09 20:13:25 +000062>>> print(dig / Decimal(3))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000630.333333333333333333
Guido van Rossum7131f842007-02-09 20:13:25 +000064>>> print(dig.sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000651
Guido van Rossum7131f842007-02-09 20:13:25 +000066>>> print(Decimal(3).sqrt())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000671.73205080756887729
Guido van Rossum7131f842007-02-09 20:13:25 +000068>>> print(Decimal(3) ** 123)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000694.85192780976896427E+58
70>>> inf = Decimal(1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000071>>> print(inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000072Infinity
73>>> neginf = Decimal(-1) / Decimal(0)
Guido van Rossum7131f842007-02-09 20:13:25 +000074>>> print(neginf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000075-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000076>>> print(neginf + inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000077NaN
Guido van Rossum7131f842007-02-09 20:13:25 +000078>>> print(neginf * inf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000079-Infinity
Guido van Rossum7131f842007-02-09 20:13:25 +000080>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000081Infinity
Raymond Hettingerbf440692004-07-10 14:14:37 +000082>>> getcontext().traps[DivisionByZero] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000083>>> print(dig / 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000084Traceback (most recent call last):
85 ...
86 ...
87 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +000088decimal.DivisionByZero: x / 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000089>>> c = Context()
Raymond Hettingerbf440692004-07-10 14:14:37 +000090>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000091>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000920
93>>> c.divide(Decimal(0), Decimal(0))
Christian Heimes68f5fbe2008-02-14 08:27:37 +000094Decimal('NaN')
Raymond Hettingerbf440692004-07-10 14:14:37 +000095>>> c.traps[InvalidOperation] = 1
Guido van Rossum7131f842007-02-09 20:13:25 +000096>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000098>>> c.flags[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +000099>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000
Guido van Rossum7131f842007-02-09 20:13:25 +0000101>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000102Traceback (most recent call last):
103 ...
104 ...
105 ...
Guido van Rossum6a2a2a02006-08-26 20:37:44 +0000106decimal.InvalidOperation: 0 / 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000107>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000109>>> c.flags[InvalidOperation] = 0
Raymond Hettingerbf440692004-07-10 14:14:37 +0000110>>> c.traps[InvalidOperation] = 0
Guido van Rossum7131f842007-02-09 20:13:25 +0000111>>> print(c.divide(Decimal(0), Decimal(0)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000112NaN
Guido van Rossum7131f842007-02-09 20:13:25 +0000113>>> print(c.flags[InvalidOperation])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141
115>>>
116"""
117
118__all__ = [
119 # Two major classes
120 'Decimal', 'Context',
121
122 # 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',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000128
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000129 # Constants for use in setting up contexts
130 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000131 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000132
133 # Functions for manipulating contexts
Thomas Wouters89f507f2006-12-13 04:49:30 +0000134 'setcontext', 'getcontext', 'localcontext'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000135]
136
Guido van Rossuma13f4a12007-12-10 20:04:04 +0000137import numbers as _numbers
Raymond Hettingereb260842005-06-07 18:52:34 +0000138import copy as _copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000139
Christian Heimes25bb7832008-01-11 16:17:00 +0000140try:
141 from collections import namedtuple as _namedtuple
142 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
143except ImportError:
144 DecimalTuple = lambda *args: args
145
Guido van Rossumd8faa362007-04-27 19:54:29 +0000146# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000147ROUND_DOWN = 'ROUND_DOWN'
148ROUND_HALF_UP = 'ROUND_HALF_UP'
149ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
150ROUND_CEILING = 'ROUND_CEILING'
151ROUND_FLOOR = 'ROUND_FLOOR'
152ROUND_UP = 'ROUND_UP'
153ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000154ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000155
Guido van Rossumd8faa362007-04-27 19:54:29 +0000156# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000157
158class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000159 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000160
161 Used exceptions derive from this.
162 If an exception derives from another exception besides this (such as
163 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
164 called if the others are present. This isn't actually used for
165 anything, though.
166
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000167 handle -- Called when context._raise_error is called and the
168 trap_enabler is set. First argument is self, second is the
169 context. More arguments can be given, those being after
170 the explanation in _raise_error (For example,
171 context._raise_error(NewError, '(-x)!', self._sign) would
172 call NewError().handle(context, self._sign).)
173
174 To define a new exception, it should be sufficient to have it derive
175 from DecimalException.
176 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000177 def handle(self, context, *args):
178 pass
179
180
181class Clamped(DecimalException):
182 """Exponent of a 0 changed to fit bounds.
183
184 This occurs and signals clamped if the exponent of a result has been
185 altered in order to fit the constraints of a specific concrete
Guido van Rossumd8faa362007-04-27 19:54:29 +0000186 representation. This may occur when the exponent of a zero result would
187 be outside the bounds of a representation, or when a large normal
188 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000189 this latter case, the exponent is reduced to fit and the corresponding
190 number of zero digits are appended to the coefficient ("fold-down").
191 """
192
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000193class InvalidOperation(DecimalException):
194 """An invalid operation was performed.
195
196 Various bad things cause this:
197
198 Something creates a signaling NaN
199 -INF + INF
Guido van Rossumd8faa362007-04-27 19:54:29 +0000200 0 * (+-)INF
201 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000202 x % 0
203 (+-)INF % x
204 x._rescale( non-integer )
205 sqrt(-x) , x > 0
206 0 ** 0
207 x ** (non-integer)
208 x ** (+-)INF
209 An operand is invalid
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000210
211 The result of the operation after these is a quiet positive NaN,
212 except when the cause is a signaling NaN, in which case the result is
213 also a quiet NaN, but with the original sign, and an optional
214 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000215 """
216 def handle(self, context, *args):
217 if args:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000218 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
219 return ans._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000220 return NaN
221
222class ConversionSyntax(InvalidOperation):
223 """Trying to convert badly formed string.
224
225 This occurs and signals invalid-operation if an string is being
226 converted to a number and it does not conform to the numeric string
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000228 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000229 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000230 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000231
232class DivisionByZero(DecimalException, ZeroDivisionError):
233 """Division by 0.
234
235 This occurs and signals division-by-zero if division of a finite number
236 by zero was attempted (during a divide-integer or divide operation, or a
237 power operation with negative right-hand operand), and the dividend was
238 not zero.
239
240 The result of the operation is [sign,inf], where sign is the exclusive
241 or of the signs of the operands for divide, or is 1 for an odd power of
242 -0, for power.
243 """
244
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000245 def handle(self, context, sign, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000246 return Infsign[sign]
247
248class DivisionImpossible(InvalidOperation):
249 """Cannot perform the division adequately.
250
251 This occurs and signals invalid-operation if the integer result of a
252 divide-integer or remainder operation had too many digits (would be
Guido van Rossumd8faa362007-04-27 19:54:29 +0000253 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000254 """
255
256 def handle(self, context, *args):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000257 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000258
259class DivisionUndefined(InvalidOperation, ZeroDivisionError):
260 """Undefined result of division.
261
262 This occurs and signals invalid-operation if division by zero was
263 attempted (during a divide-integer, divide, or remainder operation), and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000264 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000265 """
266
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000267 def handle(self, context, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000268 return NaN
269
270class Inexact(DecimalException):
271 """Had to round, losing information.
272
273 This occurs and signals inexact whenever the result of an operation is
274 not exact (that is, it needed to be rounded and any discarded digits
Guido van Rossumd8faa362007-04-27 19:54:29 +0000275 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000276 result in all cases is unchanged.
277
278 The inexact signal may be tested (or trapped) to determine if a given
279 operation (or sequence of operations) was inexact.
280 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000281
282class InvalidContext(InvalidOperation):
283 """Invalid context. Unknown rounding, for example.
284
285 This occurs and signals invalid-operation if an invalid context was
Guido van Rossumd8faa362007-04-27 19:54:29 +0000286 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000287 on creation and either the precision exceeds the capability of the
288 underlying concrete representation or an unknown or unsupported rounding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000289 was specified. These aspects of the context need only be checked when
290 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000291 """
292
293 def handle(self, context, *args):
294 return NaN
295
296class Rounded(DecimalException):
297 """Number got rounded (not necessarily changed during rounding).
298
299 This occurs and signals rounded whenever the result of an operation is
300 rounded (that is, some zero or non-zero digits were discarded from the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000301 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000302 result in all cases is unchanged.
303
304 The rounded signal may be tested (or trapped) to determine if a given
305 operation (or sequence of operations) caused a loss of precision.
306 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000307
308class Subnormal(DecimalException):
309 """Exponent < Emin before rounding.
310
311 This occurs and signals subnormal whenever the result of a conversion or
312 operation is subnormal (that is, its adjusted exponent is less than
Guido van Rossumd8faa362007-04-27 19:54:29 +0000313 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000314
315 The subnormal signal may be tested (or trapped) to determine if a given
316 or operation (or sequence of operations) yielded a subnormal result.
317 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000318
319class Overflow(Inexact, Rounded):
320 """Numerical overflow.
321
322 This occurs and signals overflow if the adjusted exponent of a result
323 (from a conversion or from an operation that is not an attempt to divide
324 by zero), after rounding, would be greater than the largest value that
325 can be handled by the implementation (the value Emax).
326
327 The result depends on the rounding mode:
328
329 For round-half-up and round-half-even (and for round-half-down and
330 round-up, if implemented), the result of the operation is [sign,inf],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000331 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000332 result is the largest finite number that can be represented in the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000333 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000334 round-ceiling, the result is the same as for round-down if the sign of
Guido van Rossumd8faa362007-04-27 19:54:29 +0000335 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000336 the result is the same as for round-down if the sign of the intermediate
Guido van Rossumd8faa362007-04-27 19:54:29 +0000337 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000338 will also be raised.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000339 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000340
341 def handle(self, context, sign, *args):
342 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000343 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000344 return Infsign[sign]
345 if sign == 0:
346 if context.rounding == ROUND_CEILING:
347 return Infsign[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000348 return _dec_from_triple(sign, '9'*context.prec,
349 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000350 if sign == 1:
351 if context.rounding == ROUND_FLOOR:
352 return Infsign[sign]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000353 return _dec_from_triple(sign, '9'*context.prec,
354 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000355
356
357class Underflow(Inexact, Rounded, Subnormal):
358 """Numerical underflow with result rounded to 0.
359
360 This occurs and signals underflow if a result is inexact and the
361 adjusted exponent of the result would be smaller (more negative) than
362 the smallest value that can be handled by the implementation (the value
Guido van Rossumd8faa362007-04-27 19:54:29 +0000363 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000364
365 The result after an underflow will be a subnormal number rounded, if
Guido van Rossumd8faa362007-04-27 19:54:29 +0000366 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000367 in 0 with the sign of the intermediate result and an exponent of Etiny.
368
369 In all cases, Inexact, Rounded, and Subnormal will also be raised.
370 """
371
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000372# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000373_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000374 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000375
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000376# Map conditions (per the spec) to signals
377_condition_map = {ConversionSyntax:InvalidOperation,
378 DivisionImpossible:InvalidOperation,
379 DivisionUndefined:InvalidOperation,
380 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000381
Guido van Rossumd8faa362007-04-27 19:54:29 +0000382##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000383
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000384# The getcontext() and setcontext() function manage access to a thread-local
385# current context. Py2.4 offers direct support for thread locals. If that
386# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000387# work for older Pythons. If threads are not part of the build, create a
388# mock threading object with threading.local() returning the module namespace.
389
390try:
391 import threading
392except ImportError:
393 # Python was compiled without threads; create a mock object instead
394 import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +0000395 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000396 def local(self, sys=sys):
397 return sys.modules[__name__]
398 threading = MockThreading()
399 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000400
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000401try:
402 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000403
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000404except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000405
Guido van Rossumd8faa362007-04-27 19:54:29 +0000406 # To fix reloading, force it to create a new context
407 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000408 if hasattr(threading.currentThread(), '__decimal_context__'):
409 del threading.currentThread().__decimal_context__
410
411 def setcontext(context):
412 """Set this thread's context to context."""
413 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000414 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000415 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000416 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000417
418 def getcontext():
419 """Returns this thread's context.
420
421 If this thread does not yet have a context, returns
422 a new context and sets this thread's context.
423 New contexts are copies of DefaultContext.
424 """
425 try:
426 return threading.currentThread().__decimal_context__
427 except AttributeError:
428 context = Context()
429 threading.currentThread().__decimal_context__ = context
430 return context
431
432else:
433
434 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000435 if hasattr(local, '__decimal_context__'):
436 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000437
438 def getcontext(_local=local):
439 """Returns this thread's context.
440
441 If this thread does not yet have a context, returns
442 a new context and sets this thread's context.
443 New contexts are copies of DefaultContext.
444 """
445 try:
446 return _local.__decimal_context__
447 except AttributeError:
448 context = Context()
449 _local.__decimal_context__ = context
450 return context
451
452 def setcontext(context, _local=local):
453 """Set this thread's context to context."""
454 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000455 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000456 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000457 _local.__decimal_context__ = context
458
459 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000460
Thomas Wouters89f507f2006-12-13 04:49:30 +0000461def localcontext(ctx=None):
462 """Return a context manager for a copy of the supplied context
463
464 Uses a copy of the current context if no context is specified
465 The returned context manager creates a local decimal context
466 in a with statement:
467 def sin(x):
468 with localcontext() as ctx:
469 ctx.prec += 2
470 # Rest of sin calculation algorithm
471 # uses a precision 2 greater than normal
Guido van Rossumd8faa362007-04-27 19:54:29 +0000472 return +s # Convert result to normal precision
Thomas Wouters89f507f2006-12-13 04:49:30 +0000473
474 def sin(x):
475 with localcontext(ExtendedContext):
476 # Rest of sin calculation algorithm
477 # uses the Extended Context from the
478 # General Decimal Arithmetic Specification
Guido van Rossumd8faa362007-04-27 19:54:29 +0000479 return +s # Convert result to normal context
Thomas Wouters89f507f2006-12-13 04:49:30 +0000480
481 """
482 # The string below can't be included in the docstring until Python 2.6
483 # as the doctest module doesn't understand __future__ statements
484 """
485 >>> from __future__ import with_statement
Guido van Rossum7131f842007-02-09 20:13:25 +0000486 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000487 28
488 >>> with localcontext():
489 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000490 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000491 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000492 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000493 30
494 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000495 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000496 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000497 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000498 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000499 28
500 """
501 if ctx is None: ctx = getcontext()
502 return _ContextManager(ctx)
503
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000504
Guido van Rossumd8faa362007-04-27 19:54:29 +0000505##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000506
Christian Heimes08976cb2008-03-16 00:32:36 +0000507class Decimal(_numbers.Real):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000508 """Floating point class for decimal arithmetic."""
509
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000510 __slots__ = ('_exp','_int','_sign', '_is_special')
511 # Generally, the value of the Decimal instance is given by
512 # (-1)**_sign * _int * 10**_exp
513 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000514
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000515 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000516 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000517 """Create a decimal point instance.
518
519 >>> Decimal('3.14') # string input
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000520 Decimal('3.14')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000521 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000522 Decimal('3.14')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000523 >>> Decimal(314) # int
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000524 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000525 >>> Decimal(Decimal(314)) # another decimal instance
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000526 Decimal('314')
Christian Heimesa62da1d2008-01-12 19:39:10 +0000527 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000528 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000529 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000530
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000531 # Note that the coefficient, self._int, is actually stored as
532 # a string rather than as a tuple of digits. This speeds up
533 # the "digits to integer" and "integer to digits" conversions
534 # that are used in almost every arithmetic operation on
535 # Decimals. This is an internal detail: the as_tuple function
536 # and the Decimal constructor still deal with tuples of
537 # digits.
538
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000539 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000540
Christian Heimesd59c64c2007-11-30 19:27:20 +0000541 # From a string
542 # REs insist on real strings, so we can too.
543 if isinstance(value, str):
Christian Heimesa62da1d2008-01-12 19:39:10 +0000544 m = _parser(value.strip())
Christian Heimesd59c64c2007-11-30 19:27:20 +0000545 if m is None:
546 if context is None:
547 context = getcontext()
548 return context._raise_error(ConversionSyntax,
549 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000550
Christian Heimesd59c64c2007-11-30 19:27:20 +0000551 if m.group('sign') == "-":
552 self._sign = 1
553 else:
554 self._sign = 0
555 intpart = m.group('int')
556 if intpart is not None:
557 # finite number
558 fracpart = m.group('frac')
559 exp = int(m.group('exp') or '0')
560 if fracpart is not None:
561 self._int = (intpart+fracpart).lstrip('0') or '0'
562 self._exp = exp - len(fracpart)
563 else:
564 self._int = intpart.lstrip('0') or '0'
565 self._exp = exp
566 self._is_special = False
567 else:
568 diag = m.group('diag')
569 if diag is not None:
570 # NaN
571 self._int = diag.lstrip('0')
572 if m.group('signal'):
573 self._exp = 'N'
574 else:
575 self._exp = 'n'
576 else:
577 # infinity
578 self._int = '0'
579 self._exp = 'F'
580 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000581 return self
582
583 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000584 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000585 if value >= 0:
586 self._sign = 0
587 else:
588 self._sign = 1
589 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000590 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000591 self._is_special = False
592 return self
593
594 # From another decimal
595 if isinstance(value, Decimal):
596 self._exp = value._exp
597 self._sign = value._sign
598 self._int = value._int
599 self._is_special = value._is_special
600 return self
601
602 # From an internal working value
603 if isinstance(value, _WorkRep):
604 self._sign = value.sign
605 self._int = str(value.int)
606 self._exp = int(value.exp)
607 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000608 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000609
610 # tuple/list conversion (possibly from as_tuple())
611 if isinstance(value, (list,tuple)):
612 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000613 raise ValueError('Invalid tuple size in creation of Decimal '
614 'from list or tuple. The list or tuple '
615 'should have exactly three elements.')
616 # process sign. The isinstance test rejects floats
617 if not (isinstance(value[0], int) and value[0] in (0,1)):
618 raise ValueError("Invalid sign. The first value in the tuple "
619 "should be an integer; either 0 for a "
620 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000621 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000622 if value[2] == 'F':
623 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000624 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000625 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000626 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000627 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000628 # process and validate the digits in value[1]
629 digits = []
630 for digit in value[1]:
631 if isinstance(digit, int) and 0 <= digit <= 9:
632 # skip leading zeros
633 if digits or digit != 0:
634 digits.append(digit)
635 else:
636 raise ValueError("The second value in the tuple must "
637 "be composed of integers in the range "
638 "0 through 9.")
639 if value[2] in ('n', 'N'):
640 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000641 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000642 self._exp = value[2]
643 self._is_special = True
644 elif isinstance(value[2], int):
645 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000646 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000647 self._exp = value[2]
648 self._is_special = False
649 else:
650 raise ValueError("The third value in the tuple must "
651 "be an integer, or one of the "
652 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000653 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000654
Raymond Hettingerbf440692004-07-10 14:14:37 +0000655 if isinstance(value, float):
656 raise TypeError("Cannot convert float to Decimal. " +
657 "First convert the float to a string")
658
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000659 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000660
661 def _isnan(self):
662 """Returns whether the number is not actually one.
663
664 0 if a number
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000665 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000666 2 if sNaN
667 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000668 if self._is_special:
669 exp = self._exp
670 if exp == 'n':
671 return 1
672 elif exp == 'N':
673 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000674 return 0
675
676 def _isinfinity(self):
677 """Returns whether the number is infinite
678
679 0 if finite or not a number
680 1 if +INF
681 -1 if -INF
682 """
683 if self._exp == 'F':
684 if self._sign:
685 return -1
686 return 1
687 return 0
688
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000689 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000690 """Returns whether the number is not actually one.
691
692 if self, other are sNaN, signal
693 if self, other are NaN return nan
694 return 0
695
696 Done before operations.
697 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000698
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000699 self_is_nan = self._isnan()
700 if other is None:
701 other_is_nan = False
702 else:
703 other_is_nan = other._isnan()
704
705 if self_is_nan or other_is_nan:
706 if context is None:
707 context = getcontext()
708
709 if self_is_nan == 2:
710 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000711 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000712 if other_is_nan == 2:
713 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000714 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000715 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000716 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000717
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000718 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000719 return 0
720
Christian Heimes77c02eb2008-02-09 02:18:51 +0000721 def _compare_check_nans(self, other, context):
722 """Version of _check_nans used for the signaling comparisons
723 compare_signal, __le__, __lt__, __ge__, __gt__.
724
725 Signal InvalidOperation if either self or other is a (quiet
726 or signaling) NaN. Signaling NaNs take precedence over quiet
727 NaNs.
728
729 Return 0 if neither operand is a NaN.
730
731 """
732 if context is None:
733 context = getcontext()
734
735 if self._is_special or other._is_special:
736 if self.is_snan():
737 return context._raise_error(InvalidOperation,
738 'comparison involving sNaN',
739 self)
740 elif other.is_snan():
741 return context._raise_error(InvalidOperation,
742 'comparison involving sNaN',
743 other)
744 elif self.is_qnan():
745 return context._raise_error(InvalidOperation,
746 'comparison involving NaN',
747 self)
748 elif other.is_qnan():
749 return context._raise_error(InvalidOperation,
750 'comparison involving NaN',
751 other)
752 return 0
753
Jack Diederich4dafcc42006-11-28 19:15:13 +0000754 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000755 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000756
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000757 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000758 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000759 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000760
Christian Heimes77c02eb2008-02-09 02:18:51 +0000761 def _cmp(self, other):
762 """Compare the two non-NaN decimal instances self and other.
763
764 Returns -1 if self < other, 0 if self == other and 1
765 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000766
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000767 if self._is_special or other._is_special:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000768 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000769
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000770 # check for zeros; note that cmp(0, -0) should return 0
771 if not self:
772 if not other:
773 return 0
774 else:
775 return -((-1)**other._sign)
776 if not other:
777 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000778
Guido van Rossumd8faa362007-04-27 19:54:29 +0000779 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000780 if other._sign < self._sign:
781 return -1
782 if self._sign < other._sign:
783 return 1
784
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000785 self_adjusted = self.adjusted()
786 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000787 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000788 self_padded = self._int + '0'*(self._exp - other._exp)
789 other_padded = other._int + '0'*(other._exp - self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000790 return cmp(self_padded, other_padded) * (-1)**self._sign
791 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000792 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000793 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000794 return -((-1)**self._sign)
795
Christian Heimes77c02eb2008-02-09 02:18:51 +0000796 # Note: The Decimal standard doesn't cover rich comparisons for
797 # Decimals. In particular, the specification is silent on the
798 # subject of what should happen for a comparison involving a NaN.
799 # We take the following approach:
800 #
801 # == comparisons involving a NaN always return False
802 # != comparisons involving a NaN always return True
803 # <, >, <= and >= comparisons involving a (quiet or signaling)
804 # NaN signal InvalidOperation, and return False if the
Christian Heimes3feef612008-02-11 06:19:17 +0000805 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000806 #
807 # This behavior is designed to conform as closely as possible to
808 # that specified by IEEE 754.
809
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000810 def __eq__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000811 other = _convert_other(other)
812 if other is NotImplemented:
813 return other
814 if self.is_nan() or other.is_nan():
815 return False
816 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000817
818 def __ne__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000819 other = _convert_other(other)
820 if other is NotImplemented:
821 return other
822 if self.is_nan() or other.is_nan():
823 return True
824 return self._cmp(other) != 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000825
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000826
Christian Heimes77c02eb2008-02-09 02:18:51 +0000827 def __lt__(self, other, context=None):
828 other = _convert_other(other)
829 if other is NotImplemented:
830 return other
831 ans = self._compare_check_nans(other, context)
832 if ans:
833 return False
834 return self._cmp(other) < 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000835
Christian Heimes77c02eb2008-02-09 02:18:51 +0000836 def __le__(self, other, context=None):
837 other = _convert_other(other)
838 if other is NotImplemented:
839 return other
840 ans = self._compare_check_nans(other, context)
841 if ans:
842 return False
843 return self._cmp(other) <= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000844
Christian Heimes77c02eb2008-02-09 02:18:51 +0000845 def __gt__(self, other, context=None):
846 other = _convert_other(other)
847 if other is NotImplemented:
848 return other
849 ans = self._compare_check_nans(other, context)
850 if ans:
851 return False
852 return self._cmp(other) > 0
853
854 def __ge__(self, other, context=None):
855 other = _convert_other(other)
856 if other is NotImplemented:
857 return other
858 ans = self._compare_check_nans(other, context)
859 if ans:
860 return False
861 return self._cmp(other) >= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000862
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000863 def compare(self, other, context=None):
864 """Compares one to another.
865
866 -1 => a < b
867 0 => a = b
868 1 => a > b
869 NaN => one is NaN
870 Like __cmp__, but returns Decimal instances.
871 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000872 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000873
Guido van Rossumd8faa362007-04-27 19:54:29 +0000874 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000875 if (self._is_special or other and other._is_special):
876 ans = self._check_nans(other, context)
877 if ans:
878 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000879
Christian Heimes77c02eb2008-02-09 02:18:51 +0000880 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000881
882 def __hash__(self):
883 """x.__hash__() <==> hash(x)"""
884 # Decimal integers must hash the same as the ints
Christian Heimes2380ac72008-01-09 00:17:24 +0000885 #
886 # The hash of a nonspecial noninteger Decimal must depend only
887 # on the value of that Decimal, and not on its representation.
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000888 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000889 if self._is_special:
890 if self._isnan():
891 raise TypeError('Cannot hash a NaN value.')
892 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000893 if not self:
894 return 0
895 if self._isinteger():
896 op = _WorkRep(self.to_integral_value())
897 # to make computation feasible for Decimals with large
898 # exponent, we use the fact that hash(n) == hash(m) for
899 # any two nonzero integers n and m such that (i) n and m
900 # have the same sign, and (ii) n is congruent to m modulo
901 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
902 # hash((-1)**s*c*pow(10, e, 2**64-1).
903 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Christian Heimes2380ac72008-01-09 00:17:24 +0000904 # The value of a nonzero nonspecial Decimal instance is
905 # faithfully represented by the triple consisting of its sign,
906 # its adjusted exponent, and its coefficient with trailing
907 # zeros removed.
908 return hash((self._sign,
909 self._exp+len(self._int),
910 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000911
912 def as_tuple(self):
913 """Represents the number as a triple tuple.
914
915 To show the internals exactly as they are.
916 """
Christian Heimes25bb7832008-01-11 16:17:00 +0000917 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000918
919 def __repr__(self):
920 """Represents the number as an instance of Decimal."""
921 # Invariant: eval(repr(d)) == d
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000922 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000923
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000924 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000925 """Return string representation of the number in scientific notation.
926
927 Captures all of the information in the underlying representation.
928 """
929
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000930 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000931 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000932 if self._exp == 'F':
933 return sign + 'Infinity'
934 elif self._exp == 'n':
935 return sign + 'NaN' + self._int
936 else: # self._exp == 'N'
937 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000938
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000939 # number of digits of self._int to left of decimal point
940 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000941
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000942 # dotplace is number of digits of self._int to the left of the
943 # decimal point in the mantissa of the output string (that is,
944 # after adjusting the exponent)
945 if self._exp <= 0 and leftdigits > -6:
946 # no exponent required
947 dotplace = leftdigits
948 elif not eng:
949 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000950 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000951 elif self._int == '0':
952 # engineering notation, zero
953 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000954 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000955 # engineering notation, nonzero
956 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000957
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000958 if dotplace <= 0:
959 intpart = '0'
960 fracpart = '.' + '0'*(-dotplace) + self._int
961 elif dotplace >= len(self._int):
962 intpart = self._int+'0'*(dotplace-len(self._int))
963 fracpart = ''
964 else:
965 intpart = self._int[:dotplace]
966 fracpart = '.' + self._int[dotplace:]
967 if leftdigits == dotplace:
968 exp = ''
969 else:
970 if context is None:
971 context = getcontext()
972 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
973
974 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000975
976 def to_eng_string(self, context=None):
977 """Convert to engineering-type string.
978
979 Engineering notation has an exponent which is a multiple of 3, so there
980 are up to 3 digits left of the decimal place.
981
982 Same rules for when in exponential and when as a value as in __str__.
983 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000984 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000985
986 def __neg__(self, context=None):
987 """Returns a copy with the sign switched.
988
989 Rounds, if it has reason.
990 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000991 if self._is_special:
992 ans = self._check_nans(context=context)
993 if ans:
994 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000995
996 if not self:
997 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000998 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000999 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001000 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001001
1002 if context is None:
1003 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001004 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001005
1006 def __pos__(self, context=None):
1007 """Returns a copy, unless it is a sNaN.
1008
1009 Rounds the number (if more then precision digits)
1010 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001011 if self._is_special:
1012 ans = self._check_nans(context=context)
1013 if ans:
1014 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001015
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001016 if not self:
1017 # + (-0) = 0
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001018 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001019 else:
1020 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001021
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001022 if context is None:
1023 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001024 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001025
Christian Heimes2c181612007-12-17 20:04:13 +00001026 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001027 """Returns the absolute value of self.
1028
Christian Heimes2c181612007-12-17 20:04:13 +00001029 If the keyword argument 'round' is false, do not round. The
1030 expression self.__abs__(round=False) is equivalent to
1031 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001032 """
Christian Heimes2c181612007-12-17 20:04:13 +00001033 if not round:
1034 return self.copy_abs()
1035
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001036 if self._is_special:
1037 ans = self._check_nans(context=context)
1038 if ans:
1039 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001040
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001041 if self._sign:
1042 ans = self.__neg__(context=context)
1043 else:
1044 ans = self.__pos__(context=context)
1045
1046 return ans
1047
1048 def __add__(self, other, context=None):
1049 """Returns self + other.
1050
1051 -INF + INF (or the reverse) cause InvalidOperation errors.
1052 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001053 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001054 if other is NotImplemented:
1055 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001056
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001057 if context is None:
1058 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001059
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001060 if self._is_special or other._is_special:
1061 ans = self._check_nans(other, context)
1062 if ans:
1063 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001064
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001065 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001066 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001067 if self._sign != other._sign and other._isinfinity():
1068 return context._raise_error(InvalidOperation, '-INF + INF')
1069 return Decimal(self)
1070 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001071 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001072
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001073 exp = min(self._exp, other._exp)
1074 negativezero = 0
1075 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001076 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001077 negativezero = 1
1078
1079 if not self and not other:
1080 sign = min(self._sign, other._sign)
1081 if negativezero:
1082 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001083 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001084 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001085 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001086 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001087 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001088 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001089 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001090 return ans
1091 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001092 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001093 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001094 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001095 return ans
1096
1097 op1 = _WorkRep(self)
1098 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001099 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001100
1101 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001102 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001103 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001104 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001105 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001106 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001107 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001108 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001109 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001110 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001111 if op1.sign == 1:
1112 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001113 op1.sign, op2.sign = op2.sign, op1.sign
1114 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001115 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001116 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001117 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001118 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001119 op1.sign, op2.sign = (0, 0)
1120 else:
1121 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001122 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001123
Raymond Hettinger17931de2004-10-27 06:21:46 +00001124 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001125 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001126 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001127 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001128
1129 result.exp = op1.exp
1130 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001131 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001132 return ans
1133
1134 __radd__ = __add__
1135
1136 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001137 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001138 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001139 if other is NotImplemented:
1140 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001142 if self._is_special or other._is_special:
1143 ans = self._check_nans(other, context=context)
1144 if ans:
1145 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001146
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001147 # self - other is computed as self + other.copy_negate()
1148 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001149
1150 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001151 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001152 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001153 if other is NotImplemented:
1154 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001155
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001156 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001157
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001158 def __mul__(self, other, context=None):
1159 """Return self * other.
1160
1161 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1162 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001163 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001164 if other is NotImplemented:
1165 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001166
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001167 if context is None:
1168 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001169
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001170 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001171
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001172 if self._is_special or other._is_special:
1173 ans = self._check_nans(other, context)
1174 if ans:
1175 return ans
1176
1177 if self._isinfinity():
1178 if not other:
1179 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1180 return Infsign[resultsign]
1181
1182 if other._isinfinity():
1183 if not self:
1184 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1185 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001186
1187 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001188
1189 # Special case for multiplying by zero
1190 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001191 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001192 # Fixing in case the exponent is out of bounds
1193 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001194 return ans
1195
1196 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001197 if self._int == '1':
1198 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001199 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001200 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001201 if other._int == '1':
1202 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001203 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001204 return ans
1205
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001206 op1 = _WorkRep(self)
1207 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001208
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001209 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001210 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001211
1212 return ans
1213 __rmul__ = __mul__
1214
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001215 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001216 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001217 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001218 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001219 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001220
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001221 if context is None:
1222 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001223
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001224 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001225
1226 if self._is_special or other._is_special:
1227 ans = self._check_nans(other, context)
1228 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001229 return ans
1230
1231 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001232 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001233
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001234 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001235 return Infsign[sign]
1236
1237 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001238 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001239 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001240
1241 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001242 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001243 if not self:
1244 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001245 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001246
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001247 if not self:
1248 exp = self._exp - other._exp
1249 coeff = 0
1250 else:
1251 # OK, so neither = 0, INF or NaN
1252 shift = len(other._int) - len(self._int) + context.prec + 1
1253 exp = self._exp - other._exp - shift
1254 op1 = _WorkRep(self)
1255 op2 = _WorkRep(other)
1256 if shift >= 0:
1257 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1258 else:
1259 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1260 if remainder:
1261 # result is not exact; adjust to ensure correct rounding
1262 if coeff % 5 == 0:
1263 coeff += 1
1264 else:
1265 # result is exact; get as close to ideal exponent as possible
1266 ideal_exp = self._exp - other._exp
1267 while exp < ideal_exp and coeff % 10 == 0:
1268 coeff //= 10
1269 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001270
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001271 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001272 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001273
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001274 def _divide(self, other, context):
1275 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001276
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001277 Assumes that neither self nor other is a NaN, that self is not
1278 infinite and that other is nonzero.
1279 """
1280 sign = self._sign ^ other._sign
1281 if other._isinfinity():
1282 ideal_exp = self._exp
1283 else:
1284 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001285
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001286 expdiff = self.adjusted() - other.adjusted()
1287 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001288 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001289 self._rescale(ideal_exp, context.rounding))
1290 if expdiff <= context.prec:
1291 op1 = _WorkRep(self)
1292 op2 = _WorkRep(other)
1293 if op1.exp >= op2.exp:
1294 op1.int *= 10**(op1.exp - op2.exp)
1295 else:
1296 op2.int *= 10**(op2.exp - op1.exp)
1297 q, r = divmod(op1.int, op2.int)
1298 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001299 return (_dec_from_triple(sign, str(q), 0),
1300 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001301
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001302 # Here the quotient is too large to be representable
1303 ans = context._raise_error(DivisionImpossible,
1304 'quotient too large in //, % or divmod')
1305 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001306
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001307 def __rtruediv__(self, other, context=None):
1308 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001309 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001310 if other is NotImplemented:
1311 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001312 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001313
1314 def __divmod__(self, other, context=None):
1315 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001316 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001317 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001318 other = _convert_other(other)
1319 if other is NotImplemented:
1320 return other
1321
1322 if context is None:
1323 context = getcontext()
1324
1325 ans = self._check_nans(other, context)
1326 if ans:
1327 return (ans, ans)
1328
1329 sign = self._sign ^ other._sign
1330 if self._isinfinity():
1331 if other._isinfinity():
1332 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1333 return ans, ans
1334 else:
1335 return (Infsign[sign],
1336 context._raise_error(InvalidOperation, 'INF % x'))
1337
1338 if not other:
1339 if not self:
1340 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1341 return ans, ans
1342 else:
1343 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1344 context._raise_error(InvalidOperation, 'x % 0'))
1345
1346 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001347 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001348 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001349
1350 def __rdivmod__(self, other, context=None):
1351 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001352 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001353 if other is NotImplemented:
1354 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001355 return other.__divmod__(self, context=context)
1356
1357 def __mod__(self, other, context=None):
1358 """
1359 self % other
1360 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001361 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001362 if other is NotImplemented:
1363 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001364
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001365 if context is None:
1366 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001367
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001368 ans = self._check_nans(other, context)
1369 if ans:
1370 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001371
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001372 if self._isinfinity():
1373 return context._raise_error(InvalidOperation, 'INF % x')
1374 elif not other:
1375 if self:
1376 return context._raise_error(InvalidOperation, 'x % 0')
1377 else:
1378 return context._raise_error(DivisionUndefined, '0 % 0')
1379
1380 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001381 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001382 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001383
1384 def __rmod__(self, other, context=None):
1385 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001386 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001387 if other is NotImplemented:
1388 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001389 return other.__mod__(self, context=context)
1390
1391 def remainder_near(self, other, context=None):
1392 """
1393 Remainder nearest to 0- abs(remainder-near) <= other/2
1394 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001395 if context is None:
1396 context = getcontext()
1397
1398 other = _convert_other(other, raiseit=True)
1399
1400 ans = self._check_nans(other, context)
1401 if ans:
1402 return ans
1403
1404 # self == +/-infinity -> InvalidOperation
1405 if self._isinfinity():
1406 return context._raise_error(InvalidOperation,
1407 'remainder_near(infinity, x)')
1408
1409 # other == 0 -> either InvalidOperation or DivisionUndefined
1410 if not other:
1411 if self:
1412 return context._raise_error(InvalidOperation,
1413 'remainder_near(x, 0)')
1414 else:
1415 return context._raise_error(DivisionUndefined,
1416 'remainder_near(0, 0)')
1417
1418 # other = +/-infinity -> remainder = self
1419 if other._isinfinity():
1420 ans = Decimal(self)
1421 return ans._fix(context)
1422
1423 # self = 0 -> remainder = self, with ideal exponent
1424 ideal_exponent = min(self._exp, other._exp)
1425 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001426 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001427 return ans._fix(context)
1428
1429 # catch most cases of large or small quotient
1430 expdiff = self.adjusted() - other.adjusted()
1431 if expdiff >= context.prec + 1:
1432 # expdiff >= prec+1 => abs(self/other) > 10**prec
1433 return context._raise_error(DivisionImpossible)
1434 if expdiff <= -2:
1435 # expdiff <= -2 => abs(self/other) < 0.1
1436 ans = self._rescale(ideal_exponent, context.rounding)
1437 return ans._fix(context)
1438
1439 # adjust both arguments to have the same exponent, then divide
1440 op1 = _WorkRep(self)
1441 op2 = _WorkRep(other)
1442 if op1.exp >= op2.exp:
1443 op1.int *= 10**(op1.exp - op2.exp)
1444 else:
1445 op2.int *= 10**(op2.exp - op1.exp)
1446 q, r = divmod(op1.int, op2.int)
1447 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1448 # 10**ideal_exponent. Apply correction to ensure that
1449 # abs(remainder) <= abs(other)/2
1450 if 2*r + (q&1) > op2.int:
1451 r -= op2.int
1452 q += 1
1453
1454 if q >= 10**context.prec:
1455 return context._raise_error(DivisionImpossible)
1456
1457 # result has same sign as self unless r is negative
1458 sign = self._sign
1459 if r < 0:
1460 sign = 1-sign
1461 r = -r
1462
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001463 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001464 return ans._fix(context)
1465
1466 def __floordiv__(self, other, context=None):
1467 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001468 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001469 if other is NotImplemented:
1470 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001471
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001472 if context is None:
1473 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001474
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001475 ans = self._check_nans(other, context)
1476 if ans:
1477 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001478
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001479 if self._isinfinity():
1480 if other._isinfinity():
1481 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001482 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001483 return Infsign[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001484
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001485 if not other:
1486 if self:
1487 return context._raise_error(DivisionByZero, 'x // 0',
1488 self._sign ^ other._sign)
1489 else:
1490 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001491
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001492 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001493
1494 def __rfloordiv__(self, other, context=None):
1495 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001496 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001497 if other is NotImplemented:
1498 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001499 return other.__floordiv__(self, context=context)
1500
1501 def __float__(self):
1502 """Float representation."""
1503 return float(str(self))
1504
1505 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001506 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001507 if self._is_special:
1508 if self._isnan():
1509 context = getcontext()
1510 return context._raise_error(InvalidContext)
1511 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001512 raise OverflowError("Cannot convert infinity to int")
1513 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001514 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001515 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001516 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001517 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001518
Christian Heimes969fe572008-01-25 11:23:10 +00001519 __trunc__ = __int__
1520
Christian Heimes0bd4e112008-02-12 22:59:25 +00001521 @property
1522 def real(self):
1523 return self
1524
1525 @property
1526 def imag(self):
1527 return Decimal(0)
1528
1529 def conjugate(self):
1530 return self
1531
1532 def __complex__(self):
1533 return complex(float(self))
1534
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001535 def _fix_nan(self, context):
1536 """Decapitate the payload of a NaN to fit the context"""
1537 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001538
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001539 # maximum length of payload is precision if _clamp=0,
1540 # precision-1 if _clamp=1.
1541 max_payload_len = context.prec - context._clamp
1542 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001543 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1544 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001545 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001546
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001547 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001548 """Round if it is necessary to keep self within prec precision.
1549
1550 Rounds and fixes the exponent. Does not raise on a sNaN.
1551
1552 Arguments:
1553 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001554 context - context used.
1555 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001556
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001557 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001558 if self._isnan():
1559 # decapitate payload if necessary
1560 return self._fix_nan(context)
1561 else:
1562 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001563 return Decimal(self)
1564
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001565 # if self is zero then exponent should be between Etiny and
1566 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1567 Etiny = context.Etiny()
1568 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001569 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001570 exp_max = [context.Emax, Etop][context._clamp]
1571 new_exp = min(max(self._exp, Etiny), exp_max)
1572 if new_exp != self._exp:
1573 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001574 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001575 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001576 return Decimal(self)
1577
1578 # exp_min is the smallest allowable exponent of the result,
1579 # equal to max(self.adjusted()-context.prec+1, Etiny)
1580 exp_min = len(self._int) + self._exp - context.prec
1581 if exp_min > Etop:
1582 # overflow: exp_min > Etop iff self.adjusted() > Emax
1583 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001584 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001585 return context._raise_error(Overflow, 'above Emax', self._sign)
1586 self_is_subnormal = exp_min < Etiny
1587 if self_is_subnormal:
1588 context._raise_error(Subnormal)
1589 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001590
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001591 # round if self has too many digits
1592 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001593 context._raise_error(Rounded)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001594 digits = len(self._int) + self._exp - exp_min
1595 if digits < 0:
1596 self = _dec_from_triple(self._sign, '1', exp_min-1)
1597 digits = 0
1598 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1599 changed = this_function(digits)
1600 coeff = self._int[:digits] or '0'
1601 if changed == 1:
1602 coeff = str(int(coeff)+1)
1603 ans = _dec_from_triple(self._sign, coeff, exp_min)
1604
1605 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001606 context._raise_error(Inexact)
1607 if self_is_subnormal:
1608 context._raise_error(Underflow)
1609 if not ans:
1610 # raise Clamped on underflow to 0
1611 context._raise_error(Clamped)
1612 elif len(ans._int) == context.prec+1:
1613 # we get here only if rescaling rounds the
1614 # cofficient up to exactly 10**context.prec
1615 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001616 ans = _dec_from_triple(ans._sign,
1617 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001618 else:
1619 # Inexact and Rounded have already been raised
1620 ans = context._raise_error(Overflow, 'above Emax',
1621 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001622 return ans
1623
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001624 # fold down if _clamp == 1 and self has too few digits
1625 if context._clamp == 1 and self._exp > Etop:
1626 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001627 self_padded = self._int + '0'*(self._exp - Etop)
1628 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001629
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001630 # here self was representable to begin with; return unchanged
1631 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001632
1633 _pick_rounding_function = {}
1634
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001635 # for each of the rounding functions below:
1636 # self is a finite, nonzero Decimal
1637 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001638 #
1639 # each function returns either -1, 0, or 1, as follows:
1640 # 1 indicates that self should be rounded up (away from zero)
1641 # 0 indicates that self should be truncated, and that all the
1642 # digits to be truncated are zeros (so the value is unchanged)
1643 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001644
1645 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001646 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001647 if _all_zeros(self._int, prec):
1648 return 0
1649 else:
1650 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001651
Christian Heimes9e7f1d22008-02-28 12:27:11 +00001652 def __round__(self):
1653 return self._round_down(0)
1654
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001655 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001656 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001657 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001658
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001659 def _round_half_up(self, prec):
1660 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001661 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001662 return 1
1663 elif _all_zeros(self._int, prec):
1664 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001665 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001666 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001667
1668 def _round_half_down(self, prec):
1669 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001670 if _exact_half(self._int, prec):
1671 return -1
1672 else:
1673 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001674
1675 def _round_half_even(self, prec):
1676 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001677 if _exact_half(self._int, prec) and \
1678 (prec == 0 or self._int[prec-1] in '02468'):
1679 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001680 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001681 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001682
1683 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001684 """Rounds up (not away from 0 if negative.)"""
1685 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001686 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001687 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001688 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001689
Christian Heimes9e7f1d22008-02-28 12:27:11 +00001690 def __ceil__(self):
1691 return self._round_ceiling(0)
1692
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001693 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001694 """Rounds down (not towards 0 if negative)"""
1695 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001696 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001697 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001698 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001699
Christian Heimes9e7f1d22008-02-28 12:27:11 +00001700 def __floor__(self):
1701 return self._round_floor(0)
1702
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001703 def _round_05up(self, prec):
1704 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001705 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001706 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001707 else:
1708 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001709
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001710 def fma(self, other, third, context=None):
1711 """Fused multiply-add.
1712
1713 Returns self*other+third with no rounding of the intermediate
1714 product self*other.
1715
1716 self and other are multiplied together, with no rounding of
1717 the result. The third operand is then added to the result,
1718 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001719 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001720
1721 other = _convert_other(other, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001722
1723 # compute product; raise InvalidOperation if either operand is
1724 # a signaling NaN or if the product is zero times infinity.
1725 if self._is_special or other._is_special:
1726 if context is None:
1727 context = getcontext()
1728 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001729 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001730 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001731 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001732 if self._exp == 'n':
1733 product = self
1734 elif other._exp == 'n':
1735 product = other
1736 elif self._exp == 'F':
1737 if not other:
1738 return context._raise_error(InvalidOperation,
1739 'INF * 0 in fma')
1740 product = Infsign[self._sign ^ other._sign]
1741 elif other._exp == 'F':
1742 if not self:
1743 return context._raise_error(InvalidOperation,
1744 '0 * INF in fma')
1745 product = Infsign[self._sign ^ other._sign]
1746 else:
1747 product = _dec_from_triple(self._sign ^ other._sign,
1748 str(int(self._int) * int(other._int)),
1749 self._exp + other._exp)
1750
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001751 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001752 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001753
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001754 def _power_modulo(self, other, modulo, context=None):
1755 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001756
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001757 # if can't convert other and modulo to Decimal, raise
1758 # TypeError; there's no point returning NotImplemented (no
1759 # equivalent of __rpow__ for three argument pow)
1760 other = _convert_other(other, raiseit=True)
1761 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001762
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001763 if context is None:
1764 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001765
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001766 # deal with NaNs: if there are any sNaNs then first one wins,
1767 # (i.e. behaviour for NaNs is identical to that of fma)
1768 self_is_nan = self._isnan()
1769 other_is_nan = other._isnan()
1770 modulo_is_nan = modulo._isnan()
1771 if self_is_nan or other_is_nan or modulo_is_nan:
1772 if self_is_nan == 2:
1773 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001774 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001775 if other_is_nan == 2:
1776 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001777 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001778 if modulo_is_nan == 2:
1779 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001780 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001781 if self_is_nan:
1782 return self._fix_nan(context)
1783 if other_is_nan:
1784 return other._fix_nan(context)
1785 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001786
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001787 # check inputs: we apply same restrictions as Python's pow()
1788 if not (self._isinteger() and
1789 other._isinteger() and
1790 modulo._isinteger()):
1791 return context._raise_error(InvalidOperation,
1792 'pow() 3rd argument not allowed '
1793 'unless all arguments are integers')
1794 if other < 0:
1795 return context._raise_error(InvalidOperation,
1796 'pow() 2nd argument cannot be '
1797 'negative when 3rd argument specified')
1798 if not modulo:
1799 return context._raise_error(InvalidOperation,
1800 'pow() 3rd argument cannot be 0')
1801
1802 # additional restriction for decimal: the modulus must be less
1803 # than 10**prec in absolute value
1804 if modulo.adjusted() >= context.prec:
1805 return context._raise_error(InvalidOperation,
1806 'insufficient precision: pow() 3rd '
1807 'argument must not have more than '
1808 'precision digits')
1809
1810 # define 0**0 == NaN, for consistency with two-argument pow
1811 # (even though it hurts!)
1812 if not other and not self:
1813 return context._raise_error(InvalidOperation,
1814 'at least one of pow() 1st argument '
1815 'and 2nd argument must be nonzero ;'
1816 '0**0 is not defined')
1817
1818 # compute sign of result
1819 if other._iseven():
1820 sign = 0
1821 else:
1822 sign = self._sign
1823
1824 # convert modulo to a Python integer, and self and other to
1825 # Decimal integers (i.e. force their exponents to be >= 0)
1826 modulo = abs(int(modulo))
1827 base = _WorkRep(self.to_integral_value())
1828 exponent = _WorkRep(other.to_integral_value())
1829
1830 # compute result using integer pow()
1831 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1832 for i in range(exponent.exp):
1833 base = pow(base, 10, modulo)
1834 base = pow(base, exponent.int, modulo)
1835
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001836 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001837
1838 def _power_exact(self, other, p):
1839 """Attempt to compute self**other exactly.
1840
1841 Given Decimals self and other and an integer p, attempt to
1842 compute an exact result for the power self**other, with p
1843 digits of precision. Return None if self**other is not
1844 exactly representable in p digits.
1845
1846 Assumes that elimination of special cases has already been
1847 performed: self and other must both be nonspecial; self must
1848 be positive and not numerically equal to 1; other must be
1849 nonzero. For efficiency, other._exp should not be too large,
1850 so that 10**abs(other._exp) is a feasible calculation."""
1851
1852 # In the comments below, we write x for the value of self and
1853 # y for the value of other. Write x = xc*10**xe and y =
1854 # yc*10**ye.
1855
1856 # The main purpose of this method is to identify the *failure*
1857 # of x**y to be exactly representable with as little effort as
1858 # possible. So we look for cheap and easy tests that
1859 # eliminate the possibility of x**y being exact. Only if all
1860 # these tests are passed do we go on to actually compute x**y.
1861
1862 # Here's the main idea. First normalize both x and y. We
1863 # express y as a rational m/n, with m and n relatively prime
1864 # and n>0. Then for x**y to be exactly representable (at
1865 # *any* precision), xc must be the nth power of a positive
1866 # integer and xe must be divisible by n. If m is negative
1867 # then additionally xc must be a power of either 2 or 5, hence
1868 # a power of 2**n or 5**n.
1869 #
1870 # There's a limit to how small |y| can be: if y=m/n as above
1871 # then:
1872 #
1873 # (1) if xc != 1 then for the result to be representable we
1874 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1875 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1876 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1877 # representable.
1878 #
1879 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1880 # |y| < 1/|xe| then the result is not representable.
1881 #
1882 # Note that since x is not equal to 1, at least one of (1) and
1883 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1884 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1885 #
1886 # There's also a limit to how large y can be, at least if it's
1887 # positive: the normalized result will have coefficient xc**y,
1888 # so if it's representable then xc**y < 10**p, and y <
1889 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1890 # not exactly representable.
1891
1892 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1893 # so |y| < 1/xe and the result is not representable.
1894 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1895 # < 1/nbits(xc).
1896
1897 x = _WorkRep(self)
1898 xc, xe = x.int, x.exp
1899 while xc % 10 == 0:
1900 xc //= 10
1901 xe += 1
1902
1903 y = _WorkRep(other)
1904 yc, ye = y.int, y.exp
1905 while yc % 10 == 0:
1906 yc //= 10
1907 ye += 1
1908
1909 # case where xc == 1: result is 10**(xe*y), with xe*y
1910 # required to be an integer
1911 if xc == 1:
1912 if ye >= 0:
1913 exponent = xe*yc*10**ye
1914 else:
1915 exponent, remainder = divmod(xe*yc, 10**-ye)
1916 if remainder:
1917 return None
1918 if y.sign == 1:
1919 exponent = -exponent
1920 # if other is a nonnegative integer, use ideal exponent
1921 if other._isinteger() and other._sign == 0:
1922 ideal_exponent = self._exp*int(other)
1923 zeros = min(exponent-ideal_exponent, p-1)
1924 else:
1925 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001926 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001927
1928 # case where y is negative: xc must be either a power
1929 # of 2 or a power of 5.
1930 if y.sign == 1:
1931 last_digit = xc % 10
1932 if last_digit in (2,4,6,8):
1933 # quick test for power of 2
1934 if xc & -xc != xc:
1935 return None
1936 # now xc is a power of 2; e is its exponent
1937 e = _nbits(xc)-1
1938 # find e*y and xe*y; both must be integers
1939 if ye >= 0:
1940 y_as_int = yc*10**ye
1941 e = e*y_as_int
1942 xe = xe*y_as_int
1943 else:
1944 ten_pow = 10**-ye
1945 e, remainder = divmod(e*yc, ten_pow)
1946 if remainder:
1947 return None
1948 xe, remainder = divmod(xe*yc, ten_pow)
1949 if remainder:
1950 return None
1951
1952 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1953 return None
1954 xc = 5**e
1955
1956 elif last_digit == 5:
1957 # e >= log_5(xc) if xc is a power of 5; we have
1958 # equality all the way up to xc=5**2658
1959 e = _nbits(xc)*28//65
1960 xc, remainder = divmod(5**e, xc)
1961 if remainder:
1962 return None
1963 while xc % 5 == 0:
1964 xc //= 5
1965 e -= 1
1966 if ye >= 0:
1967 y_as_integer = yc*10**ye
1968 e = e*y_as_integer
1969 xe = xe*y_as_integer
1970 else:
1971 ten_pow = 10**-ye
1972 e, remainder = divmod(e*yc, ten_pow)
1973 if remainder:
1974 return None
1975 xe, remainder = divmod(xe*yc, ten_pow)
1976 if remainder:
1977 return None
1978 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1979 return None
1980 xc = 2**e
1981 else:
1982 return None
1983
1984 if xc >= 10**p:
1985 return None
1986 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001987 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001988
1989 # now y is positive; find m and n such that y = m/n
1990 if ye >= 0:
1991 m, n = yc*10**ye, 1
1992 else:
1993 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1994 return None
1995 xc_bits = _nbits(xc)
1996 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1997 return None
1998 m, n = yc, 10**(-ye)
1999 while m % 2 == n % 2 == 0:
2000 m //= 2
2001 n //= 2
2002 while m % 5 == n % 5 == 0:
2003 m //= 5
2004 n //= 5
2005
2006 # compute nth root of xc*10**xe
2007 if n > 1:
2008 # if 1 < xc < 2**n then xc isn't an nth power
2009 if xc != 1 and xc_bits <= n:
2010 return None
2011
2012 xe, rem = divmod(xe, n)
2013 if rem != 0:
2014 return None
2015
2016 # compute nth root of xc using Newton's method
2017 a = 1 << -(-_nbits(xc)//n) # initial estimate
2018 while True:
2019 q, r = divmod(xc, a**(n-1))
2020 if a <= q:
2021 break
2022 else:
2023 a = (a*(n-1) + q)//n
2024 if not (a == q and r == 0):
2025 return None
2026 xc = a
2027
2028 # now xc*10**xe is the nth root of the original xc*10**xe
2029 # compute mth power of xc*10**xe
2030
2031 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2032 # 10**p and the result is not representable.
2033 if xc > 1 and m > p*100//_log10_lb(xc):
2034 return None
2035 xc = xc**m
2036 xe *= m
2037 if xc > 10**p:
2038 return None
2039
2040 # by this point the result *is* exactly representable
2041 # adjust the exponent to get as close as possible to the ideal
2042 # exponent, if necessary
2043 str_xc = str(xc)
2044 if other._isinteger() and other._sign == 0:
2045 ideal_exponent = self._exp*int(other)
2046 zeros = min(xe-ideal_exponent, p-len(str_xc))
2047 else:
2048 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002049 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002050
2051 def __pow__(self, other, modulo=None, context=None):
2052 """Return self ** other [ % modulo].
2053
2054 With two arguments, compute self**other.
2055
2056 With three arguments, compute (self**other) % modulo. For the
2057 three argument form, the following restrictions on the
2058 arguments hold:
2059
2060 - all three arguments must be integral
2061 - other must be nonnegative
2062 - either self or other (or both) must be nonzero
2063 - modulo must be nonzero and must have at most p digits,
2064 where p is the context precision.
2065
2066 If any of these restrictions is violated the InvalidOperation
2067 flag is raised.
2068
2069 The result of pow(self, other, modulo) is identical to the
2070 result that would be obtained by computing (self**other) %
2071 modulo with unbounded precision, but is computed more
2072 efficiently. It is always exact.
2073 """
2074
2075 if modulo is not None:
2076 return self._power_modulo(other, modulo, context)
2077
2078 other = _convert_other(other)
2079 if other is NotImplemented:
2080 return other
2081
2082 if context is None:
2083 context = getcontext()
2084
2085 # either argument is a NaN => result is NaN
2086 ans = self._check_nans(other, context)
2087 if ans:
2088 return ans
2089
2090 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2091 if not other:
2092 if not self:
2093 return context._raise_error(InvalidOperation, '0 ** 0')
2094 else:
2095 return Dec_p1
2096
2097 # result has sign 1 iff self._sign is 1 and other is an odd integer
2098 result_sign = 0
2099 if self._sign == 1:
2100 if other._isinteger():
2101 if not other._iseven():
2102 result_sign = 1
2103 else:
2104 # -ve**noninteger = NaN
2105 # (-0)**noninteger = 0**noninteger
2106 if self:
2107 return context._raise_error(InvalidOperation,
2108 'x ** y with x negative and y not an integer')
2109 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002110 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002111
2112 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2113 if not self:
2114 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002115 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002116 else:
2117 return Infsign[result_sign]
2118
2119 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002120 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002121 if other._sign == 0:
2122 return Infsign[result_sign]
2123 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002124 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002125
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002126 # 1**other = 1, but the choice of exponent and the flags
2127 # depend on the exponent of self, and on whether other is a
2128 # positive integer, a negative integer, or neither
2129 if self == Dec_p1:
2130 if other._isinteger():
2131 # exp = max(self._exp*max(int(other), 0),
2132 # 1-context.prec) but evaluating int(other) directly
2133 # is dangerous until we know other is small (other
2134 # could be 1e999999999)
2135 if other._sign == 1:
2136 multiplier = 0
2137 elif other > context.prec:
2138 multiplier = context.prec
2139 else:
2140 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002141
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002142 exp = self._exp * multiplier
2143 if exp < 1-context.prec:
2144 exp = 1-context.prec
2145 context._raise_error(Rounded)
2146 else:
2147 context._raise_error(Inexact)
2148 context._raise_error(Rounded)
2149 exp = 1-context.prec
2150
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002151 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002152
2153 # compute adjusted exponent of self
2154 self_adj = self.adjusted()
2155
2156 # self ** infinity is infinity if self > 1, 0 if self < 1
2157 # self ** -infinity is infinity if self < 1, 0 if self > 1
2158 if other._isinfinity():
2159 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002160 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002161 else:
2162 return Infsign[result_sign]
2163
2164 # from here on, the result always goes through the call
2165 # to _fix at the end of this function.
2166 ans = None
2167
2168 # crude test to catch cases of extreme overflow/underflow. If
2169 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2170 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2171 # self**other >= 10**(Emax+1), so overflow occurs. The test
2172 # for underflow is similar.
2173 bound = self._log10_exp_bound() + other.adjusted()
2174 if (self_adj >= 0) == (other._sign == 0):
2175 # self > 1 and other +ve, or self < 1 and other -ve
2176 # possibility of overflow
2177 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002178 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002179 else:
2180 # self > 1 and other -ve, or self < 1 and other +ve
2181 # possibility of underflow to 0
2182 Etiny = context.Etiny()
2183 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002184 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002185
2186 # try for an exact result with precision +1
2187 if ans is None:
2188 ans = self._power_exact(other, context.prec + 1)
2189 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002190 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002191
2192 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2193 if ans is None:
2194 p = context.prec
2195 x = _WorkRep(self)
2196 xc, xe = x.int, x.exp
2197 y = _WorkRep(other)
2198 yc, ye = y.int, y.exp
2199 if y.sign == 1:
2200 yc = -yc
2201
2202 # compute correctly rounded result: start with precision +3,
2203 # then increase precision until result is unambiguously roundable
2204 extra = 3
2205 while True:
2206 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2207 if coeff % (5*10**(len(str(coeff))-p-1)):
2208 break
2209 extra += 3
2210
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002211 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002212
2213 # the specification says that for non-integer other we need to
2214 # raise Inexact, even when the result is actually exact. In
2215 # the same way, we need to raise Underflow here if the result
2216 # is subnormal. (The call to _fix will take care of raising
2217 # Rounded and Subnormal, as usual.)
2218 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002219 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002220 # pad with zeros up to length context.prec+1 if necessary
2221 if len(ans._int) <= context.prec:
2222 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002223 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2224 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002225 if ans.adjusted() < context.Emin:
2226 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002227
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002228 # unlike exp, ln and log10, the power function respects the
2229 # rounding mode; no need to use ROUND_HALF_EVEN here
2230 ans = ans._fix(context)
2231 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002232
2233 def __rpow__(self, other, context=None):
2234 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002235 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002236 if other is NotImplemented:
2237 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002238 return other.__pow__(self, context=context)
2239
2240 def normalize(self, context=None):
2241 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002242
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002243 if context is None:
2244 context = getcontext()
2245
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002246 if self._is_special:
2247 ans = self._check_nans(context=context)
2248 if ans:
2249 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002250
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002251 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002252 if dup._isinfinity():
2253 return dup
2254
2255 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002256 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002257 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002258 end = len(dup._int)
2259 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002260 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002261 exp += 1
2262 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002263 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002264
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002265 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002266 """Quantize self so its exponent is the same as that of exp.
2267
2268 Similar to self._rescale(exp._exp) but with error checking.
2269 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002270 exp = _convert_other(exp, raiseit=True)
2271
2272 if context is None:
2273 context = getcontext()
2274 if rounding is None:
2275 rounding = context.rounding
2276
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002277 if self._is_special or exp._is_special:
2278 ans = self._check_nans(exp, context)
2279 if ans:
2280 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002281
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002282 if exp._isinfinity() or self._isinfinity():
2283 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002284 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002285 return context._raise_error(InvalidOperation,
2286 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002287
2288 # if we're not watching exponents, do a simple rescale
2289 if not watchexp:
2290 ans = self._rescale(exp._exp, rounding)
2291 # raise Inexact and Rounded where appropriate
2292 if ans._exp > self._exp:
2293 context._raise_error(Rounded)
2294 if ans != self:
2295 context._raise_error(Inexact)
2296 return ans
2297
2298 # exp._exp should be between Etiny and Emax
2299 if not (context.Etiny() <= exp._exp <= context.Emax):
2300 return context._raise_error(InvalidOperation,
2301 'target exponent out of bounds in quantize')
2302
2303 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002304 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002305 return ans._fix(context)
2306
2307 self_adjusted = self.adjusted()
2308 if self_adjusted > context.Emax:
2309 return context._raise_error(InvalidOperation,
2310 'exponent of quantize result too large for current context')
2311 if self_adjusted - exp._exp + 1 > context.prec:
2312 return context._raise_error(InvalidOperation,
2313 'quantize result has too many digits for current context')
2314
2315 ans = self._rescale(exp._exp, rounding)
2316 if ans.adjusted() > context.Emax:
2317 return context._raise_error(InvalidOperation,
2318 'exponent of quantize result too large for current context')
2319 if len(ans._int) > context.prec:
2320 return context._raise_error(InvalidOperation,
2321 'quantize result has too many digits for current context')
2322
2323 # raise appropriate flags
2324 if ans._exp > self._exp:
2325 context._raise_error(Rounded)
2326 if ans != self:
2327 context._raise_error(Inexact)
2328 if ans and ans.adjusted() < context.Emin:
2329 context._raise_error(Subnormal)
2330
2331 # call to fix takes care of any necessary folddown
2332 ans = ans._fix(context)
2333 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002334
2335 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002336 """Return True if self and other have the same exponent; otherwise
2337 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002338
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002339 If either operand is a special value, the following rules are used:
2340 * return True if both operands are infinities
2341 * return True if both operands are NaNs
2342 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002343 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002344 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002345 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002346 return (self.is_nan() and other.is_nan() or
2347 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002348 return self._exp == other._exp
2349
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002350 def _rescale(self, exp, rounding):
2351 """Rescale self so that the exponent is exp, either by padding with zeros
2352 or by truncating digits, using the given rounding mode.
2353
2354 Specials are returned without change. This operation is
2355 quiet: it raises no flags, and uses no information from the
2356 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002357
2358 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002359 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002360 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002361 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002362 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002363 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002364 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002365
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002366 if self._exp >= exp:
2367 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002368 return _dec_from_triple(self._sign,
2369 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002370
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002371 # too many digits; round and lose data. If self.adjusted() <
2372 # exp-1, replace self by 10**(exp-1) before rounding
2373 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002374 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002375 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002376 digits = 0
2377 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002378 changed = this_function(digits)
2379 coeff = self._int[:digits] or '0'
2380 if changed == 1:
2381 coeff = str(int(coeff)+1)
2382 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002383
Christian Heimesf16baeb2008-02-29 14:57:44 +00002384 def _round(self, places, rounding):
2385 """Round a nonzero, nonspecial Decimal to a fixed number of
2386 significant figures, using the given rounding mode.
2387
2388 Infinities, NaNs and zeros are returned unaltered.
2389
2390 This operation is quiet: it raises no flags, and uses no
2391 information from the context.
2392
2393 """
2394 if places <= 0:
2395 raise ValueError("argument should be at least 1 in _round")
2396 if self._is_special or not self:
2397 return Decimal(self)
2398 ans = self._rescale(self.adjusted()+1-places, rounding)
2399 # it can happen that the rescale alters the adjusted exponent;
2400 # for example when rounding 99.97 to 3 significant figures.
2401 # When this happens we end up with an extra 0 at the end of
2402 # the number; a second rescale fixes this.
2403 if ans.adjusted() != self.adjusted():
2404 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2405 return ans
2406
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002407 def to_integral_exact(self, rounding=None, context=None):
2408 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002409
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002410 If no rounding mode is specified, take the rounding mode from
2411 the context. This method raises the Rounded and Inexact flags
2412 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002413
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002414 See also: to_integral_value, which does exactly the same as
2415 this method except that it doesn't raise Inexact or Rounded.
2416 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002417 if self._is_special:
2418 ans = self._check_nans(context=context)
2419 if ans:
2420 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002421 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002422 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002423 return Decimal(self)
2424 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002425 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002426 if context is None:
2427 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002428 if rounding is None:
2429 rounding = context.rounding
2430 context._raise_error(Rounded)
2431 ans = self._rescale(0, rounding)
2432 if ans != self:
2433 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002434 return ans
2435
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002436 def to_integral_value(self, rounding=None, context=None):
2437 """Rounds to the nearest integer, without raising inexact, rounded."""
2438 if context is None:
2439 context = getcontext()
2440 if rounding is None:
2441 rounding = context.rounding
2442 if self._is_special:
2443 ans = self._check_nans(context=context)
2444 if ans:
2445 return ans
2446 return Decimal(self)
2447 if self._exp >= 0:
2448 return Decimal(self)
2449 else:
2450 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002451
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002452 # the method name changed, but we provide also the old one, for compatibility
2453 to_integral = to_integral_value
2454
2455 def sqrt(self, context=None):
2456 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002457 if self._is_special:
2458 ans = self._check_nans(context=context)
2459 if ans:
2460 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002461
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002462 if self._isinfinity() and self._sign == 0:
2463 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002464
2465 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002466 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002467 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002468 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002469
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002470 if context is None:
2471 context = getcontext()
2472
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002473 if self._sign == 1:
2474 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2475
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002476 # At this point self represents a positive number. Let p be
2477 # the desired precision and express self in the form c*100**e
2478 # with c a positive real number and e an integer, c and e
2479 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2480 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2481 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2482 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2483 # the closest integer to sqrt(c) with the even integer chosen
2484 # in the case of a tie.
2485 #
2486 # To ensure correct rounding in all cases, we use the
2487 # following trick: we compute the square root to an extra
2488 # place (precision p+1 instead of precision p), rounding down.
2489 # Then, if the result is inexact and its last digit is 0 or 5,
2490 # we increase the last digit to 1 or 6 respectively; if it's
2491 # exact we leave the last digit alone. Now the final round to
2492 # p places (or fewer in the case of underflow) will round
2493 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002494
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002495 # use an extra digit of precision
2496 prec = context.prec+1
2497
2498 # write argument in the form c*100**e where e = self._exp//2
2499 # is the 'ideal' exponent, to be used if the square root is
2500 # exactly representable. l is the number of 'digits' of c in
2501 # base 100, so that 100**(l-1) <= c < 100**l.
2502 op = _WorkRep(self)
2503 e = op.exp >> 1
2504 if op.exp & 1:
2505 c = op.int * 10
2506 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002507 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002508 c = op.int
2509 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002510
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002511 # rescale so that c has exactly prec base 100 'digits'
2512 shift = prec-l
2513 if shift >= 0:
2514 c *= 100**shift
2515 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002516 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002517 c, remainder = divmod(c, 100**-shift)
2518 exact = not remainder
2519 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002520
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002521 # find n = floor(sqrt(c)) using Newton's method
2522 n = 10**prec
2523 while True:
2524 q = c//n
2525 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002526 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002527 else:
2528 n = n + q >> 1
2529 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002530
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002531 if exact:
2532 # result is exact; rescale to use ideal exponent e
2533 if shift >= 0:
2534 # assert n % 10**shift == 0
2535 n //= 10**shift
2536 else:
2537 n *= 10**-shift
2538 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002539 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002540 # result is not exact; fix last digit as described above
2541 if n % 5 == 0:
2542 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002543
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002544 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002545
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002546 # round, and fit to current context
2547 context = context._shallow_copy()
2548 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002549 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002550 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002551
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002552 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002553
2554 def max(self, other, context=None):
2555 """Returns the larger value.
2556
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002557 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002558 NaN (and signals if one is sNaN). Also rounds.
2559 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002560 other = _convert_other(other, raiseit=True)
2561
2562 if context is None:
2563 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002564
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002565 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002566 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002567 # number is always returned
2568 sn = self._isnan()
2569 on = other._isnan()
2570 if sn or on:
2571 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002572 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002573 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002574 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002575 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002576
Christian Heimes77c02eb2008-02-09 02:18:51 +00002577 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002578 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002579 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002580 # then an ordering is applied:
2581 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002582 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002583 # positive sign and min returns the operand with the negative sign
2584 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002585 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002586 # the result. This is exactly the ordering used in compare_total.
2587 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002588
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002589 if c == -1:
2590 ans = other
2591 else:
2592 ans = self
2593
Christian Heimes2c181612007-12-17 20:04:13 +00002594 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002595
2596 def min(self, other, context=None):
2597 """Returns the smaller value.
2598
Guido van Rossumd8faa362007-04-27 19:54:29 +00002599 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002600 NaN (and signals if one is sNaN). Also rounds.
2601 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002602 other = _convert_other(other, raiseit=True)
2603
2604 if context is None:
2605 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002606
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002607 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002608 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002609 # number is always returned
2610 sn = self._isnan()
2611 on = other._isnan()
2612 if sn or on:
2613 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002614 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002615 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002616 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002617 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002618
Christian Heimes77c02eb2008-02-09 02:18:51 +00002619 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002620 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002621 c = self.compare_total(other)
2622
2623 if c == -1:
2624 ans = self
2625 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002626 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002627
Christian Heimes2c181612007-12-17 20:04:13 +00002628 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002629
2630 def _isinteger(self):
2631 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002632 if self._is_special:
2633 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002634 if self._exp >= 0:
2635 return True
2636 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002637 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002638
2639 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002640 """Returns True if self is even. Assumes self is an integer."""
2641 if not self or self._exp > 0:
2642 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002643 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002644
2645 def adjusted(self):
2646 """Return the adjusted exponent of self"""
2647 try:
2648 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002649 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002650 except TypeError:
2651 return 0
2652
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002653 def canonical(self, context=None):
2654 """Returns the same Decimal object.
2655
2656 As we do not have different encodings for the same number, the
2657 received object already is in its canonical form.
2658 """
2659 return self
2660
2661 def compare_signal(self, other, context=None):
2662 """Compares self to the other operand numerically.
2663
2664 It's pretty much like compare(), but all NaNs signal, with signaling
2665 NaNs taking precedence over quiet NaNs.
2666 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002667 other = _convert_other(other, raiseit = True)
2668 ans = self._compare_check_nans(other, context)
2669 if ans:
2670 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002671 return self.compare(other, context=context)
2672
2673 def compare_total(self, other):
2674 """Compares self to other using the abstract representations.
2675
2676 This is not like the standard compare, which use their numerical
2677 value. Note that a total ordering is defined for all possible abstract
2678 representations.
2679 """
2680 # if one is negative and the other is positive, it's easy
2681 if self._sign and not other._sign:
2682 return Dec_n1
2683 if not self._sign and other._sign:
2684 return Dec_p1
2685 sign = self._sign
2686
2687 # let's handle both NaN types
2688 self_nan = self._isnan()
2689 other_nan = other._isnan()
2690 if self_nan or other_nan:
2691 if self_nan == other_nan:
2692 if self._int < other._int:
2693 if sign:
2694 return Dec_p1
2695 else:
2696 return Dec_n1
2697 if self._int > other._int:
2698 if sign:
2699 return Dec_n1
2700 else:
2701 return Dec_p1
2702 return Dec_0
2703
2704 if sign:
2705 if self_nan == 1:
2706 return Dec_n1
2707 if other_nan == 1:
2708 return Dec_p1
2709 if self_nan == 2:
2710 return Dec_n1
2711 if other_nan == 2:
2712 return Dec_p1
2713 else:
2714 if self_nan == 1:
2715 return Dec_p1
2716 if other_nan == 1:
2717 return Dec_n1
2718 if self_nan == 2:
2719 return Dec_p1
2720 if other_nan == 2:
2721 return Dec_n1
2722
2723 if self < other:
2724 return Dec_n1
2725 if self > other:
2726 return Dec_p1
2727
2728 if self._exp < other._exp:
2729 if sign:
2730 return Dec_p1
2731 else:
2732 return Dec_n1
2733 if self._exp > other._exp:
2734 if sign:
2735 return Dec_n1
2736 else:
2737 return Dec_p1
2738 return Dec_0
2739
2740
2741 def compare_total_mag(self, other):
2742 """Compares self to other using abstract repr., ignoring sign.
2743
2744 Like compare_total, but with operand's sign ignored and assumed to be 0.
2745 """
2746 s = self.copy_abs()
2747 o = other.copy_abs()
2748 return s.compare_total(o)
2749
2750 def copy_abs(self):
2751 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002752 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002753
2754 def copy_negate(self):
2755 """Returns a copy with the sign inverted."""
2756 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002757 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002758 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002759 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002760
2761 def copy_sign(self, other):
2762 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002763 return _dec_from_triple(other._sign, self._int,
2764 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002765
2766 def exp(self, context=None):
2767 """Returns e ** self."""
2768
2769 if context is None:
2770 context = getcontext()
2771
2772 # exp(NaN) = NaN
2773 ans = self._check_nans(context=context)
2774 if ans:
2775 return ans
2776
2777 # exp(-Infinity) = 0
2778 if self._isinfinity() == -1:
2779 return Dec_0
2780
2781 # exp(0) = 1
2782 if not self:
2783 return Dec_p1
2784
2785 # exp(Infinity) = Infinity
2786 if self._isinfinity() == 1:
2787 return Decimal(self)
2788
2789 # the result is now guaranteed to be inexact (the true
2790 # mathematical result is transcendental). There's no need to
2791 # raise Rounded and Inexact here---they'll always be raised as
2792 # a result of the call to _fix.
2793 p = context.prec
2794 adj = self.adjusted()
2795
2796 # we only need to do any computation for quite a small range
2797 # of adjusted exponents---for example, -29 <= adj <= 10 for
2798 # the default context. For smaller exponent the result is
2799 # indistinguishable from 1 at the given precision, while for
2800 # larger exponent the result either overflows or underflows.
2801 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2802 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002803 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002804 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2805 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002806 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002807 elif self._sign == 0 and adj < -p:
2808 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002809 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002810 elif self._sign == 1 and adj < -p-1:
2811 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002812 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002813 # general case
2814 else:
2815 op = _WorkRep(self)
2816 c, e = op.int, op.exp
2817 if op.sign == 1:
2818 c = -c
2819
2820 # compute correctly rounded result: increase precision by
2821 # 3 digits at a time until we get an unambiguously
2822 # roundable result
2823 extra = 3
2824 while True:
2825 coeff, exp = _dexp(c, e, p+extra)
2826 if coeff % (5*10**(len(str(coeff))-p-1)):
2827 break
2828 extra += 3
2829
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002830 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002831
2832 # at this stage, ans should round correctly with *any*
2833 # rounding mode, not just with ROUND_HALF_EVEN
2834 context = context._shallow_copy()
2835 rounding = context._set_rounding(ROUND_HALF_EVEN)
2836 ans = ans._fix(context)
2837 context.rounding = rounding
2838
2839 return ans
2840
2841 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002842 """Return True if self is canonical; otherwise return False.
2843
2844 Currently, the encoding of a Decimal instance is always
2845 canonical, so this method returns True for any Decimal.
2846 """
2847 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002848
2849 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002850 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002851
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002852 A Decimal instance is considered finite if it is neither
2853 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002854 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002855 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002856
2857 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002858 """Return True if self is infinite; otherwise return False."""
2859 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002860
2861 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002862 """Return True if self is a qNaN or sNaN; otherwise return False."""
2863 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002864
2865 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002866 """Return True if self is a normal number; otherwise return False."""
2867 if self._is_special or not self:
2868 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002869 if context is None:
2870 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002871 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002872
2873 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002874 """Return True if self is a quiet NaN; otherwise return False."""
2875 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002876
2877 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002878 """Return True if self is negative; otherwise return False."""
2879 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002880
2881 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002882 """Return True if self is a signaling NaN; otherwise return False."""
2883 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002884
2885 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002886 """Return True if self is subnormal; otherwise return False."""
2887 if self._is_special or not self:
2888 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002889 if context is None:
2890 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002891 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002892
2893 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002894 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002895 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002896
2897 def _ln_exp_bound(self):
2898 """Compute a lower bound for the adjusted exponent of self.ln().
2899 In other words, compute r such that self.ln() >= 10**r. Assumes
2900 that self is finite and positive and that self != 1.
2901 """
2902
2903 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2904 adj = self._exp + len(self._int) - 1
2905 if adj >= 1:
2906 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2907 return len(str(adj*23//10)) - 1
2908 if adj <= -2:
2909 # argument <= 0.1
2910 return len(str((-1-adj)*23//10)) - 1
2911 op = _WorkRep(self)
2912 c, e = op.int, op.exp
2913 if adj == 0:
2914 # 1 < self < 10
2915 num = str(c-10**-e)
2916 den = str(c)
2917 return len(num) - len(den) - (num < den)
2918 # adj == -1, 0.1 <= self < 1
2919 return e + len(str(10**-e - c)) - 1
2920
2921
2922 def ln(self, context=None):
2923 """Returns the natural (base e) logarithm of self."""
2924
2925 if context is None:
2926 context = getcontext()
2927
2928 # ln(NaN) = NaN
2929 ans = self._check_nans(context=context)
2930 if ans:
2931 return ans
2932
2933 # ln(0.0) == -Infinity
2934 if not self:
2935 return negInf
2936
2937 # ln(Infinity) = Infinity
2938 if self._isinfinity() == 1:
2939 return Inf
2940
2941 # ln(1.0) == 0.0
2942 if self == Dec_p1:
2943 return Dec_0
2944
2945 # ln(negative) raises InvalidOperation
2946 if self._sign == 1:
2947 return context._raise_error(InvalidOperation,
2948 'ln of a negative value')
2949
2950 # result is irrational, so necessarily inexact
2951 op = _WorkRep(self)
2952 c, e = op.int, op.exp
2953 p = context.prec
2954
2955 # correctly rounded result: repeatedly increase precision by 3
2956 # until we get an unambiguously roundable result
2957 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2958 while True:
2959 coeff = _dlog(c, e, places)
2960 # assert len(str(abs(coeff)))-p >= 1
2961 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2962 break
2963 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002964 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002965
2966 context = context._shallow_copy()
2967 rounding = context._set_rounding(ROUND_HALF_EVEN)
2968 ans = ans._fix(context)
2969 context.rounding = rounding
2970 return ans
2971
2972 def _log10_exp_bound(self):
2973 """Compute a lower bound for the adjusted exponent of self.log10().
2974 In other words, find r such that self.log10() >= 10**r.
2975 Assumes that self is finite and positive and that self != 1.
2976 """
2977
2978 # For x >= 10 or x < 0.1 we only need a bound on the integer
2979 # part of log10(self), and this comes directly from the
2980 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2981 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2982 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2983
2984 adj = self._exp + len(self._int) - 1
2985 if adj >= 1:
2986 # self >= 10
2987 return len(str(adj))-1
2988 if adj <= -2:
2989 # self < 0.1
2990 return len(str(-1-adj))-1
2991 op = _WorkRep(self)
2992 c, e = op.int, op.exp
2993 if adj == 0:
2994 # 1 < self < 10
2995 num = str(c-10**-e)
2996 den = str(231*c)
2997 return len(num) - len(den) - (num < den) + 2
2998 # adj == -1, 0.1 <= self < 1
2999 num = str(10**-e-c)
3000 return len(num) + e - (num < "231") - 1
3001
3002 def log10(self, context=None):
3003 """Returns the base 10 logarithm of self."""
3004
3005 if context is None:
3006 context = getcontext()
3007
3008 # log10(NaN) = NaN
3009 ans = self._check_nans(context=context)
3010 if ans:
3011 return ans
3012
3013 # log10(0.0) == -Infinity
3014 if not self:
3015 return negInf
3016
3017 # log10(Infinity) = Infinity
3018 if self._isinfinity() == 1:
3019 return Inf
3020
3021 # log10(negative or -Infinity) raises InvalidOperation
3022 if self._sign == 1:
3023 return context._raise_error(InvalidOperation,
3024 'log10 of a negative value')
3025
3026 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003027 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003028 # answer may need rounding
3029 ans = Decimal(self._exp + len(self._int) - 1)
3030 else:
3031 # result is irrational, so necessarily inexact
3032 op = _WorkRep(self)
3033 c, e = op.int, op.exp
3034 p = context.prec
3035
3036 # correctly rounded result: repeatedly increase precision
3037 # until result is unambiguously roundable
3038 places = p-self._log10_exp_bound()+2
3039 while True:
3040 coeff = _dlog10(c, e, places)
3041 # assert len(str(abs(coeff)))-p >= 1
3042 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3043 break
3044 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003045 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003046
3047 context = context._shallow_copy()
3048 rounding = context._set_rounding(ROUND_HALF_EVEN)
3049 ans = ans._fix(context)
3050 context.rounding = rounding
3051 return ans
3052
3053 def logb(self, context=None):
3054 """ Returns the exponent of the magnitude of self's MSD.
3055
3056 The result is the integer which is the exponent of the magnitude
3057 of the most significant digit of self (as though it were truncated
3058 to a single digit while maintaining the value of that digit and
3059 without limiting the resulting exponent).
3060 """
3061 # logb(NaN) = NaN
3062 ans = self._check_nans(context=context)
3063 if ans:
3064 return ans
3065
3066 if context is None:
3067 context = getcontext()
3068
3069 # logb(+/-Inf) = +Inf
3070 if self._isinfinity():
3071 return Inf
3072
3073 # logb(0) = -Inf, DivisionByZero
3074 if not self:
3075 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3076
3077 # otherwise, simply return the adjusted exponent of self, as a
3078 # Decimal. Note that no attempt is made to fit the result
3079 # into the current context.
3080 return Decimal(self.adjusted())
3081
3082 def _islogical(self):
3083 """Return True if self is a logical operand.
3084
Christian Heimes679db4a2008-01-18 09:56:22 +00003085 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003086 an exponent of 0, and a coefficient whose digits must all be
3087 either 0 or 1.
3088 """
3089 if self._sign != 0 or self._exp != 0:
3090 return False
3091 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003092 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003093 return False
3094 return True
3095
3096 def _fill_logical(self, context, opa, opb):
3097 dif = context.prec - len(opa)
3098 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003099 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003100 elif dif < 0:
3101 opa = opa[-context.prec:]
3102 dif = context.prec - len(opb)
3103 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003104 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003105 elif dif < 0:
3106 opb = opb[-context.prec:]
3107 return opa, opb
3108
3109 def logical_and(self, other, context=None):
3110 """Applies an 'and' operation between self and other's digits."""
3111 if context is None:
3112 context = getcontext()
3113 if not self._islogical() or not other._islogical():
3114 return context._raise_error(InvalidOperation)
3115
3116 # fill to context.prec
3117 (opa, opb) = self._fill_logical(context, self._int, other._int)
3118
3119 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003120 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3121 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003122
3123 def logical_invert(self, context=None):
3124 """Invert all its digits."""
3125 if context is None:
3126 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003127 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3128 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003129
3130 def logical_or(self, other, context=None):
3131 """Applies an 'or' operation between self and other's digits."""
3132 if context is None:
3133 context = getcontext()
3134 if not self._islogical() or not other._islogical():
3135 return context._raise_error(InvalidOperation)
3136
3137 # fill to context.prec
3138 (opa, opb) = self._fill_logical(context, self._int, other._int)
3139
3140 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003141 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3142 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003143
3144 def logical_xor(self, other, context=None):
3145 """Applies an 'xor' operation between self and other's digits."""
3146 if context is None:
3147 context = getcontext()
3148 if not self._islogical() or not other._islogical():
3149 return context._raise_error(InvalidOperation)
3150
3151 # fill to context.prec
3152 (opa, opb) = self._fill_logical(context, self._int, other._int)
3153
3154 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003155 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3156 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003157
3158 def max_mag(self, other, context=None):
3159 """Compares the values numerically with their sign ignored."""
3160 other = _convert_other(other, raiseit=True)
3161
3162 if context is None:
3163 context = getcontext()
3164
3165 if self._is_special or other._is_special:
3166 # If one operand is a quiet NaN and the other is number, then the
3167 # number is always returned
3168 sn = self._isnan()
3169 on = other._isnan()
3170 if sn or on:
3171 if on == 1 and sn != 2:
3172 return self._fix_nan(context)
3173 if sn == 1 and on != 2:
3174 return other._fix_nan(context)
3175 return self._check_nans(other, context)
3176
Christian Heimes77c02eb2008-02-09 02:18:51 +00003177 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003178 if c == 0:
3179 c = self.compare_total(other)
3180
3181 if c == -1:
3182 ans = other
3183 else:
3184 ans = self
3185
Christian Heimes2c181612007-12-17 20:04:13 +00003186 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003187
3188 def min_mag(self, other, context=None):
3189 """Compares the values numerically with their sign ignored."""
3190 other = _convert_other(other, raiseit=True)
3191
3192 if context is None:
3193 context = getcontext()
3194
3195 if self._is_special or other._is_special:
3196 # If one operand is a quiet NaN and the other is number, then the
3197 # number is always returned
3198 sn = self._isnan()
3199 on = other._isnan()
3200 if sn or on:
3201 if on == 1 and sn != 2:
3202 return self._fix_nan(context)
3203 if sn == 1 and on != 2:
3204 return other._fix_nan(context)
3205 return self._check_nans(other, context)
3206
Christian Heimes77c02eb2008-02-09 02:18:51 +00003207 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003208 if c == 0:
3209 c = self.compare_total(other)
3210
3211 if c == -1:
3212 ans = self
3213 else:
3214 ans = other
3215
Christian Heimes2c181612007-12-17 20:04:13 +00003216 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003217
3218 def next_minus(self, context=None):
3219 """Returns the largest representable number smaller than itself."""
3220 if context is None:
3221 context = getcontext()
3222
3223 ans = self._check_nans(context=context)
3224 if ans:
3225 return ans
3226
3227 if self._isinfinity() == -1:
3228 return negInf
3229 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003230 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003231
3232 context = context.copy()
3233 context._set_rounding(ROUND_FLOOR)
3234 context._ignore_all_flags()
3235 new_self = self._fix(context)
3236 if new_self != self:
3237 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003238 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3239 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003240
3241 def next_plus(self, context=None):
3242 """Returns the smallest representable number larger than itself."""
3243 if context is None:
3244 context = getcontext()
3245
3246 ans = self._check_nans(context=context)
3247 if ans:
3248 return ans
3249
3250 if self._isinfinity() == 1:
3251 return Inf
3252 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003253 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003254
3255 context = context.copy()
3256 context._set_rounding(ROUND_CEILING)
3257 context._ignore_all_flags()
3258 new_self = self._fix(context)
3259 if new_self != self:
3260 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003261 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3262 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003263
3264 def next_toward(self, other, context=None):
3265 """Returns the number closest to self, in the direction towards other.
3266
3267 The result is the closest representable number to self
3268 (excluding self) that is in the direction towards other,
3269 unless both have the same value. If the two operands are
3270 numerically equal, then the result is a copy of self with the
3271 sign set to be the same as the sign of other.
3272 """
3273 other = _convert_other(other, raiseit=True)
3274
3275 if context is None:
3276 context = getcontext()
3277
3278 ans = self._check_nans(other, context)
3279 if ans:
3280 return ans
3281
Christian Heimes77c02eb2008-02-09 02:18:51 +00003282 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003283 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003284 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003285
3286 if comparison == -1:
3287 ans = self.next_plus(context)
3288 else: # comparison == 1
3289 ans = self.next_minus(context)
3290
3291 # decide which flags to raise using value of ans
3292 if ans._isinfinity():
3293 context._raise_error(Overflow,
3294 'Infinite result from next_toward',
3295 ans._sign)
3296 context._raise_error(Rounded)
3297 context._raise_error(Inexact)
3298 elif ans.adjusted() < context.Emin:
3299 context._raise_error(Underflow)
3300 context._raise_error(Subnormal)
3301 context._raise_error(Rounded)
3302 context._raise_error(Inexact)
3303 # if precision == 1 then we don't raise Clamped for a
3304 # result 0E-Etiny.
3305 if not ans:
3306 context._raise_error(Clamped)
3307
3308 return ans
3309
3310 def number_class(self, context=None):
3311 """Returns an indication of the class of self.
3312
3313 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003314 sNaN
3315 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003316 -Infinity
3317 -Normal
3318 -Subnormal
3319 -Zero
3320 +Zero
3321 +Subnormal
3322 +Normal
3323 +Infinity
3324 """
3325 if self.is_snan():
3326 return "sNaN"
3327 if self.is_qnan():
3328 return "NaN"
3329 inf = self._isinfinity()
3330 if inf == 1:
3331 return "+Infinity"
3332 if inf == -1:
3333 return "-Infinity"
3334 if self.is_zero():
3335 if self._sign:
3336 return "-Zero"
3337 else:
3338 return "+Zero"
3339 if context is None:
3340 context = getcontext()
3341 if self.is_subnormal(context=context):
3342 if self._sign:
3343 return "-Subnormal"
3344 else:
3345 return "+Subnormal"
3346 # just a normal, regular, boring number, :)
3347 if self._sign:
3348 return "-Normal"
3349 else:
3350 return "+Normal"
3351
3352 def radix(self):
3353 """Just returns 10, as this is Decimal, :)"""
3354 return Decimal(10)
3355
3356 def rotate(self, other, context=None):
3357 """Returns a rotated copy of self, value-of-other times."""
3358 if context is None:
3359 context = getcontext()
3360
3361 ans = self._check_nans(other, context)
3362 if ans:
3363 return ans
3364
3365 if other._exp != 0:
3366 return context._raise_error(InvalidOperation)
3367 if not (-context.prec <= int(other) <= context.prec):
3368 return context._raise_error(InvalidOperation)
3369
3370 if self._isinfinity():
3371 return Decimal(self)
3372
3373 # get values, pad if necessary
3374 torot = int(other)
3375 rotdig = self._int
3376 topad = context.prec - len(rotdig)
3377 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003378 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003379
3380 # let's rotate!
3381 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003382 return _dec_from_triple(self._sign,
3383 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003384
3385 def scaleb (self, other, context=None):
3386 """Returns self operand after adding the second value to its exp."""
3387 if context is None:
3388 context = getcontext()
3389
3390 ans = self._check_nans(other, context)
3391 if ans:
3392 return ans
3393
3394 if other._exp != 0:
3395 return context._raise_error(InvalidOperation)
3396 liminf = -2 * (context.Emax + context.prec)
3397 limsup = 2 * (context.Emax + context.prec)
3398 if not (liminf <= int(other) <= limsup):
3399 return context._raise_error(InvalidOperation)
3400
3401 if self._isinfinity():
3402 return Decimal(self)
3403
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003404 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003405 d = d._fix(context)
3406 return d
3407
3408 def shift(self, other, context=None):
3409 """Returns a shifted copy of self, value-of-other times."""
3410 if context is None:
3411 context = getcontext()
3412
3413 ans = self._check_nans(other, context)
3414 if ans:
3415 return ans
3416
3417 if other._exp != 0:
3418 return context._raise_error(InvalidOperation)
3419 if not (-context.prec <= int(other) <= context.prec):
3420 return context._raise_error(InvalidOperation)
3421
3422 if self._isinfinity():
3423 return Decimal(self)
3424
3425 # get values, pad if necessary
3426 torot = int(other)
3427 if not torot:
3428 return Decimal(self)
3429 rotdig = self._int
3430 topad = context.prec - len(rotdig)
3431 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003432 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003433
3434 # let's shift!
3435 if torot < 0:
3436 rotated = rotdig[:torot]
3437 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003438 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003439 rotated = rotated[-context.prec:]
3440
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003441 return _dec_from_triple(self._sign,
3442 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003443
Guido van Rossumd8faa362007-04-27 19:54:29 +00003444 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003445 def __reduce__(self):
3446 return (self.__class__, (str(self),))
3447
3448 def __copy__(self):
3449 if type(self) == Decimal:
3450 return self # I'm immutable; therefore I am my own clone
3451 return self.__class__(str(self))
3452
3453 def __deepcopy__(self, memo):
3454 if type(self) == Decimal:
3455 return self # My components are also immutable
3456 return self.__class__(str(self))
3457
Christian Heimesf16baeb2008-02-29 14:57:44 +00003458 # PEP 3101 support. See also _parse_format_specifier and _format_align
3459 def __format__(self, specifier, context=None):
3460 """Format a Decimal instance according to the given specifier.
3461
3462 The specifier should be a standard format specifier, with the
3463 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3464 'F', 'g', 'G', and '%' are supported. If the formatting type
3465 is omitted it defaults to 'g' or 'G', depending on the value
3466 of context.capitals.
3467
3468 At this time the 'n' format specifier type (which is supposed
3469 to use the current locale) is not supported.
3470 """
3471
3472 # Note: PEP 3101 says that if the type is not present then
3473 # there should be at least one digit after the decimal point.
3474 # We take the liberty of ignoring this requirement for
3475 # Decimal---it's presumably there to make sure that
3476 # format(float, '') behaves similarly to str(float).
3477 if context is None:
3478 context = getcontext()
3479
3480 spec = _parse_format_specifier(specifier)
3481
3482 # special values don't care about the type or precision...
3483 if self._is_special:
3484 return _format_align(str(self), spec)
3485
3486 # a type of None defaults to 'g' or 'G', depending on context
3487 # if type is '%', adjust exponent of self accordingly
3488 if spec['type'] is None:
3489 spec['type'] = ['g', 'G'][context.capitals]
3490 elif spec['type'] == '%':
3491 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3492
3493 # round if necessary, taking rounding mode from the context
3494 rounding = context.rounding
3495 precision = spec['precision']
3496 if precision is not None:
3497 if spec['type'] in 'eE':
3498 self = self._round(precision+1, rounding)
3499 elif spec['type'] in 'gG':
3500 if len(self._int) > precision:
3501 self = self._round(precision, rounding)
3502 elif spec['type'] in 'fF%':
3503 self = self._rescale(-precision, rounding)
3504 # special case: zeros with a positive exponent can't be
3505 # represented in fixed point; rescale them to 0e0.
3506 elif not self and self._exp > 0 and spec['type'] in 'fF%':
3507 self = self._rescale(0, rounding)
3508
3509 # figure out placement of the decimal point
3510 leftdigits = self._exp + len(self._int)
3511 if spec['type'] in 'fF%':
3512 dotplace = leftdigits
3513 elif spec['type'] in 'eE':
3514 if not self and precision is not None:
3515 dotplace = 1 - precision
3516 else:
3517 dotplace = 1
3518 elif spec['type'] in 'gG':
3519 if self._exp <= 0 and leftdigits > -6:
3520 dotplace = leftdigits
3521 else:
3522 dotplace = 1
3523
3524 # figure out main part of numeric string...
3525 if dotplace <= 0:
3526 num = '0.' + '0'*(-dotplace) + self._int
3527 elif dotplace >= len(self._int):
3528 # make sure we're not padding a '0' with extra zeros on the right
3529 assert dotplace==len(self._int) or self._int != '0'
3530 num = self._int + '0'*(dotplace-len(self._int))
3531 else:
3532 num = self._int[:dotplace] + '.' + self._int[dotplace:]
3533
3534 # ...then the trailing exponent, or trailing '%'
3535 if leftdigits != dotplace or spec['type'] in 'eE':
3536 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3537 num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3538 elif spec['type'] == '%':
3539 num = num + '%'
3540
3541 # add sign
3542 if self._sign == 1:
3543 num = '-' + num
3544 return _format_align(num, spec)
3545
3546
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003547def _dec_from_triple(sign, coefficient, exponent, special=False):
3548 """Create a decimal instance directly, without any validation,
3549 normalization (e.g. removal of leading zeros) or argument
3550 conversion.
3551
3552 This function is for *internal use only*.
3553 """
3554
3555 self = object.__new__(Decimal)
3556 self._sign = sign
3557 self._int = coefficient
3558 self._exp = exponent
3559 self._is_special = special
3560
3561 return self
3562
Guido van Rossumd8faa362007-04-27 19:54:29 +00003563##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003564
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003565
3566# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003567rounding_functions = [name for name in Decimal.__dict__.keys()
3568 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003569for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003570 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003571 globalname = name[1:].upper()
3572 val = globals()[globalname]
3573 Decimal._pick_rounding_function[val] = name
3574
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003575del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003576
Thomas Wouters89f507f2006-12-13 04:49:30 +00003577class _ContextManager(object):
3578 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003579
Thomas Wouters89f507f2006-12-13 04:49:30 +00003580 Sets a copy of the supplied context in __enter__() and restores
3581 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003582 """
3583 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003584 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003585 def __enter__(self):
3586 self.saved_context = getcontext()
3587 setcontext(self.new_context)
3588 return self.new_context
3589 def __exit__(self, t, v, tb):
3590 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003591
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003592class Context(object):
3593 """Contains the context for a Decimal instance.
3594
3595 Contains:
3596 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003597 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003598 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003599 raised when it is caused. Otherwise, a value is
3600 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003601 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003602 (Whether or not the trap_enabler is set)
3603 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003604 Emin - Minimum exponent
3605 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003606 capitals - If 1, 1*10^1 is printed as 1E+1.
3607 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003608 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003609 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003610
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003611 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003612 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003613 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003614 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003615 _ignored_flags=None):
3616 if flags is None:
3617 flags = []
3618 if _ignored_flags is None:
3619 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003620 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003621 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003622 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003623 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003624 for name, val in locals().items():
3625 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003626 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003627 else:
3628 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003629 del self.self
3630
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003631 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003632 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003633 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003634 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3635 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3636 % vars(self))
3637 names = [f.__name__ for f, v in self.flags.items() if v]
3638 s.append('flags=[' + ', '.join(names) + ']')
3639 names = [t.__name__ for t, v in self.traps.items() if v]
3640 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003641 return ', '.join(s) + ')'
3642
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003643 def clear_flags(self):
3644 """Reset all flags to zero"""
3645 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003646 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003647
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003648 def _shallow_copy(self):
3649 """Returns a shallow copy from self."""
Christian Heimes2c181612007-12-17 20:04:13 +00003650 nc = Context(self.prec, self.rounding, self.traps,
3651 self.flags, self.Emin, self.Emax,
3652 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003653 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003654
3655 def copy(self):
3656 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003657 nc = Context(self.prec, self.rounding, self.traps.copy(),
Christian Heimes2c181612007-12-17 20:04:13 +00003658 self.flags.copy(), self.Emin, self.Emax,
3659 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003660 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003661 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003662
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003663 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003664 """Handles an error
3665
3666 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003667 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003668 trap_enabler is set, it reaises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00003669 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003670 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003671 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003672 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003673 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003674 return error().handle(self, *args)
3675
Raymond Hettinger86173da2008-02-01 20:38:12 +00003676 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003677 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003678 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003679 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003680
3681 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003682 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003683 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003684
3685 def _ignore_all_flags(self):
3686 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003687 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003688
3689 def _ignore_flags(self, *flags):
3690 """Ignore the flags, if they are raised"""
3691 # Do not mutate-- This way, copies of a context leave the original
3692 # alone.
3693 self._ignored_flags = (self._ignored_flags + list(flags))
3694 return list(flags)
3695
3696 def _regard_flags(self, *flags):
3697 """Stop ignoring the flags, if they are raised"""
3698 if flags and isinstance(flags[0], (tuple,list)):
3699 flags = flags[0]
3700 for flag in flags:
3701 self._ignored_flags.remove(flag)
3702
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003703 def __hash__(self):
3704 """A Context cannot be hashed."""
3705 # We inherit object.__hash__, so we must deny this explicitly
Guido van Rossumd8faa362007-04-27 19:54:29 +00003706 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003707
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003708 def Etiny(self):
3709 """Returns Etiny (= Emin - prec + 1)"""
3710 return int(self.Emin - self.prec + 1)
3711
3712 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003713 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003714 return int(self.Emax - self.prec + 1)
3715
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003716 def _set_rounding(self, type):
3717 """Sets the rounding type.
3718
3719 Sets the rounding type, and returns the current (previous)
3720 rounding type. Often used like:
3721
3722 context = context.copy()
3723 # so you don't change the calling context
3724 # if an error occurs in the middle.
3725 rounding = context._set_rounding(ROUND_UP)
3726 val = self.__sub__(other, context=context)
3727 context._set_rounding(rounding)
3728
3729 This will make it round up for that operation.
3730 """
3731 rounding = self.rounding
3732 self.rounding= type
3733 return rounding
3734
Raymond Hettingerfed52962004-07-14 15:41:57 +00003735 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00003736 """Creates a new Decimal instance but using self as context.
3737
3738 This method implements the to-number operation of the
3739 IBM Decimal specification."""
3740
3741 if isinstance(num, str) and num != num.strip():
3742 return self._raise_error(ConversionSyntax,
3743 "no trailing or leading whitespace is "
3744 "permitted.")
3745
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003746 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003747 if d._isnan() and len(d._int) > self.prec - self._clamp:
3748 return self._raise_error(ConversionSyntax,
3749 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003750 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003751
Guido van Rossumd8faa362007-04-27 19:54:29 +00003752 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003753 def abs(self, a):
3754 """Returns the absolute value of the operand.
3755
3756 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003757 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003758 the plus operation on the operand.
3759
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003760 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003761 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003762 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003763 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003764 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003765 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003766 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003767 Decimal('101.5')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003768 """
3769 return a.__abs__(context=self)
3770
3771 def add(self, a, b):
3772 """Return the sum of the two operands.
3773
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003774 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003775 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003776 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003777 Decimal('1.02E+4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003778 """
3779 return a.__add__(b, context=self)
3780
3781 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003782 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003783
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003784 def canonical(self, a):
3785 """Returns the same Decimal object.
3786
3787 As we do not have different encodings for the same number, the
3788 received object already is in its canonical form.
3789
3790 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003791 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003792 """
3793 return a.canonical(context=self)
3794
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003795 def compare(self, a, b):
3796 """Compares values numerically.
3797
3798 If the signs of the operands differ, a value representing each operand
3799 ('-1' if the operand is less than zero, '0' if the operand is zero or
3800 negative zero, or '1' if the operand is greater than zero) is used in
3801 place of that operand for the comparison instead of the actual
3802 operand.
3803
3804 The comparison is then effected by subtracting the second operand from
3805 the first and then returning a value according to the result of the
3806 subtraction: '-1' if the result is less than zero, '0' if the result is
3807 zero or negative zero, or '1' if the result is greater than zero.
3808
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003809 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003810 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003811 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003812 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003813 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003814 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003815 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003816 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003817 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003818 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003819 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003820 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003821 """
3822 return a.compare(b, context=self)
3823
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003824 def compare_signal(self, a, b):
3825 """Compares the values of the two operands numerically.
3826
3827 It's pretty much like compare(), but all NaNs signal, with signaling
3828 NaNs taking precedence over quiet NaNs.
3829
3830 >>> c = ExtendedContext
3831 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003832 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003833 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003834 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003835 >>> c.flags[InvalidOperation] = 0
3836 >>> print(c.flags[InvalidOperation])
3837 0
3838 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003839 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003840 >>> print(c.flags[InvalidOperation])
3841 1
3842 >>> c.flags[InvalidOperation] = 0
3843 >>> print(c.flags[InvalidOperation])
3844 0
3845 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003846 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003847 >>> print(c.flags[InvalidOperation])
3848 1
3849 """
3850 return a.compare_signal(b, context=self)
3851
3852 def compare_total(self, a, b):
3853 """Compares two operands using their abstract representation.
3854
3855 This is not like the standard compare, which use their numerical
3856 value. Note that a total ordering is defined for all possible abstract
3857 representations.
3858
3859 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003860 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003861 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003862 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003863 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003864 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003865 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003866 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003867 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003868 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003869 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003870 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003871 """
3872 return a.compare_total(b)
3873
3874 def compare_total_mag(self, a, b):
3875 """Compares two operands using their abstract representation ignoring sign.
3876
3877 Like compare_total, but with operand's sign ignored and assumed to be 0.
3878 """
3879 return a.compare_total_mag(b)
3880
3881 def copy_abs(self, a):
3882 """Returns a copy of the operand with the sign set to 0.
3883
3884 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003885 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003886 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003887 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003888 """
3889 return a.copy_abs()
3890
3891 def copy_decimal(self, a):
3892 """Returns a copy of the decimal objet.
3893
3894 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003895 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003896 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003897 Decimal('-1.00')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003898 """
3899 return Decimal(a)
3900
3901 def copy_negate(self, a):
3902 """Returns a copy of the operand with the sign inverted.
3903
3904 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003905 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003906 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003907 Decimal('101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003908 """
3909 return a.copy_negate()
3910
3911 def copy_sign(self, a, b):
3912 """Copies the second operand's sign to the first one.
3913
3914 In detail, it returns a copy of the first operand with the sign
3915 equal to the sign of the second operand.
3916
3917 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003918 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003919 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003920 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003921 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003922 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003923 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003924 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003925 """
3926 return a.copy_sign(b)
3927
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003928 def divide(self, a, b):
3929 """Decimal division in a specified context.
3930
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003931 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003932 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003933 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003934 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003935 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003936 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003937 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003938 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003939 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003940 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003941 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003942 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003943 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003944 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003945 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003946 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003947 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003948 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003949 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003950 Decimal('1.20E+6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003951 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003952 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003953
3954 def divide_int(self, a, b):
3955 """Divides two numbers and returns the integer part of the result.
3956
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003957 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003958 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003959 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003960 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003961 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003962 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003963 """
3964 return a.__floordiv__(b, context=self)
3965
3966 def divmod(self, a, b):
3967 return a.__divmod__(b, context=self)
3968
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003969 def exp(self, a):
3970 """Returns e ** a.
3971
3972 >>> c = ExtendedContext.copy()
3973 >>> c.Emin = -999
3974 >>> c.Emax = 999
3975 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003976 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003977 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003978 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003979 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003980 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003981 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003982 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003983 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003984 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003985 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003986 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003987 """
3988 return a.exp(context=self)
3989
3990 def fma(self, a, b, c):
3991 """Returns a multiplied by b, plus c.
3992
3993 The first two operands are multiplied together, using multiply,
3994 the third operand is then added to the result of that
3995 multiplication, using add, all with only one final rounding.
3996
3997 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003998 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003999 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004000 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004001 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004002 Decimal('1.38435736E+12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004003 """
4004 return a.fma(b, c, context=self)
4005
4006 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004007 """Return True if the operand is canonical; otherwise return False.
4008
4009 Currently, the encoding of a Decimal instance is always
4010 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004011
4012 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004013 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004014 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004015 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004016
4017 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004018 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004019
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004020 A Decimal instance is considered finite if it is neither
4021 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004022
4023 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004024 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004025 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004026 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004027 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004028 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004029 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004030 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004031 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004032 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004033 """
4034 return a.is_finite()
4035
4036 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004037 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004038
4039 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004040 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004041 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004042 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004043 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004044 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004045 """
4046 return a.is_infinite()
4047
4048 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004049 """Return True if the operand is a qNaN or sNaN;
4050 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004051
4052 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004053 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004054 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004055 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004056 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004057 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004058 """
4059 return a.is_nan()
4060
4061 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004062 """Return True if the operand is a normal number;
4063 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004064
4065 >>> c = ExtendedContext.copy()
4066 >>> c.Emin = -999
4067 >>> c.Emax = 999
4068 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004069 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004070 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004071 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004072 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004073 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004074 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004075 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004076 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004077 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004078 """
4079 return a.is_normal(context=self)
4080
4081 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004082 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004083
4084 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004085 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004086 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004087 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004088 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004089 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004090 """
4091 return a.is_qnan()
4092
4093 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004094 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004095
4096 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004097 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004098 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004099 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004100 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004101 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004102 """
4103 return a.is_signed()
4104
4105 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004106 """Return True if the operand is a signaling NaN;
4107 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004108
4109 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004110 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004111 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004112 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004113 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004114 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004115 """
4116 return a.is_snan()
4117
4118 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004119 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004120
4121 >>> c = ExtendedContext.copy()
4122 >>> c.Emin = -999
4123 >>> c.Emax = 999
4124 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004125 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004126 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004127 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004128 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004129 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004130 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004131 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004132 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004133 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004134 """
4135 return a.is_subnormal(context=self)
4136
4137 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004138 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004139
4140 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004141 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004142 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004143 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004144 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004145 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004146 """
4147 return a.is_zero()
4148
4149 def ln(self, a):
4150 """Returns the natural (base e) logarithm of the operand.
4151
4152 >>> c = ExtendedContext.copy()
4153 >>> c.Emin = -999
4154 >>> c.Emax = 999
4155 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004156 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004157 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004158 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004159 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004160 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004161 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004162 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004163 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004164 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004165 """
4166 return a.ln(context=self)
4167
4168 def log10(self, a):
4169 """Returns the base 10 logarithm of the operand.
4170
4171 >>> c = ExtendedContext.copy()
4172 >>> c.Emin = -999
4173 >>> c.Emax = 999
4174 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004175 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004176 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004177 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004178 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004179 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004180 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004181 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004182 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004183 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004184 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004185 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004186 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004187 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004188 """
4189 return a.log10(context=self)
4190
4191 def logb(self, a):
4192 """ Returns the exponent of the magnitude of the operand's MSD.
4193
4194 The result is the integer which is the exponent of the magnitude
4195 of the most significant digit of the operand (as though the
4196 operand were truncated to a single digit while maintaining the
4197 value of that digit and without limiting the resulting exponent).
4198
4199 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004200 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004201 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004202 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004203 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004204 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004205 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004206 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004207 """
4208 return a.logb(context=self)
4209
4210 def logical_and(self, a, b):
4211 """Applies the logical operation 'and' between each operand's digits.
4212
4213 The operands must be both logical numbers.
4214
4215 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004216 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004217 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004218 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004219 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004220 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004221 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004222 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004223 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004224 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004225 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004226 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004227 """
4228 return a.logical_and(b, context=self)
4229
4230 def logical_invert(self, a):
4231 """Invert all the digits in the operand.
4232
4233 The operand must be a logical number.
4234
4235 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004236 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004237 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004238 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004239 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004240 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004241 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004242 Decimal('10101010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004243 """
4244 return a.logical_invert(context=self)
4245
4246 def logical_or(self, a, b):
4247 """Applies the logical operation 'or' between each operand's digits.
4248
4249 The operands must be both logical numbers.
4250
4251 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004252 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004253 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004254 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004255 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004256 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004257 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004258 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004259 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004260 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004261 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004262 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004263 """
4264 return a.logical_or(b, context=self)
4265
4266 def logical_xor(self, a, b):
4267 """Applies the logical operation 'xor' between each operand's digits.
4268
4269 The operands must be both logical numbers.
4270
4271 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004272 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004273 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004274 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004275 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004276 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004277 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004278 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004279 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004280 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004281 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004282 Decimal('1101')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004283 """
4284 return a.logical_xor(b, context=self)
4285
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004286 def max(self, a,b):
4287 """max compares two values numerically and returns the maximum.
4288
4289 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004290 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004291 operation. If they are numerically equal then the left-hand operand
4292 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004293 infinity) of the two operands is chosen as the result.
4294
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004295 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004296 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004297 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004298 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004299 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004300 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004301 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004302 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004303 """
4304 return a.max(b, context=self)
4305
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004306 def max_mag(self, a, b):
4307 """Compares the values numerically with their sign ignored."""
4308 return a.max_mag(b, context=self)
4309
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004310 def min(self, a,b):
4311 """min compares two values numerically and returns the minimum.
4312
4313 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004314 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004315 operation. If they are numerically equal then the left-hand operand
4316 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004317 infinity) of the two operands is chosen as the result.
4318
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004319 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004320 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004321 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004322 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004323 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004324 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004325 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004326 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004327 """
4328 return a.min(b, context=self)
4329
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004330 def min_mag(self, a, b):
4331 """Compares the values numerically with their sign ignored."""
4332 return a.min_mag(b, context=self)
4333
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004334 def minus(self, a):
4335 """Minus corresponds to unary prefix minus in Python.
4336
4337 The operation is evaluated using the same rules as subtract; the
4338 operation minus(a) is calculated as subtract('0', a) where the '0'
4339 has the same exponent as the operand.
4340
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004341 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004342 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004343 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004344 Decimal('1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004345 """
4346 return a.__neg__(context=self)
4347
4348 def multiply(self, a, b):
4349 """multiply multiplies two operands.
4350
4351 If either operand is a special value then the general rules apply.
4352 Otherwise, the operands are multiplied together ('long multiplication'),
4353 resulting in a number which may be as long as the sum of the lengths
4354 of the two operands.
4355
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004356 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004357 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004358 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004359 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004360 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004361 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004362 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004363 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004364 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004365 Decimal('4.28135971E+11')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004366 """
4367 return a.__mul__(b, context=self)
4368
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004369 def next_minus(self, a):
4370 """Returns the largest representable number smaller than a.
4371
4372 >>> c = ExtendedContext.copy()
4373 >>> c.Emin = -999
4374 >>> c.Emax = 999
4375 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004376 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004377 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004378 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004379 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004380 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004381 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004382 Decimal('9.99999999E+999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004383 """
4384 return a.next_minus(context=self)
4385
4386 def next_plus(self, a):
4387 """Returns the smallest representable number larger than a.
4388
4389 >>> c = ExtendedContext.copy()
4390 >>> c.Emin = -999
4391 >>> c.Emax = 999
4392 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004393 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004394 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004395 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004396 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004397 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004398 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004399 Decimal('-9.99999999E+999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004400 """
4401 return a.next_plus(context=self)
4402
4403 def next_toward(self, a, b):
4404 """Returns the number closest to a, in direction towards b.
4405
4406 The result is the closest representable number from the first
4407 operand (but not the first operand) that is in the direction
4408 towards the second operand, unless the operands have the same
4409 value.
4410
4411 >>> c = ExtendedContext.copy()
4412 >>> c.Emin = -999
4413 >>> c.Emax = 999
4414 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004415 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004416 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004417 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004418 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004419 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004420 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004421 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004422 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004423 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004424 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004425 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004426 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004427 Decimal('-0.00')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004428 """
4429 return a.next_toward(b, context=self)
4430
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004431 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004432 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004433
4434 Essentially a plus operation with all trailing zeros removed from the
4435 result.
4436
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004437 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004438 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004439 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004440 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004441 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004442 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004443 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004444 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004445 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004446 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004447 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004448 Decimal('0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004449 """
4450 return a.normalize(context=self)
4451
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004452 def number_class(self, a):
4453 """Returns an indication of the class of the operand.
4454
4455 The class is one of the following strings:
4456 -sNaN
4457 -NaN
4458 -Infinity
4459 -Normal
4460 -Subnormal
4461 -Zero
4462 +Zero
4463 +Subnormal
4464 +Normal
4465 +Infinity
4466
4467 >>> c = Context(ExtendedContext)
4468 >>> c.Emin = -999
4469 >>> c.Emax = 999
4470 >>> c.number_class(Decimal('Infinity'))
4471 '+Infinity'
4472 >>> c.number_class(Decimal('1E-10'))
4473 '+Normal'
4474 >>> c.number_class(Decimal('2.50'))
4475 '+Normal'
4476 >>> c.number_class(Decimal('0.1E-999'))
4477 '+Subnormal'
4478 >>> c.number_class(Decimal('0'))
4479 '+Zero'
4480 >>> c.number_class(Decimal('-0'))
4481 '-Zero'
4482 >>> c.number_class(Decimal('-0.1E-999'))
4483 '-Subnormal'
4484 >>> c.number_class(Decimal('-1E-10'))
4485 '-Normal'
4486 >>> c.number_class(Decimal('-2.50'))
4487 '-Normal'
4488 >>> c.number_class(Decimal('-Infinity'))
4489 '-Infinity'
4490 >>> c.number_class(Decimal('NaN'))
4491 'NaN'
4492 >>> c.number_class(Decimal('-NaN'))
4493 'NaN'
4494 >>> c.number_class(Decimal('sNaN'))
4495 'sNaN'
4496 """
4497 return a.number_class(context=self)
4498
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004499 def plus(self, a):
4500 """Plus corresponds to unary prefix plus in Python.
4501
4502 The operation is evaluated using the same rules as add; the
4503 operation plus(a) is calculated as add('0', a) where the '0'
4504 has the same exponent as the operand.
4505
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004506 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004507 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004508 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004509 Decimal('-1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004510 """
4511 return a.__pos__(context=self)
4512
4513 def power(self, a, b, modulo=None):
4514 """Raises a to the power of b, to modulo if given.
4515
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004516 With two arguments, compute a**b. If a is negative then b
4517 must be integral. The result will be inexact unless b is
4518 integral and the result is finite and can be expressed exactly
4519 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004520
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004521 With three arguments, compute (a**b) % modulo. For the
4522 three argument form, the following restrictions on the
4523 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004524
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004525 - all three arguments must be integral
4526 - b must be nonnegative
4527 - at least one of a or b must be nonzero
4528 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004529
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004530 The result of pow(a, b, modulo) is identical to the result
4531 that would be obtained by computing (a**b) % modulo with
4532 unbounded precision, but is computed more efficiently. It is
4533 always exact.
4534
4535 >>> c = ExtendedContext.copy()
4536 >>> c.Emin = -999
4537 >>> c.Emax = 999
4538 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004539 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004540 >>> c.power(Decimal('-2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004541 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004542 >>> c.power(Decimal('2'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004543 Decimal('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004544 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004545 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004546 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004547 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004548 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004549 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004550 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004551 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004552 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004553 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004554 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004555 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004556 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004557 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004558 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004559 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004560 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004561 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004562 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004563 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004564
4565 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004566 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004567 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004568 Decimal('-11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004569 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004570 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004571 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004572 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004573 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004574 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004575 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004576 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004577 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004578 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004579 """
4580 return a.__pow__(b, modulo, context=self)
4581
4582 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004583 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004584
4585 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004586 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004587 exponent is being increased), multiplied by a positive power of ten (if
4588 the exponent is being decreased), or is unchanged (if the exponent is
4589 already equal to that of the right-hand operand).
4590
4591 Unlike other operations, if the length of the coefficient after the
4592 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004593 operation condition is raised. This guarantees that, unless there is
4594 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004595 equal to that of the right-hand operand.
4596
4597 Also unlike other operations, quantize will never raise Underflow, even
4598 if the result is subnormal and inexact.
4599
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004600 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004601 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004602 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004603 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004604 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004605 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004606 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004607 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004608 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004609 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004610 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004611 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004612 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004613 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004614 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004615 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004616 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004617 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004618 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004619 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004620 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004621 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004622 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004623 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004624 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004625 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004626 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004627 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004628 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004629 Decimal('2E+2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004630 """
4631 return a.quantize(b, context=self)
4632
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004633 def radix(self):
4634 """Just returns 10, as this is Decimal, :)
4635
4636 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004637 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004638 """
4639 return Decimal(10)
4640
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004641 def remainder(self, a, b):
4642 """Returns the remainder from integer division.
4643
4644 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004645 calculating integer division as described for divide-integer, rounded
4646 to precision digits if necessary. The sign of the result, if
4647 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004648
4649 This operation will fail under the same conditions as integer division
4650 (that is, if integer division on the same two operands would fail, the
4651 remainder cannot be calculated).
4652
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004653 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004654 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004655 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004656 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004657 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004658 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004659 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004660 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004661 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004662 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004663 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004664 Decimal('1.0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004665 """
4666 return a.__mod__(b, context=self)
4667
4668 def remainder_near(self, a, b):
4669 """Returns to be "a - b * n", where n is the integer nearest the exact
4670 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004671 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004672 sign of a.
4673
4674 This operation will fail under the same conditions as integer division
4675 (that is, if integer division on the same two operands would fail, the
4676 remainder cannot be calculated).
4677
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004678 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004679 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004680 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004681 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004682 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004683 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004684 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004685 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004686 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004687 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004688 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004689 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004690 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004691 Decimal('-0.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004692 """
4693 return a.remainder_near(b, context=self)
4694
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004695 def rotate(self, a, b):
4696 """Returns a rotated copy of a, b times.
4697
4698 The coefficient of the result is a rotated copy of the digits in
4699 the coefficient of the first operand. The number of places of
4700 rotation is taken from the absolute value of the second operand,
4701 with the rotation being to the left if the second operand is
4702 positive or to the right otherwise.
4703
4704 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004705 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004706 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004707 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004708 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004709 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004710 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004711 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004712 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004713 Decimal('345678912')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004714 """
4715 return a.rotate(b, context=self)
4716
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004717 def same_quantum(self, a, b):
4718 """Returns True if the two operands have the same exponent.
4719
4720 The result is never affected by either the sign or the coefficient of
4721 either operand.
4722
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004723 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004724 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004725 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004726 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004727 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004728 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004729 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004730 True
4731 """
4732 return a.same_quantum(b)
4733
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004734 def scaleb (self, a, b):
4735 """Returns the first operand after adding the second value its exp.
4736
4737 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004738 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004739 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004740 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004741 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004742 Decimal('7.50E+3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004743 """
4744 return a.scaleb (b, context=self)
4745
4746 def shift(self, a, b):
4747 """Returns a shifted copy of a, b times.
4748
4749 The coefficient of the result is a shifted copy of the digits
4750 in the coefficient of the first operand. The number of places
4751 to shift is taken from the absolute value of the second operand,
4752 with the shift being to the left if the second operand is
4753 positive or to the right otherwise. Digits shifted into the
4754 coefficient are zeros.
4755
4756 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004757 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004758 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004759 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004760 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004761 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004762 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004763 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004764 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004765 Decimal('345678900')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004766 """
4767 return a.shift(b, context=self)
4768
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004769 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004770 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004771
4772 If the result must be inexact, it is rounded using the round-half-even
4773 algorithm.
4774
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004775 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004776 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004777 >>> ExtendedContext.sqrt(Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004778 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004779 >>> ExtendedContext.sqrt(Decimal('0.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004780 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004781 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004782 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004783 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004784 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004785 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004786 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004787 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004788 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004789 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004790 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004791 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004792 Decimal('3.16227766')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004793 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004794 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004795 """
4796 return a.sqrt(context=self)
4797
4798 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004799 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004800
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004801 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004802 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004803 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004804 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004805 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004806 Decimal('-0.77')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004807 """
4808 return a.__sub__(b, context=self)
4809
4810 def to_eng_string(self, a):
4811 """Converts a number to a string, using scientific notation.
4812
4813 The operation is not affected by the context.
4814 """
4815 return a.to_eng_string(context=self)
4816
4817 def to_sci_string(self, a):
4818 """Converts a number to a string, using scientific notation.
4819
4820 The operation is not affected by the context.
4821 """
4822 return a.__str__(context=self)
4823
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004824 def to_integral_exact(self, a):
4825 """Rounds to an integer.
4826
4827 When the operand has a negative exponent, the result is the same
4828 as using the quantize() operation using the given operand as the
4829 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4830 of the operand as the precision setting; Inexact and Rounded flags
4831 are allowed in this operation. The rounding mode is taken from the
4832 context.
4833
4834 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004835 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004836 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004837 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004838 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004839 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004840 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004841 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004842 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004843 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004844 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004845 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004846 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004847 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004848 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004849 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004850 """
4851 return a.to_integral_exact(context=self)
4852
4853 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004854 """Rounds to an integer.
4855
4856 When the operand has a negative exponent, the result is the same
4857 as using the quantize() operation using the given operand as the
4858 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4859 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004860 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004861
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004862 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004863 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004864 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004865 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004866 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004867 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004868 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004869 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004870 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004871 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004872 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004873 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004874 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004875 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004876 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004877 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004878 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004879 return a.to_integral_value(context=self)
4880
4881 # the method name changed, but we provide also the old one, for compatibility
4882 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004883
4884class _WorkRep(object):
4885 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004886 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004887 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004888 # exp: None, int, or string
4889
4890 def __init__(self, value=None):
4891 if value is None:
4892 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004893 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004894 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004895 elif isinstance(value, Decimal):
4896 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00004897 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004898 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004899 else:
4900 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004901 self.sign = value[0]
4902 self.int = value[1]
4903 self.exp = value[2]
4904
4905 def __repr__(self):
4906 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4907
4908 __str__ = __repr__
4909
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004910
4911
Christian Heimes2c181612007-12-17 20:04:13 +00004912def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004913 """Normalizes op1, op2 to have the same exp and length of coefficient.
4914
4915 Done during addition.
4916 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004917 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004918 tmp = op2
4919 other = op1
4920 else:
4921 tmp = op1
4922 other = op2
4923
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004924 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4925 # Then adding 10**exp to tmp has the same effect (after rounding)
4926 # as adding any positive quantity smaller than 10**exp; similarly
4927 # for subtraction. So if other is smaller than 10**exp we replace
4928 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00004929 tmp_len = len(str(tmp.int))
4930 other_len = len(str(other.int))
4931 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4932 if other_len + other.exp - 1 < exp:
4933 other.int = 1
4934 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004935
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004936 tmp.int *= 10 ** (tmp.exp - other.exp)
4937 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004938 return op1, op2
4939
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004940##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004941
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004942# This function from Tim Peters was taken from here:
4943# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4944# The correction being in the function definition is for speed, and
4945# the whole function is not resolved with math.log because of avoiding
4946# the use of floats.
4947def _nbits(n, correction = {
4948 '0': 4, '1': 3, '2': 2, '3': 2,
4949 '4': 1, '5': 1, '6': 1, '7': 1,
4950 '8': 0, '9': 0, 'a': 0, 'b': 0,
4951 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4952 """Number of bits in binary representation of the positive integer n,
4953 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004954 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004955 if n < 0:
4956 raise ValueError("The argument to _nbits should be nonnegative.")
4957 hex_n = "%x" % n
4958 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004959
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004960def _sqrt_nearest(n, a):
4961 """Closest integer to the square root of the positive integer n. a is
4962 an initial approximation to the square root. Any positive integer
4963 will do for a, but the closer a is to the square root of n the
4964 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004965
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004966 """
4967 if n <= 0 or a <= 0:
4968 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4969
4970 b=0
4971 while a != b:
4972 b, a = a, a--n//a>>1
4973 return a
4974
4975def _rshift_nearest(x, shift):
4976 """Given an integer x and a nonnegative integer shift, return closest
4977 integer to x / 2**shift; use round-to-even in case of a tie.
4978
4979 """
4980 b, q = 1 << shift, x >> shift
4981 return q + (2*(x & (b-1)) + (q&1) > b)
4982
4983def _div_nearest(a, b):
4984 """Closest integer to a/b, a and b positive integers; rounds to even
4985 in the case of a tie.
4986
4987 """
4988 q, r = divmod(a, b)
4989 return q + (2*r + (q&1) > b)
4990
4991def _ilog(x, M, L = 8):
4992 """Integer approximation to M*log(x/M), with absolute error boundable
4993 in terms only of x/M.
4994
4995 Given positive integers x and M, return an integer approximation to
4996 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4997 between the approximation and the exact result is at most 22. For
4998 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4999 both cases these are upper bounds on the error; it will usually be
5000 much smaller."""
5001
5002 # The basic algorithm is the following: let log1p be the function
5003 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5004 # the reduction
5005 #
5006 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5007 #
5008 # repeatedly until the argument to log1p is small (< 2**-L in
5009 # absolute value). For small y we can use the Taylor series
5010 # expansion
5011 #
5012 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5013 #
5014 # truncating at T such that y**T is small enough. The whole
5015 # computation is carried out in a form of fixed-point arithmetic,
5016 # with a real number z being represented by an integer
5017 # approximation to z*M. To avoid loss of precision, the y below
5018 # is actually an integer approximation to 2**R*y*M, where R is the
5019 # number of reductions performed so far.
5020
5021 y = x-M
5022 # argument reduction; R = number of reductions performed
5023 R = 0
5024 while (R <= L and abs(y) << L-R >= M or
5025 R > L and abs(y) >> R-L >= M):
5026 y = _div_nearest((M*y) << 1,
5027 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5028 R += 1
5029
5030 # Taylor series with T terms
5031 T = -int(-10*len(str(M))//(3*L))
5032 yshift = _rshift_nearest(y, R)
5033 w = _div_nearest(M, T)
5034 for k in range(T-1, 0, -1):
5035 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5036
5037 return _div_nearest(w*y, M)
5038
5039def _dlog10(c, e, p):
5040 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5041 approximation to 10**p * log10(c*10**e), with an absolute error of
5042 at most 1. Assumes that c*10**e is not exactly 1."""
5043
5044 # increase precision by 2; compensate for this by dividing
5045 # final result by 100
5046 p += 2
5047
5048 # write c*10**e as d*10**f with either:
5049 # f >= 0 and 1 <= d <= 10, or
5050 # f <= 0 and 0.1 <= d <= 1.
5051 # Thus for c*10**e close to 1, f = 0
5052 l = len(str(c))
5053 f = e+l - (e+l >= 1)
5054
5055 if p > 0:
5056 M = 10**p
5057 k = e+p-f
5058 if k >= 0:
5059 c *= 10**k
5060 else:
5061 c = _div_nearest(c, 10**-k)
5062
5063 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005064 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005065 log_d = _div_nearest(log_d*M, log_10)
5066 log_tenpower = f*M # exact
5067 else:
5068 log_d = 0 # error < 2.31
5069 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
5070
5071 return _div_nearest(log_tenpower+log_d, 100)
5072
5073def _dlog(c, e, p):
5074 """Given integers c, e and p with c > 0, compute an integer
5075 approximation to 10**p * log(c*10**e), with an absolute error of
5076 at most 1. Assumes that c*10**e is not exactly 1."""
5077
5078 # Increase precision by 2. The precision increase is compensated
5079 # for at the end with a division by 100.
5080 p += 2
5081
5082 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5083 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5084 # as 10**p * log(d) + 10**p*f * log(10).
5085 l = len(str(c))
5086 f = e+l - (e+l >= 1)
5087
5088 # compute approximation to 10**p*log(d), with error < 27
5089 if p > 0:
5090 k = e+p-f
5091 if k >= 0:
5092 c *= 10**k
5093 else:
5094 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5095
5096 # _ilog magnifies existing error in c by a factor of at most 10
5097 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5098 else:
5099 # p <= 0: just approximate the whole thing by 0; error < 2.31
5100 log_d = 0
5101
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005102 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005103 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005104 extra = len(str(abs(f)))-1
5105 if p + extra >= 0:
5106 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5107 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5108 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005109 else:
5110 f_log_ten = 0
5111 else:
5112 f_log_ten = 0
5113
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005114 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005115 return _div_nearest(f_log_ten + log_d, 100)
5116
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005117class _Log10Memoize(object):
5118 """Class to compute, store, and allow retrieval of, digits of the
5119 constant log(10) = 2.302585.... This constant is needed by
5120 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5121 def __init__(self):
5122 self.digits = "23025850929940456840179914546843642076011014886"
5123
5124 def getdigits(self, p):
5125 """Given an integer p >= 0, return floor(10**p)*log(10).
5126
5127 For example, self.getdigits(3) returns 2302.
5128 """
5129 # digits are stored as a string, for quick conversion to
5130 # integer in the case that we've already computed enough
5131 # digits; the stored digits should always be correct
5132 # (truncated, not rounded to nearest).
5133 if p < 0:
5134 raise ValueError("p should be nonnegative")
5135
5136 if p >= len(self.digits):
5137 # compute p+3, p+6, p+9, ... digits; continue until at
5138 # least one of the extra digits is nonzero
5139 extra = 3
5140 while True:
5141 # compute p+extra digits, correct to within 1ulp
5142 M = 10**(p+extra+2)
5143 digits = str(_div_nearest(_ilog(10*M, M), 100))
5144 if digits[-extra:] != '0'*extra:
5145 break
5146 extra += 3
5147 # keep all reliable digits so far; remove trailing zeros
5148 # and next nonzero digit
5149 self.digits = digits.rstrip('0')[:-1]
5150 return int(self.digits[:p+1])
5151
5152_log10_digits = _Log10Memoize().getdigits
5153
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005154def _iexp(x, M, L=8):
5155 """Given integers x and M, M > 0, such that x/M is small in absolute
5156 value, compute an integer approximation to M*exp(x/M). For 0 <=
5157 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5158 is usually much smaller)."""
5159
5160 # Algorithm: to compute exp(z) for a real number z, first divide z
5161 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5162 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5163 # series
5164 #
5165 # expm1(x) = x + x**2/2! + x**3/3! + ...
5166 #
5167 # Now use the identity
5168 #
5169 # expm1(2x) = expm1(x)*(expm1(x)+2)
5170 #
5171 # R times to compute the sequence expm1(z/2**R),
5172 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5173
5174 # Find R such that x/2**R/M <= 2**-L
5175 R = _nbits((x<<L)//M)
5176
5177 # Taylor series. (2**L)**T > M
5178 T = -int(-10*len(str(M))//(3*L))
5179 y = _div_nearest(x, T)
5180 Mshift = M<<R
5181 for i in range(T-1, 0, -1):
5182 y = _div_nearest(x*(Mshift + y), Mshift * i)
5183
5184 # Expansion
5185 for k in range(R-1, -1, -1):
5186 Mshift = M<<(k+2)
5187 y = _div_nearest(y*(y+Mshift), Mshift)
5188
5189 return M+y
5190
5191def _dexp(c, e, p):
5192 """Compute an approximation to exp(c*10**e), with p decimal places of
5193 precision.
5194
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005195 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005196
5197 10**(p-1) <= d <= 10**p, and
5198 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5199
5200 In other words, d*10**f is an approximation to exp(c*10**e) with p
5201 digits of precision, and with an error in d of at most 1. This is
5202 almost, but not quite, the same as the error being < 1ulp: when d
5203 = 10**(p-1) the error could be up to 10 ulp."""
5204
5205 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5206 p += 2
5207
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005208 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005209 extra = max(0, e + len(str(c)) - 1)
5210 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005211
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005212 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005213 # rounding down
5214 shift = e+q
5215 if shift >= 0:
5216 cshift = c*10**shift
5217 else:
5218 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005219 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005220
5221 # reduce remainder back to original precision
5222 rem = _div_nearest(rem, 10**extra)
5223
5224 # error in result of _iexp < 120; error after division < 0.62
5225 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5226
5227def _dpower(xc, xe, yc, ye, p):
5228 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5229 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5230
5231 10**(p-1) <= c <= 10**p, and
5232 (c-1)*10**e < x**y < (c+1)*10**e
5233
5234 in other words, c*10**e is an approximation to x**y with p digits
5235 of precision, and with an error in c of at most 1. (This is
5236 almost, but not quite, the same as the error being < 1ulp: when c
5237 == 10**(p-1) we can only guarantee error < 10ulp.)
5238
5239 We assume that: x is positive and not equal to 1, and y is nonzero.
5240 """
5241
5242 # Find b such that 10**(b-1) <= |y| <= 10**b
5243 b = len(str(abs(yc))) + ye
5244
5245 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5246 lxc = _dlog(xc, xe, p+b+1)
5247
5248 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5249 shift = ye-b
5250 if shift >= 0:
5251 pc = lxc*yc*10**shift
5252 else:
5253 pc = _div_nearest(lxc*yc, 10**-shift)
5254
5255 if pc == 0:
5256 # we prefer a result that isn't exactly 1; this makes it
5257 # easier to compute a correctly rounded result in __pow__
5258 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5259 coeff, exp = 10**(p-1)+1, 1-p
5260 else:
5261 coeff, exp = 10**p-1, -p
5262 else:
5263 coeff, exp = _dexp(pc, -(p+1), p+1)
5264 coeff = _div_nearest(coeff, 10)
5265 exp += 1
5266
5267 return coeff, exp
5268
5269def _log10_lb(c, correction = {
5270 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5271 '6': 23, '7': 16, '8': 10, '9': 5}):
5272 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5273 if c <= 0:
5274 raise ValueError("The argument to _log10_lb should be nonnegative.")
5275 str_c = str(c)
5276 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005277
Guido van Rossumd8faa362007-04-27 19:54:29 +00005278##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005279
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005280def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005281 """Convert other to Decimal.
5282
5283 Verifies that it's ok to use in an implicit construction.
5284 """
5285 if isinstance(other, Decimal):
5286 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005287 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005288 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005289 if raiseit:
5290 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005291 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005292
Guido van Rossumd8faa362007-04-27 19:54:29 +00005293##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005294
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005295# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005296# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005297
5298DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005299 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005300 traps=[DivisionByZero, Overflow, InvalidOperation],
5301 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005302 Emax=999999999,
5303 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005304 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005305)
5306
5307# Pre-made alternate contexts offered by the specification
5308# Don't change these; the user should be able to select these
5309# contexts and be able to reproduce results from other implementations
5310# of the spec.
5311
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005312BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005313 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005314 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5315 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005316)
5317
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005318ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005319 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005320 traps=[],
5321 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005322)
5323
5324
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005325##### crud for parsing strings #############################################
Christian Heimes23daade02008-02-25 12:39:23 +00005326#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005327# Regular expression used for parsing numeric strings. Additional
5328# comments:
5329#
5330# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5331# whitespace. But note that the specification disallows whitespace in
5332# a numeric string.
5333#
5334# 2. For finite numbers (not infinities and NaNs) the body of the
5335# number between the optional sign and the optional exponent must have
5336# at least one decimal digit, possibly after the decimal point. The
5337# lookahead expression '(?=\d|\.\d)' checks this.
5338#
5339# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5340# other meaning for \d than the numbers [0-9].
5341
5342import re
5343_parser = re.compile(r""" # A numeric string consists of:
5344# \s*
5345 (?P<sign>[-+])? # an optional sign, followed by either...
5346 (
5347 (?=\d|\.\d) # ...a number (with at least one digit)
5348 (?P<int>\d*) # consisting of a (possibly empty) integer part
5349 (\.(?P<frac>\d*))? # followed by an optional fractional part
5350 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5351 |
5352 Inf(inity)? # ...an infinity, or...
5353 |
5354 (?P<signal>s)? # ...an (optionally signaling)
5355 NaN # NaN
5356 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5357 )
5358# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00005359 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005360""", re.VERBOSE | re.IGNORECASE).match
5361
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005362_all_zeros = re.compile('0*$').match
5363_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00005364
5365##### PEP3101 support functions ##############################################
5366# The functions parse_format_specifier and format_align have little to do
5367# with the Decimal class, and could potentially be reused for other pure
5368# Python numeric classes that want to implement __format__
5369#
5370# A format specifier for Decimal looks like:
5371#
5372# [[fill]align][sign][0][minimumwidth][.precision][type]
5373#
5374
5375_parse_format_specifier_regex = re.compile(r"""\A
5376(?:
5377 (?P<fill>.)?
5378 (?P<align>[<>=^])
5379)?
5380(?P<sign>[-+ ])?
5381(?P<zeropad>0)?
5382(?P<minimumwidth>(?!0)\d+)?
5383(?:\.(?P<precision>0|(?!0)\d+))?
5384(?P<type>[eEfFgG%])?
5385\Z
5386""", re.VERBOSE)
5387
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005388del re
5389
Christian Heimesf16baeb2008-02-29 14:57:44 +00005390def _parse_format_specifier(format_spec):
5391 """Parse and validate a format specifier.
5392
5393 Turns a standard numeric format specifier into a dict, with the
5394 following entries:
5395
5396 fill: fill character to pad field to minimum width
5397 align: alignment type, either '<', '>', '=' or '^'
5398 sign: either '+', '-' or ' '
5399 minimumwidth: nonnegative integer giving minimum width
5400 precision: nonnegative integer giving precision, or None
5401 type: one of the characters 'eEfFgG%', or None
5402 unicode: either True or False (always True for Python 3.x)
5403
5404 """
5405 m = _parse_format_specifier_regex.match(format_spec)
5406 if m is None:
5407 raise ValueError("Invalid format specifier: " + format_spec)
5408
5409 # get the dictionary
5410 format_dict = m.groupdict()
5411
5412 # defaults for fill and alignment
5413 fill = format_dict['fill']
5414 align = format_dict['align']
5415 if format_dict.pop('zeropad') is not None:
5416 # in the face of conflict, refuse the temptation to guess
5417 if fill is not None and fill != '0':
5418 raise ValueError("Fill character conflicts with '0'"
5419 " in format specifier: " + format_spec)
5420 if align is not None and align != '=':
5421 raise ValueError("Alignment conflicts with '0' in "
5422 "format specifier: " + format_spec)
5423 fill = '0'
5424 align = '='
5425 format_dict['fill'] = fill or ' '
5426 format_dict['align'] = align or '<'
5427
5428 if format_dict['sign'] is None:
5429 format_dict['sign'] = '-'
5430
5431 # turn minimumwidth and precision entries into integers.
5432 # minimumwidth defaults to 0; precision remains None if not given
5433 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5434 if format_dict['precision'] is not None:
5435 format_dict['precision'] = int(format_dict['precision'])
5436
5437 # if format type is 'g' or 'G' then a precision of 0 makes little
5438 # sense; convert it to 1. Same if format type is unspecified.
5439 if format_dict['precision'] == 0:
5440 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5441 format_dict['precision'] = 1
5442
5443 # record whether return type should be str or unicode
Christian Heimes295f4fa2008-02-29 15:03:39 +00005444 format_dict['unicode'] = True
Christian Heimesf16baeb2008-02-29 14:57:44 +00005445
5446 return format_dict
5447
5448def _format_align(body, spec_dict):
5449 """Given an unpadded, non-aligned numeric string, add padding and
5450 aligment to conform with the given format specifier dictionary (as
5451 output from parse_format_specifier).
5452
5453 It's assumed that if body is negative then it starts with '-'.
5454 Any leading sign ('-' or '+') is stripped from the body before
5455 applying the alignment and padding rules, and replaced in the
5456 appropriate position.
5457
5458 """
5459 # figure out the sign; we only examine the first character, so if
5460 # body has leading whitespace the results may be surprising.
5461 if len(body) > 0 and body[0] in '-+':
5462 sign = body[0]
5463 body = body[1:]
5464 else:
5465 sign = ''
5466
5467 if sign != '-':
5468 if spec_dict['sign'] in ' +':
5469 sign = spec_dict['sign']
5470 else:
5471 sign = ''
5472
5473 # how much extra space do we have to play with?
5474 minimumwidth = spec_dict['minimumwidth']
5475 fill = spec_dict['fill']
5476 padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5477
5478 align = spec_dict['align']
5479 if align == '<':
5480 result = padding + sign + body
5481 elif align == '>':
5482 result = sign + body + padding
5483 elif align == '=':
5484 result = sign + padding + body
5485 else: #align == '^'
5486 half = len(padding)//2
5487 result = padding[:half] + sign + body + padding[half:]
5488
Christian Heimesf16baeb2008-02-29 14:57:44 +00005489 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005490
Guido van Rossumd8faa362007-04-27 19:54:29 +00005491##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005492
Guido van Rossumd8faa362007-04-27 19:54:29 +00005493# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005494Inf = Decimal('Inf')
5495negInf = Decimal('-Inf')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005496NaN = Decimal('NaN')
5497Dec_0 = Decimal(0)
5498Dec_p1 = Decimal(1)
5499Dec_n1 = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005500
Guido van Rossumd8faa362007-04-27 19:54:29 +00005501# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005502Infsign = (Inf, negInf)
5503
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005504
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005505
5506if __name__ == '__main__':
5507 import doctest, sys
5508 doctest.testmod(sys.modules[__name__])