blob: f008b5a2c2786b0a2d83290bf84325226dd773b1 [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
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000481 >>> setcontext(DefaultContext)
Guido van Rossum7131f842007-02-09 20:13:25 +0000482 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000483 28
484 >>> with localcontext():
485 ... ctx = getcontext()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000486 ... ctx.prec += 2
Guido van Rossum7131f842007-02-09 20:13:25 +0000487 ... print(ctx.prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000488 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000489 30
490 >>> with localcontext(ExtendedContext):
Guido van Rossum7131f842007-02-09 20:13:25 +0000491 ... print(getcontext().prec)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000492 ...
Thomas Wouters89f507f2006-12-13 04:49:30 +0000493 9
Guido van Rossum7131f842007-02-09 20:13:25 +0000494 >>> print(getcontext().prec)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000495 28
496 """
497 if ctx is None: ctx = getcontext()
498 return _ContextManager(ctx)
499
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000500
Guido van Rossumd8faa362007-04-27 19:54:29 +0000501##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000502
Christian Heimes08976cb2008-03-16 00:32:36 +0000503class Decimal(_numbers.Real):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000504 """Floating point class for decimal arithmetic."""
505
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000506 __slots__ = ('_exp','_int','_sign', '_is_special')
507 # Generally, the value of the Decimal instance is given by
508 # (-1)**_sign * _int * 10**_exp
509 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000510
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000511 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000512 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000513 """Create a decimal point instance.
514
515 >>> Decimal('3.14') # string input
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000516 Decimal('3.14')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000517 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000518 Decimal('3.14')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000519 >>> Decimal(314) # int
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000520 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000521 >>> Decimal(Decimal(314)) # another decimal instance
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000522 Decimal('314')
Christian Heimesa62da1d2008-01-12 19:39:10 +0000523 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000524 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000525 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000526
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000527 # Note that the coefficient, self._int, is actually stored as
528 # a string rather than as a tuple of digits. This speeds up
529 # the "digits to integer" and "integer to digits" conversions
530 # that are used in almost every arithmetic operation on
531 # Decimals. This is an internal detail: the as_tuple function
532 # and the Decimal constructor still deal with tuples of
533 # digits.
534
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000535 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000536
Christian Heimesd59c64c2007-11-30 19:27:20 +0000537 # From a string
538 # REs insist on real strings, so we can too.
539 if isinstance(value, str):
Christian Heimesa62da1d2008-01-12 19:39:10 +0000540 m = _parser(value.strip())
Christian Heimesd59c64c2007-11-30 19:27:20 +0000541 if m is None:
542 if context is None:
543 context = getcontext()
544 return context._raise_error(ConversionSyntax,
545 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000546
Christian Heimesd59c64c2007-11-30 19:27:20 +0000547 if m.group('sign') == "-":
548 self._sign = 1
549 else:
550 self._sign = 0
551 intpart = m.group('int')
552 if intpart is not None:
553 # finite number
554 fracpart = m.group('frac')
555 exp = int(m.group('exp') or '0')
556 if fracpart is not None:
557 self._int = (intpart+fracpart).lstrip('0') or '0'
558 self._exp = exp - len(fracpart)
559 else:
560 self._int = intpart.lstrip('0') or '0'
561 self._exp = exp
562 self._is_special = False
563 else:
564 diag = m.group('diag')
565 if diag is not None:
566 # NaN
567 self._int = diag.lstrip('0')
568 if m.group('signal'):
569 self._exp = 'N'
570 else:
571 self._exp = 'n'
572 else:
573 # infinity
574 self._int = '0'
575 self._exp = 'F'
576 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000577 return self
578
579 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000580 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000581 if value >= 0:
582 self._sign = 0
583 else:
584 self._sign = 1
585 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000586 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000587 self._is_special = False
588 return self
589
590 # From another decimal
591 if isinstance(value, Decimal):
592 self._exp = value._exp
593 self._sign = value._sign
594 self._int = value._int
595 self._is_special = value._is_special
596 return self
597
598 # From an internal working value
599 if isinstance(value, _WorkRep):
600 self._sign = value.sign
601 self._int = str(value.int)
602 self._exp = int(value.exp)
603 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000604 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000605
606 # tuple/list conversion (possibly from as_tuple())
607 if isinstance(value, (list,tuple)):
608 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000609 raise ValueError('Invalid tuple size in creation of Decimal '
610 'from list or tuple. The list or tuple '
611 'should have exactly three elements.')
612 # process sign. The isinstance test rejects floats
613 if not (isinstance(value[0], int) and value[0] in (0,1)):
614 raise ValueError("Invalid sign. The first value in the tuple "
615 "should be an integer; either 0 for a "
616 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000617 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000618 if value[2] == 'F':
619 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000620 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000621 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000622 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000623 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000624 # process and validate the digits in value[1]
625 digits = []
626 for digit in value[1]:
627 if isinstance(digit, int) and 0 <= digit <= 9:
628 # skip leading zeros
629 if digits or digit != 0:
630 digits.append(digit)
631 else:
632 raise ValueError("The second value in the tuple must "
633 "be composed of integers in the range "
634 "0 through 9.")
635 if value[2] in ('n', 'N'):
636 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000637 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000638 self._exp = value[2]
639 self._is_special = True
640 elif isinstance(value[2], int):
641 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000642 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000643 self._exp = value[2]
644 self._is_special = False
645 else:
646 raise ValueError("The third value in the tuple must "
647 "be an integer, or one of the "
648 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000649 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000650
Raymond Hettingerbf440692004-07-10 14:14:37 +0000651 if isinstance(value, float):
652 raise TypeError("Cannot convert float to Decimal. " +
653 "First convert the float to a string")
654
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000655 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000656
657 def _isnan(self):
658 """Returns whether the number is not actually one.
659
660 0 if a number
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000661 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000662 2 if sNaN
663 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000664 if self._is_special:
665 exp = self._exp
666 if exp == 'n':
667 return 1
668 elif exp == 'N':
669 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000670 return 0
671
672 def _isinfinity(self):
673 """Returns whether the number is infinite
674
675 0 if finite or not a number
676 1 if +INF
677 -1 if -INF
678 """
679 if self._exp == 'F':
680 if self._sign:
681 return -1
682 return 1
683 return 0
684
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000685 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000686 """Returns whether the number is not actually one.
687
688 if self, other are sNaN, signal
689 if self, other are NaN return nan
690 return 0
691
692 Done before operations.
693 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000694
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000695 self_is_nan = self._isnan()
696 if other is None:
697 other_is_nan = False
698 else:
699 other_is_nan = other._isnan()
700
701 if self_is_nan or other_is_nan:
702 if context is None:
703 context = getcontext()
704
705 if self_is_nan == 2:
706 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000707 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000708 if other_is_nan == 2:
709 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000710 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000711 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000712 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000713
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000714 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000715 return 0
716
Christian Heimes77c02eb2008-02-09 02:18:51 +0000717 def _compare_check_nans(self, other, context):
718 """Version of _check_nans used for the signaling comparisons
719 compare_signal, __le__, __lt__, __ge__, __gt__.
720
721 Signal InvalidOperation if either self or other is a (quiet
722 or signaling) NaN. Signaling NaNs take precedence over quiet
723 NaNs.
724
725 Return 0 if neither operand is a NaN.
726
727 """
728 if context is None:
729 context = getcontext()
730
731 if self._is_special or other._is_special:
732 if self.is_snan():
733 return context._raise_error(InvalidOperation,
734 'comparison involving sNaN',
735 self)
736 elif other.is_snan():
737 return context._raise_error(InvalidOperation,
738 'comparison involving sNaN',
739 other)
740 elif self.is_qnan():
741 return context._raise_error(InvalidOperation,
742 'comparison involving NaN',
743 self)
744 elif other.is_qnan():
745 return context._raise_error(InvalidOperation,
746 'comparison involving NaN',
747 other)
748 return 0
749
Jack Diederich4dafcc42006-11-28 19:15:13 +0000750 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000751 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000752
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000753 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000754 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000755 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000756
Christian Heimes77c02eb2008-02-09 02:18:51 +0000757 def _cmp(self, other):
758 """Compare the two non-NaN decimal instances self and other.
759
760 Returns -1 if self < other, 0 if self == other and 1
761 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000762
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000763 if self._is_special or other._is_special:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000764 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000765
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000766 # check for zeros; note that cmp(0, -0) should return 0
767 if not self:
768 if not other:
769 return 0
770 else:
771 return -((-1)**other._sign)
772 if not other:
773 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000774
Guido van Rossumd8faa362007-04-27 19:54:29 +0000775 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000776 if other._sign < self._sign:
777 return -1
778 if self._sign < other._sign:
779 return 1
780
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000781 self_adjusted = self.adjusted()
782 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000783 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000784 self_padded = self._int + '0'*(self._exp - other._exp)
785 other_padded = other._int + '0'*(other._exp - self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000786 return cmp(self_padded, other_padded) * (-1)**self._sign
787 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000788 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000789 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000790 return -((-1)**self._sign)
791
Christian Heimes77c02eb2008-02-09 02:18:51 +0000792 # Note: The Decimal standard doesn't cover rich comparisons for
793 # Decimals. In particular, the specification is silent on the
794 # subject of what should happen for a comparison involving a NaN.
795 # We take the following approach:
796 #
797 # == comparisons involving a NaN always return False
798 # != comparisons involving a NaN always return True
799 # <, >, <= and >= comparisons involving a (quiet or signaling)
800 # NaN signal InvalidOperation, and return False if the
Christian Heimes3feef612008-02-11 06:19:17 +0000801 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000802 #
803 # This behavior is designed to conform as closely as possible to
804 # that specified by IEEE 754.
805
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000806 def __eq__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000807 other = _convert_other(other)
808 if other is NotImplemented:
809 return other
810 if self.is_nan() or other.is_nan():
811 return False
812 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000813
814 def __ne__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000815 other = _convert_other(other)
816 if other is NotImplemented:
817 return other
818 if self.is_nan() or other.is_nan():
819 return True
820 return self._cmp(other) != 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000821
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000822
Christian Heimes77c02eb2008-02-09 02:18:51 +0000823 def __lt__(self, other, context=None):
824 other = _convert_other(other)
825 if other is NotImplemented:
826 return other
827 ans = self._compare_check_nans(other, context)
828 if ans:
829 return False
830 return self._cmp(other) < 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000831
Christian Heimes77c02eb2008-02-09 02:18:51 +0000832 def __le__(self, other, context=None):
833 other = _convert_other(other)
834 if other is NotImplemented:
835 return other
836 ans = self._compare_check_nans(other, context)
837 if ans:
838 return False
839 return self._cmp(other) <= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000840
Christian Heimes77c02eb2008-02-09 02:18:51 +0000841 def __gt__(self, other, context=None):
842 other = _convert_other(other)
843 if other is NotImplemented:
844 return other
845 ans = self._compare_check_nans(other, context)
846 if ans:
847 return False
848 return self._cmp(other) > 0
849
850 def __ge__(self, other, context=None):
851 other = _convert_other(other)
852 if other is NotImplemented:
853 return other
854 ans = self._compare_check_nans(other, context)
855 if ans:
856 return False
857 return self._cmp(other) >= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000858
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000859 def compare(self, other, context=None):
860 """Compares one to another.
861
862 -1 => a < b
863 0 => a = b
864 1 => a > b
865 NaN => one is NaN
866 Like __cmp__, but returns Decimal instances.
867 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000868 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000869
Guido van Rossumd8faa362007-04-27 19:54:29 +0000870 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000871 if (self._is_special or other and other._is_special):
872 ans = self._check_nans(other, context)
873 if ans:
874 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000875
Christian Heimes77c02eb2008-02-09 02:18:51 +0000876 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000877
878 def __hash__(self):
879 """x.__hash__() <==> hash(x)"""
880 # Decimal integers must hash the same as the ints
Christian Heimes2380ac72008-01-09 00:17:24 +0000881 #
882 # The hash of a nonspecial noninteger Decimal must depend only
883 # on the value of that Decimal, and not on its representation.
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000884 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000885 if self._is_special:
886 if self._isnan():
887 raise TypeError('Cannot hash a NaN value.')
888 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000889 if not self:
890 return 0
891 if self._isinteger():
892 op = _WorkRep(self.to_integral_value())
893 # to make computation feasible for Decimals with large
894 # exponent, we use the fact that hash(n) == hash(m) for
895 # any two nonzero integers n and m such that (i) n and m
896 # have the same sign, and (ii) n is congruent to m modulo
897 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
898 # hash((-1)**s*c*pow(10, e, 2**64-1).
899 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Christian Heimes2380ac72008-01-09 00:17:24 +0000900 # The value of a nonzero nonspecial Decimal instance is
901 # faithfully represented by the triple consisting of its sign,
902 # its adjusted exponent, and its coefficient with trailing
903 # zeros removed.
904 return hash((self._sign,
905 self._exp+len(self._int),
906 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000907
908 def as_tuple(self):
909 """Represents the number as a triple tuple.
910
911 To show the internals exactly as they are.
912 """
Christian Heimes25bb7832008-01-11 16:17:00 +0000913 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000914
915 def __repr__(self):
916 """Represents the number as an instance of Decimal."""
917 # Invariant: eval(repr(d)) == d
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000918 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000919
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000920 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000921 """Return string representation of the number in scientific notation.
922
923 Captures all of the information in the underlying representation.
924 """
925
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000926 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000927 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000928 if self._exp == 'F':
929 return sign + 'Infinity'
930 elif self._exp == 'n':
931 return sign + 'NaN' + self._int
932 else: # self._exp == 'N'
933 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000934
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000935 # number of digits of self._int to left of decimal point
936 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000937
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000938 # dotplace is number of digits of self._int to the left of the
939 # decimal point in the mantissa of the output string (that is,
940 # after adjusting the exponent)
941 if self._exp <= 0 and leftdigits > -6:
942 # no exponent required
943 dotplace = leftdigits
944 elif not eng:
945 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000946 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000947 elif self._int == '0':
948 # engineering notation, zero
949 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000950 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000951 # engineering notation, nonzero
952 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000953
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000954 if dotplace <= 0:
955 intpart = '0'
956 fracpart = '.' + '0'*(-dotplace) + self._int
957 elif dotplace >= len(self._int):
958 intpart = self._int+'0'*(dotplace-len(self._int))
959 fracpart = ''
960 else:
961 intpart = self._int[:dotplace]
962 fracpart = '.' + self._int[dotplace:]
963 if leftdigits == dotplace:
964 exp = ''
965 else:
966 if context is None:
967 context = getcontext()
968 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
969
970 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971
972 def to_eng_string(self, context=None):
973 """Convert to engineering-type string.
974
975 Engineering notation has an exponent which is a multiple of 3, so there
976 are up to 3 digits left of the decimal place.
977
978 Same rules for when in exponential and when as a value as in __str__.
979 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000980 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000981
982 def __neg__(self, context=None):
983 """Returns a copy with the sign switched.
984
985 Rounds, if it has reason.
986 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000987 if self._is_special:
988 ans = self._check_nans(context=context)
989 if ans:
990 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000991
992 if not self:
993 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000994 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000995 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000996 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000997
998 if context is None:
999 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001000 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001001
1002 def __pos__(self, context=None):
1003 """Returns a copy, unless it is a sNaN.
1004
1005 Rounds the number (if more then precision digits)
1006 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001007 if self._is_special:
1008 ans = self._check_nans(context=context)
1009 if ans:
1010 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001011
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001012 if not self:
1013 # + (-0) = 0
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001014 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001015 else:
1016 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001017
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001018 if context is None:
1019 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001020 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001021
Christian Heimes2c181612007-12-17 20:04:13 +00001022 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001023 """Returns the absolute value of self.
1024
Christian Heimes2c181612007-12-17 20:04:13 +00001025 If the keyword argument 'round' is false, do not round. The
1026 expression self.__abs__(round=False) is equivalent to
1027 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001028 """
Christian Heimes2c181612007-12-17 20:04:13 +00001029 if not round:
1030 return self.copy_abs()
1031
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001032 if self._is_special:
1033 ans = self._check_nans(context=context)
1034 if ans:
1035 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001036
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001037 if self._sign:
1038 ans = self.__neg__(context=context)
1039 else:
1040 ans = self.__pos__(context=context)
1041
1042 return ans
1043
1044 def __add__(self, other, context=None):
1045 """Returns self + other.
1046
1047 -INF + INF (or the reverse) cause InvalidOperation errors.
1048 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001049 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001050 if other is NotImplemented:
1051 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001052
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001053 if context is None:
1054 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001056 if self._is_special or other._is_special:
1057 ans = self._check_nans(other, context)
1058 if ans:
1059 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001060
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001061 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001062 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001063 if self._sign != other._sign and other._isinfinity():
1064 return context._raise_error(InvalidOperation, '-INF + INF')
1065 return Decimal(self)
1066 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001067 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001068
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001069 exp = min(self._exp, other._exp)
1070 negativezero = 0
1071 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001072 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001073 negativezero = 1
1074
1075 if not self and not other:
1076 sign = min(self._sign, other._sign)
1077 if negativezero:
1078 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001079 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001080 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001081 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001082 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001083 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001084 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001085 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001086 return ans
1087 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001088 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001089 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001090 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001091 return ans
1092
1093 op1 = _WorkRep(self)
1094 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001095 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001096
1097 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001098 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001099 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001100 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001101 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001102 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001103 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001104 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001105 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001106 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001107 if op1.sign == 1:
1108 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001109 op1.sign, op2.sign = op2.sign, op1.sign
1110 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001111 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001112 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001113 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001114 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001115 op1.sign, op2.sign = (0, 0)
1116 else:
1117 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001118 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001119
Raymond Hettinger17931de2004-10-27 06:21:46 +00001120 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001121 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001122 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001123 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001124
1125 result.exp = op1.exp
1126 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001127 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001128 return ans
1129
1130 __radd__ = __add__
1131
1132 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001133 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001134 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001135 if other is NotImplemented:
1136 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001137
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001138 if self._is_special or other._is_special:
1139 ans = self._check_nans(other, context=context)
1140 if ans:
1141 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001142
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001143 # self - other is computed as self + other.copy_negate()
1144 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001145
1146 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001147 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001148 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001149 if other is NotImplemented:
1150 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001151
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001152 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001153
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001154 def __mul__(self, other, context=None):
1155 """Return self * other.
1156
1157 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1158 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001159 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001160 if other is NotImplemented:
1161 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001162
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001163 if context is None:
1164 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001165
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001166 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001167
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001168 if self._is_special or other._is_special:
1169 ans = self._check_nans(other, context)
1170 if ans:
1171 return ans
1172
1173 if self._isinfinity():
1174 if not other:
1175 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1176 return Infsign[resultsign]
1177
1178 if other._isinfinity():
1179 if not self:
1180 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1181 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001182
1183 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001184
1185 # Special case for multiplying by zero
1186 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001187 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001188 # Fixing in case the exponent is out of bounds
1189 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001190 return ans
1191
1192 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001193 if self._int == '1':
1194 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001195 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001196 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001197 if other._int == '1':
1198 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001199 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001200 return ans
1201
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001202 op1 = _WorkRep(self)
1203 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001204
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001205 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001206 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001207
1208 return ans
1209 __rmul__ = __mul__
1210
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001211 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001212 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001213 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001214 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001215 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001216
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001217 if context is None:
1218 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001219
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001220 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001221
1222 if self._is_special or other._is_special:
1223 ans = self._check_nans(other, context)
1224 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001225 return ans
1226
1227 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001228 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001229
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001230 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001231 return Infsign[sign]
1232
1233 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001234 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001235 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001236
1237 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001238 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001239 if not self:
1240 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001241 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001242
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001243 if not self:
1244 exp = self._exp - other._exp
1245 coeff = 0
1246 else:
1247 # OK, so neither = 0, INF or NaN
1248 shift = len(other._int) - len(self._int) + context.prec + 1
1249 exp = self._exp - other._exp - shift
1250 op1 = _WorkRep(self)
1251 op2 = _WorkRep(other)
1252 if shift >= 0:
1253 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1254 else:
1255 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1256 if remainder:
1257 # result is not exact; adjust to ensure correct rounding
1258 if coeff % 5 == 0:
1259 coeff += 1
1260 else:
1261 # result is exact; get as close to ideal exponent as possible
1262 ideal_exp = self._exp - other._exp
1263 while exp < ideal_exp and coeff % 10 == 0:
1264 coeff //= 10
1265 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001266
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001267 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001268 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001269
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001270 def _divide(self, other, context):
1271 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001272
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001273 Assumes that neither self nor other is a NaN, that self is not
1274 infinite and that other is nonzero.
1275 """
1276 sign = self._sign ^ other._sign
1277 if other._isinfinity():
1278 ideal_exp = self._exp
1279 else:
1280 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001281
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001282 expdiff = self.adjusted() - other.adjusted()
1283 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001284 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001285 self._rescale(ideal_exp, context.rounding))
1286 if expdiff <= context.prec:
1287 op1 = _WorkRep(self)
1288 op2 = _WorkRep(other)
1289 if op1.exp >= op2.exp:
1290 op1.int *= 10**(op1.exp - op2.exp)
1291 else:
1292 op2.int *= 10**(op2.exp - op1.exp)
1293 q, r = divmod(op1.int, op2.int)
1294 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001295 return (_dec_from_triple(sign, str(q), 0),
1296 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001297
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001298 # Here the quotient is too large to be representable
1299 ans = context._raise_error(DivisionImpossible,
1300 'quotient too large in //, % or divmod')
1301 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001302
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001303 def __rtruediv__(self, other, context=None):
1304 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001305 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001306 if other is NotImplemented:
1307 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001308 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001309
1310 def __divmod__(self, other, context=None):
1311 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001312 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001313 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001314 other = _convert_other(other)
1315 if other is NotImplemented:
1316 return other
1317
1318 if context is None:
1319 context = getcontext()
1320
1321 ans = self._check_nans(other, context)
1322 if ans:
1323 return (ans, ans)
1324
1325 sign = self._sign ^ other._sign
1326 if self._isinfinity():
1327 if other._isinfinity():
1328 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1329 return ans, ans
1330 else:
1331 return (Infsign[sign],
1332 context._raise_error(InvalidOperation, 'INF % x'))
1333
1334 if not other:
1335 if not self:
1336 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1337 return ans, ans
1338 else:
1339 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1340 context._raise_error(InvalidOperation, 'x % 0'))
1341
1342 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001343 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001344 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001345
1346 def __rdivmod__(self, other, context=None):
1347 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001348 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001349 if other is NotImplemented:
1350 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001351 return other.__divmod__(self, context=context)
1352
1353 def __mod__(self, other, context=None):
1354 """
1355 self % other
1356 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001357 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001358 if other is NotImplemented:
1359 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001360
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001361 if context is None:
1362 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001363
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001364 ans = self._check_nans(other, context)
1365 if ans:
1366 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001367
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001368 if self._isinfinity():
1369 return context._raise_error(InvalidOperation, 'INF % x')
1370 elif not other:
1371 if self:
1372 return context._raise_error(InvalidOperation, 'x % 0')
1373 else:
1374 return context._raise_error(DivisionUndefined, '0 % 0')
1375
1376 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001377 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001378 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001379
1380 def __rmod__(self, other, context=None):
1381 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001382 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001383 if other is NotImplemented:
1384 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001385 return other.__mod__(self, context=context)
1386
1387 def remainder_near(self, other, context=None):
1388 """
1389 Remainder nearest to 0- abs(remainder-near) <= other/2
1390 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001391 if context is None:
1392 context = getcontext()
1393
1394 other = _convert_other(other, raiseit=True)
1395
1396 ans = self._check_nans(other, context)
1397 if ans:
1398 return ans
1399
1400 # self == +/-infinity -> InvalidOperation
1401 if self._isinfinity():
1402 return context._raise_error(InvalidOperation,
1403 'remainder_near(infinity, x)')
1404
1405 # other == 0 -> either InvalidOperation or DivisionUndefined
1406 if not other:
1407 if self:
1408 return context._raise_error(InvalidOperation,
1409 'remainder_near(x, 0)')
1410 else:
1411 return context._raise_error(DivisionUndefined,
1412 'remainder_near(0, 0)')
1413
1414 # other = +/-infinity -> remainder = self
1415 if other._isinfinity():
1416 ans = Decimal(self)
1417 return ans._fix(context)
1418
1419 # self = 0 -> remainder = self, with ideal exponent
1420 ideal_exponent = min(self._exp, other._exp)
1421 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001422 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001423 return ans._fix(context)
1424
1425 # catch most cases of large or small quotient
1426 expdiff = self.adjusted() - other.adjusted()
1427 if expdiff >= context.prec + 1:
1428 # expdiff >= prec+1 => abs(self/other) > 10**prec
1429 return context._raise_error(DivisionImpossible)
1430 if expdiff <= -2:
1431 # expdiff <= -2 => abs(self/other) < 0.1
1432 ans = self._rescale(ideal_exponent, context.rounding)
1433 return ans._fix(context)
1434
1435 # adjust both arguments to have the same exponent, then divide
1436 op1 = _WorkRep(self)
1437 op2 = _WorkRep(other)
1438 if op1.exp >= op2.exp:
1439 op1.int *= 10**(op1.exp - op2.exp)
1440 else:
1441 op2.int *= 10**(op2.exp - op1.exp)
1442 q, r = divmod(op1.int, op2.int)
1443 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1444 # 10**ideal_exponent. Apply correction to ensure that
1445 # abs(remainder) <= abs(other)/2
1446 if 2*r + (q&1) > op2.int:
1447 r -= op2.int
1448 q += 1
1449
1450 if q >= 10**context.prec:
1451 return context._raise_error(DivisionImpossible)
1452
1453 # result has same sign as self unless r is negative
1454 sign = self._sign
1455 if r < 0:
1456 sign = 1-sign
1457 r = -r
1458
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001459 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001460 return ans._fix(context)
1461
1462 def __floordiv__(self, other, context=None):
1463 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001464 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001465 if other is NotImplemented:
1466 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001467
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001468 if context is None:
1469 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001470
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001471 ans = self._check_nans(other, context)
1472 if ans:
1473 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001474
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001475 if self._isinfinity():
1476 if other._isinfinity():
1477 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001478 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001479 return Infsign[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001480
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001481 if not other:
1482 if self:
1483 return context._raise_error(DivisionByZero, 'x // 0',
1484 self._sign ^ other._sign)
1485 else:
1486 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001487
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001488 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001489
1490 def __rfloordiv__(self, other, context=None):
1491 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001492 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001493 if other is NotImplemented:
1494 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001495 return other.__floordiv__(self, context=context)
1496
1497 def __float__(self):
1498 """Float representation."""
1499 return float(str(self))
1500
1501 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001502 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001503 if self._is_special:
1504 if self._isnan():
1505 context = getcontext()
1506 return context._raise_error(InvalidContext)
1507 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001508 raise OverflowError("Cannot convert infinity to int")
1509 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001510 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001511 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001512 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001513 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001514
Christian Heimes969fe572008-01-25 11:23:10 +00001515 __trunc__ = __int__
1516
Christian Heimes0bd4e112008-02-12 22:59:25 +00001517 @property
1518 def real(self):
1519 return self
1520
1521 @property
1522 def imag(self):
1523 return Decimal(0)
1524
1525 def conjugate(self):
1526 return self
1527
1528 def __complex__(self):
1529 return complex(float(self))
1530
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001531 def _fix_nan(self, context):
1532 """Decapitate the payload of a NaN to fit the context"""
1533 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001534
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001535 # maximum length of payload is precision if _clamp=0,
1536 # precision-1 if _clamp=1.
1537 max_payload_len = context.prec - context._clamp
1538 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001539 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1540 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001541 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001542
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001543 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001544 """Round if it is necessary to keep self within prec precision.
1545
1546 Rounds and fixes the exponent. Does not raise on a sNaN.
1547
1548 Arguments:
1549 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001550 context - context used.
1551 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001552
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001553 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001554 if self._isnan():
1555 # decapitate payload if necessary
1556 return self._fix_nan(context)
1557 else:
1558 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001559 return Decimal(self)
1560
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001561 # if self is zero then exponent should be between Etiny and
1562 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1563 Etiny = context.Etiny()
1564 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001565 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001566 exp_max = [context.Emax, Etop][context._clamp]
1567 new_exp = min(max(self._exp, Etiny), exp_max)
1568 if new_exp != self._exp:
1569 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001570 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001571 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001572 return Decimal(self)
1573
1574 # exp_min is the smallest allowable exponent of the result,
1575 # equal to max(self.adjusted()-context.prec+1, Etiny)
1576 exp_min = len(self._int) + self._exp - context.prec
1577 if exp_min > Etop:
1578 # overflow: exp_min > Etop iff self.adjusted() > Emax
1579 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001580 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001581 return context._raise_error(Overflow, 'above Emax', self._sign)
1582 self_is_subnormal = exp_min < Etiny
1583 if self_is_subnormal:
1584 context._raise_error(Subnormal)
1585 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001586
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001587 # round if self has too many digits
1588 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001589 context._raise_error(Rounded)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001590 digits = len(self._int) + self._exp - exp_min
1591 if digits < 0:
1592 self = _dec_from_triple(self._sign, '1', exp_min-1)
1593 digits = 0
1594 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1595 changed = this_function(digits)
1596 coeff = self._int[:digits] or '0'
1597 if changed == 1:
1598 coeff = str(int(coeff)+1)
1599 ans = _dec_from_triple(self._sign, coeff, exp_min)
1600
1601 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001602 context._raise_error(Inexact)
1603 if self_is_subnormal:
1604 context._raise_error(Underflow)
1605 if not ans:
1606 # raise Clamped on underflow to 0
1607 context._raise_error(Clamped)
1608 elif len(ans._int) == context.prec+1:
1609 # we get here only if rescaling rounds the
1610 # cofficient up to exactly 10**context.prec
1611 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001612 ans = _dec_from_triple(ans._sign,
1613 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001614 else:
1615 # Inexact and Rounded have already been raised
1616 ans = context._raise_error(Overflow, 'above Emax',
1617 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001618 return ans
1619
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001620 # fold down if _clamp == 1 and self has too few digits
1621 if context._clamp == 1 and self._exp > Etop:
1622 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001623 self_padded = self._int + '0'*(self._exp - Etop)
1624 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001625
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001626 # here self was representable to begin with; return unchanged
1627 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001628
1629 _pick_rounding_function = {}
1630
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001631 # for each of the rounding functions below:
1632 # self is a finite, nonzero Decimal
1633 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001634 #
1635 # each function returns either -1, 0, or 1, as follows:
1636 # 1 indicates that self should be rounded up (away from zero)
1637 # 0 indicates that self should be truncated, and that all the
1638 # digits to be truncated are zeros (so the value is unchanged)
1639 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001640
1641 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001642 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001643 if _all_zeros(self._int, prec):
1644 return 0
1645 else:
1646 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001647
Mark Dickinson349a7852008-05-04 00:00:19 +00001648 def __round__(self):
1649 return self._round_down(0)
1650
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001651 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001652 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001653 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001654
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001655 def _round_half_up(self, prec):
1656 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001657 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001658 return 1
1659 elif _all_zeros(self._int, prec):
1660 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001661 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001662 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001663
1664 def _round_half_down(self, prec):
1665 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001666 if _exact_half(self._int, prec):
1667 return -1
1668 else:
1669 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001670
1671 def _round_half_even(self, prec):
1672 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001673 if _exact_half(self._int, prec) and \
1674 (prec == 0 or self._int[prec-1] in '02468'):
1675 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001676 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001677 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001678
1679 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001680 """Rounds up (not away from 0 if negative.)"""
1681 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001682 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001683 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001684 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001685
Mark Dickinson349a7852008-05-04 00:00:19 +00001686 def __ceil__(self):
1687 return self._round_ceiling(0)
1688
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001689 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001690 """Rounds down (not towards 0 if negative)"""
1691 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001692 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001693 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001694 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001695
Mark Dickinson349a7852008-05-04 00:00:19 +00001696 def __floor__(self):
1697 return self._round_floor(0)
1698
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001699 def _round_05up(self, prec):
1700 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001701 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001702 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001703 else:
1704 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001705
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001706 def fma(self, other, third, context=None):
1707 """Fused multiply-add.
1708
1709 Returns self*other+third with no rounding of the intermediate
1710 product self*other.
1711
1712 self and other are multiplied together, with no rounding of
1713 the result. The third operand is then added to the result,
1714 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001715 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001716
1717 other = _convert_other(other, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001718
1719 # compute product; raise InvalidOperation if either operand is
1720 # a signaling NaN or if the product is zero times infinity.
1721 if self._is_special or other._is_special:
1722 if context is None:
1723 context = getcontext()
1724 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001725 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001726 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001727 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001728 if self._exp == 'n':
1729 product = self
1730 elif other._exp == 'n':
1731 product = other
1732 elif self._exp == 'F':
1733 if not other:
1734 return context._raise_error(InvalidOperation,
1735 'INF * 0 in fma')
1736 product = Infsign[self._sign ^ other._sign]
1737 elif other._exp == 'F':
1738 if not self:
1739 return context._raise_error(InvalidOperation,
1740 '0 * INF in fma')
1741 product = Infsign[self._sign ^ other._sign]
1742 else:
1743 product = _dec_from_triple(self._sign ^ other._sign,
1744 str(int(self._int) * int(other._int)),
1745 self._exp + other._exp)
1746
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001747 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001748 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001749
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001750 def _power_modulo(self, other, modulo, context=None):
1751 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001752
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001753 # if can't convert other and modulo to Decimal, raise
1754 # TypeError; there's no point returning NotImplemented (no
1755 # equivalent of __rpow__ for three argument pow)
1756 other = _convert_other(other, raiseit=True)
1757 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001758
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001759 if context is None:
1760 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001761
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001762 # deal with NaNs: if there are any sNaNs then first one wins,
1763 # (i.e. behaviour for NaNs is identical to that of fma)
1764 self_is_nan = self._isnan()
1765 other_is_nan = other._isnan()
1766 modulo_is_nan = modulo._isnan()
1767 if self_is_nan or other_is_nan or modulo_is_nan:
1768 if self_is_nan == 2:
1769 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001770 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001771 if other_is_nan == 2:
1772 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001773 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001774 if modulo_is_nan == 2:
1775 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001776 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001777 if self_is_nan:
1778 return self._fix_nan(context)
1779 if other_is_nan:
1780 return other._fix_nan(context)
1781 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001782
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001783 # check inputs: we apply same restrictions as Python's pow()
1784 if not (self._isinteger() and
1785 other._isinteger() and
1786 modulo._isinteger()):
1787 return context._raise_error(InvalidOperation,
1788 'pow() 3rd argument not allowed '
1789 'unless all arguments are integers')
1790 if other < 0:
1791 return context._raise_error(InvalidOperation,
1792 'pow() 2nd argument cannot be '
1793 'negative when 3rd argument specified')
1794 if not modulo:
1795 return context._raise_error(InvalidOperation,
1796 'pow() 3rd argument cannot be 0')
1797
1798 # additional restriction for decimal: the modulus must be less
1799 # than 10**prec in absolute value
1800 if modulo.adjusted() >= context.prec:
1801 return context._raise_error(InvalidOperation,
1802 'insufficient precision: pow() 3rd '
1803 'argument must not have more than '
1804 'precision digits')
1805
1806 # define 0**0 == NaN, for consistency with two-argument pow
1807 # (even though it hurts!)
1808 if not other and not self:
1809 return context._raise_error(InvalidOperation,
1810 'at least one of pow() 1st argument '
1811 'and 2nd argument must be nonzero ;'
1812 '0**0 is not defined')
1813
1814 # compute sign of result
1815 if other._iseven():
1816 sign = 0
1817 else:
1818 sign = self._sign
1819
1820 # convert modulo to a Python integer, and self and other to
1821 # Decimal integers (i.e. force their exponents to be >= 0)
1822 modulo = abs(int(modulo))
1823 base = _WorkRep(self.to_integral_value())
1824 exponent = _WorkRep(other.to_integral_value())
1825
1826 # compute result using integer pow()
1827 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1828 for i in range(exponent.exp):
1829 base = pow(base, 10, modulo)
1830 base = pow(base, exponent.int, modulo)
1831
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001832 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001833
1834 def _power_exact(self, other, p):
1835 """Attempt to compute self**other exactly.
1836
1837 Given Decimals self and other and an integer p, attempt to
1838 compute an exact result for the power self**other, with p
1839 digits of precision. Return None if self**other is not
1840 exactly representable in p digits.
1841
1842 Assumes that elimination of special cases has already been
1843 performed: self and other must both be nonspecial; self must
1844 be positive and not numerically equal to 1; other must be
1845 nonzero. For efficiency, other._exp should not be too large,
1846 so that 10**abs(other._exp) is a feasible calculation."""
1847
1848 # In the comments below, we write x for the value of self and
1849 # y for the value of other. Write x = xc*10**xe and y =
1850 # yc*10**ye.
1851
1852 # The main purpose of this method is to identify the *failure*
1853 # of x**y to be exactly representable with as little effort as
1854 # possible. So we look for cheap and easy tests that
1855 # eliminate the possibility of x**y being exact. Only if all
1856 # these tests are passed do we go on to actually compute x**y.
1857
1858 # Here's the main idea. First normalize both x and y. We
1859 # express y as a rational m/n, with m and n relatively prime
1860 # and n>0. Then for x**y to be exactly representable (at
1861 # *any* precision), xc must be the nth power of a positive
1862 # integer and xe must be divisible by n. If m is negative
1863 # then additionally xc must be a power of either 2 or 5, hence
1864 # a power of 2**n or 5**n.
1865 #
1866 # There's a limit to how small |y| can be: if y=m/n as above
1867 # then:
1868 #
1869 # (1) if xc != 1 then for the result to be representable we
1870 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1871 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1872 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1873 # representable.
1874 #
1875 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1876 # |y| < 1/|xe| then the result is not representable.
1877 #
1878 # Note that since x is not equal to 1, at least one of (1) and
1879 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1880 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1881 #
1882 # There's also a limit to how large y can be, at least if it's
1883 # positive: the normalized result will have coefficient xc**y,
1884 # so if it's representable then xc**y < 10**p, and y <
1885 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1886 # not exactly representable.
1887
1888 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1889 # so |y| < 1/xe and the result is not representable.
1890 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1891 # < 1/nbits(xc).
1892
1893 x = _WorkRep(self)
1894 xc, xe = x.int, x.exp
1895 while xc % 10 == 0:
1896 xc //= 10
1897 xe += 1
1898
1899 y = _WorkRep(other)
1900 yc, ye = y.int, y.exp
1901 while yc % 10 == 0:
1902 yc //= 10
1903 ye += 1
1904
1905 # case where xc == 1: result is 10**(xe*y), with xe*y
1906 # required to be an integer
1907 if xc == 1:
1908 if ye >= 0:
1909 exponent = xe*yc*10**ye
1910 else:
1911 exponent, remainder = divmod(xe*yc, 10**-ye)
1912 if remainder:
1913 return None
1914 if y.sign == 1:
1915 exponent = -exponent
1916 # if other is a nonnegative integer, use ideal exponent
1917 if other._isinteger() and other._sign == 0:
1918 ideal_exponent = self._exp*int(other)
1919 zeros = min(exponent-ideal_exponent, p-1)
1920 else:
1921 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001922 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001923
1924 # case where y is negative: xc must be either a power
1925 # of 2 or a power of 5.
1926 if y.sign == 1:
1927 last_digit = xc % 10
1928 if last_digit in (2,4,6,8):
1929 # quick test for power of 2
1930 if xc & -xc != xc:
1931 return None
1932 # now xc is a power of 2; e is its exponent
1933 e = _nbits(xc)-1
1934 # find e*y and xe*y; both must be integers
1935 if ye >= 0:
1936 y_as_int = yc*10**ye
1937 e = e*y_as_int
1938 xe = xe*y_as_int
1939 else:
1940 ten_pow = 10**-ye
1941 e, remainder = divmod(e*yc, ten_pow)
1942 if remainder:
1943 return None
1944 xe, remainder = divmod(xe*yc, ten_pow)
1945 if remainder:
1946 return None
1947
1948 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1949 return None
1950 xc = 5**e
1951
1952 elif last_digit == 5:
1953 # e >= log_5(xc) if xc is a power of 5; we have
1954 # equality all the way up to xc=5**2658
1955 e = _nbits(xc)*28//65
1956 xc, remainder = divmod(5**e, xc)
1957 if remainder:
1958 return None
1959 while xc % 5 == 0:
1960 xc //= 5
1961 e -= 1
1962 if ye >= 0:
1963 y_as_integer = yc*10**ye
1964 e = e*y_as_integer
1965 xe = xe*y_as_integer
1966 else:
1967 ten_pow = 10**-ye
1968 e, remainder = divmod(e*yc, ten_pow)
1969 if remainder:
1970 return None
1971 xe, remainder = divmod(xe*yc, ten_pow)
1972 if remainder:
1973 return None
1974 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1975 return None
1976 xc = 2**e
1977 else:
1978 return None
1979
1980 if xc >= 10**p:
1981 return None
1982 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001983 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001984
1985 # now y is positive; find m and n such that y = m/n
1986 if ye >= 0:
1987 m, n = yc*10**ye, 1
1988 else:
1989 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1990 return None
1991 xc_bits = _nbits(xc)
1992 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1993 return None
1994 m, n = yc, 10**(-ye)
1995 while m % 2 == n % 2 == 0:
1996 m //= 2
1997 n //= 2
1998 while m % 5 == n % 5 == 0:
1999 m //= 5
2000 n //= 5
2001
2002 # compute nth root of xc*10**xe
2003 if n > 1:
2004 # if 1 < xc < 2**n then xc isn't an nth power
2005 if xc != 1 and xc_bits <= n:
2006 return None
2007
2008 xe, rem = divmod(xe, n)
2009 if rem != 0:
2010 return None
2011
2012 # compute nth root of xc using Newton's method
2013 a = 1 << -(-_nbits(xc)//n) # initial estimate
2014 while True:
2015 q, r = divmod(xc, a**(n-1))
2016 if a <= q:
2017 break
2018 else:
2019 a = (a*(n-1) + q)//n
2020 if not (a == q and r == 0):
2021 return None
2022 xc = a
2023
2024 # now xc*10**xe is the nth root of the original xc*10**xe
2025 # compute mth power of xc*10**xe
2026
2027 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2028 # 10**p and the result is not representable.
2029 if xc > 1 and m > p*100//_log10_lb(xc):
2030 return None
2031 xc = xc**m
2032 xe *= m
2033 if xc > 10**p:
2034 return None
2035
2036 # by this point the result *is* exactly representable
2037 # adjust the exponent to get as close as possible to the ideal
2038 # exponent, if necessary
2039 str_xc = str(xc)
2040 if other._isinteger() and other._sign == 0:
2041 ideal_exponent = self._exp*int(other)
2042 zeros = min(xe-ideal_exponent, p-len(str_xc))
2043 else:
2044 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002045 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002046
2047 def __pow__(self, other, modulo=None, context=None):
2048 """Return self ** other [ % modulo].
2049
2050 With two arguments, compute self**other.
2051
2052 With three arguments, compute (self**other) % modulo. For the
2053 three argument form, the following restrictions on the
2054 arguments hold:
2055
2056 - all three arguments must be integral
2057 - other must be nonnegative
2058 - either self or other (or both) must be nonzero
2059 - modulo must be nonzero and must have at most p digits,
2060 where p is the context precision.
2061
2062 If any of these restrictions is violated the InvalidOperation
2063 flag is raised.
2064
2065 The result of pow(self, other, modulo) is identical to the
2066 result that would be obtained by computing (self**other) %
2067 modulo with unbounded precision, but is computed more
2068 efficiently. It is always exact.
2069 """
2070
2071 if modulo is not None:
2072 return self._power_modulo(other, modulo, context)
2073
2074 other = _convert_other(other)
2075 if other is NotImplemented:
2076 return other
2077
2078 if context is None:
2079 context = getcontext()
2080
2081 # either argument is a NaN => result is NaN
2082 ans = self._check_nans(other, context)
2083 if ans:
2084 return ans
2085
2086 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2087 if not other:
2088 if not self:
2089 return context._raise_error(InvalidOperation, '0 ** 0')
2090 else:
2091 return Dec_p1
2092
2093 # result has sign 1 iff self._sign is 1 and other is an odd integer
2094 result_sign = 0
2095 if self._sign == 1:
2096 if other._isinteger():
2097 if not other._iseven():
2098 result_sign = 1
2099 else:
2100 # -ve**noninteger = NaN
2101 # (-0)**noninteger = 0**noninteger
2102 if self:
2103 return context._raise_error(InvalidOperation,
2104 'x ** y with x negative and y not an integer')
2105 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002106 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002107
2108 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2109 if not self:
2110 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002111 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002112 else:
2113 return Infsign[result_sign]
2114
2115 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002116 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002117 if other._sign == 0:
2118 return Infsign[result_sign]
2119 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002120 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002121
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002122 # 1**other = 1, but the choice of exponent and the flags
2123 # depend on the exponent of self, and on whether other is a
2124 # positive integer, a negative integer, or neither
2125 if self == Dec_p1:
2126 if other._isinteger():
2127 # exp = max(self._exp*max(int(other), 0),
2128 # 1-context.prec) but evaluating int(other) directly
2129 # is dangerous until we know other is small (other
2130 # could be 1e999999999)
2131 if other._sign == 1:
2132 multiplier = 0
2133 elif other > context.prec:
2134 multiplier = context.prec
2135 else:
2136 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002137
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002138 exp = self._exp * multiplier
2139 if exp < 1-context.prec:
2140 exp = 1-context.prec
2141 context._raise_error(Rounded)
2142 else:
2143 context._raise_error(Inexact)
2144 context._raise_error(Rounded)
2145 exp = 1-context.prec
2146
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002147 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002148
2149 # compute adjusted exponent of self
2150 self_adj = self.adjusted()
2151
2152 # self ** infinity is infinity if self > 1, 0 if self < 1
2153 # self ** -infinity is infinity if self < 1, 0 if self > 1
2154 if other._isinfinity():
2155 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002156 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002157 else:
2158 return Infsign[result_sign]
2159
2160 # from here on, the result always goes through the call
2161 # to _fix at the end of this function.
2162 ans = None
2163
2164 # crude test to catch cases of extreme overflow/underflow. If
2165 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2166 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2167 # self**other >= 10**(Emax+1), so overflow occurs. The test
2168 # for underflow is similar.
2169 bound = self._log10_exp_bound() + other.adjusted()
2170 if (self_adj >= 0) == (other._sign == 0):
2171 # self > 1 and other +ve, or self < 1 and other -ve
2172 # possibility of overflow
2173 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002174 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002175 else:
2176 # self > 1 and other -ve, or self < 1 and other +ve
2177 # possibility of underflow to 0
2178 Etiny = context.Etiny()
2179 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002180 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002181
2182 # try for an exact result with precision +1
2183 if ans is None:
2184 ans = self._power_exact(other, context.prec + 1)
2185 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002186 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002187
2188 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2189 if ans is None:
2190 p = context.prec
2191 x = _WorkRep(self)
2192 xc, xe = x.int, x.exp
2193 y = _WorkRep(other)
2194 yc, ye = y.int, y.exp
2195 if y.sign == 1:
2196 yc = -yc
2197
2198 # compute correctly rounded result: start with precision +3,
2199 # then increase precision until result is unambiguously roundable
2200 extra = 3
2201 while True:
2202 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2203 if coeff % (5*10**(len(str(coeff))-p-1)):
2204 break
2205 extra += 3
2206
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002207 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002208
2209 # the specification says that for non-integer other we need to
2210 # raise Inexact, even when the result is actually exact. In
2211 # the same way, we need to raise Underflow here if the result
2212 # is subnormal. (The call to _fix will take care of raising
2213 # Rounded and Subnormal, as usual.)
2214 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002215 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002216 # pad with zeros up to length context.prec+1 if necessary
2217 if len(ans._int) <= context.prec:
2218 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002219 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2220 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002221 if ans.adjusted() < context.Emin:
2222 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002223
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002224 # unlike exp, ln and log10, the power function respects the
2225 # rounding mode; no need to use ROUND_HALF_EVEN here
2226 ans = ans._fix(context)
2227 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002228
2229 def __rpow__(self, other, context=None):
2230 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002231 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002232 if other is NotImplemented:
2233 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002234 return other.__pow__(self, context=context)
2235
2236 def normalize(self, context=None):
2237 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002238
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002239 if context is None:
2240 context = getcontext()
2241
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002242 if self._is_special:
2243 ans = self._check_nans(context=context)
2244 if ans:
2245 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002246
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002247 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002248 if dup._isinfinity():
2249 return dup
2250
2251 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002252 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002253 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002254 end = len(dup._int)
2255 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002256 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002257 exp += 1
2258 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002259 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002260
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002261 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002262 """Quantize self so its exponent is the same as that of exp.
2263
2264 Similar to self._rescale(exp._exp) but with error checking.
2265 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002266 exp = _convert_other(exp, raiseit=True)
2267
2268 if context is None:
2269 context = getcontext()
2270 if rounding is None:
2271 rounding = context.rounding
2272
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002273 if self._is_special or exp._is_special:
2274 ans = self._check_nans(exp, context)
2275 if ans:
2276 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002277
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002278 if exp._isinfinity() or self._isinfinity():
2279 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002280 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002281 return context._raise_error(InvalidOperation,
2282 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002283
2284 # if we're not watching exponents, do a simple rescale
2285 if not watchexp:
2286 ans = self._rescale(exp._exp, rounding)
2287 # raise Inexact and Rounded where appropriate
2288 if ans._exp > self._exp:
2289 context._raise_error(Rounded)
2290 if ans != self:
2291 context._raise_error(Inexact)
2292 return ans
2293
2294 # exp._exp should be between Etiny and Emax
2295 if not (context.Etiny() <= exp._exp <= context.Emax):
2296 return context._raise_error(InvalidOperation,
2297 'target exponent out of bounds in quantize')
2298
2299 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002300 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002301 return ans._fix(context)
2302
2303 self_adjusted = self.adjusted()
2304 if self_adjusted > context.Emax:
2305 return context._raise_error(InvalidOperation,
2306 'exponent of quantize result too large for current context')
2307 if self_adjusted - exp._exp + 1 > context.prec:
2308 return context._raise_error(InvalidOperation,
2309 'quantize result has too many digits for current context')
2310
2311 ans = self._rescale(exp._exp, rounding)
2312 if ans.adjusted() > context.Emax:
2313 return context._raise_error(InvalidOperation,
2314 'exponent of quantize result too large for current context')
2315 if len(ans._int) > context.prec:
2316 return context._raise_error(InvalidOperation,
2317 'quantize result has too many digits for current context')
2318
2319 # raise appropriate flags
2320 if ans._exp > self._exp:
2321 context._raise_error(Rounded)
2322 if ans != self:
2323 context._raise_error(Inexact)
2324 if ans and ans.adjusted() < context.Emin:
2325 context._raise_error(Subnormal)
2326
2327 # call to fix takes care of any necessary folddown
2328 ans = ans._fix(context)
2329 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002330
2331 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002332 """Return True if self and other have the same exponent; otherwise
2333 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002334
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002335 If either operand is a special value, the following rules are used:
2336 * return True if both operands are infinities
2337 * return True if both operands are NaNs
2338 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002339 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002340 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002341 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002342 return (self.is_nan() and other.is_nan() or
2343 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002344 return self._exp == other._exp
2345
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002346 def _rescale(self, exp, rounding):
2347 """Rescale self so that the exponent is exp, either by padding with zeros
2348 or by truncating digits, using the given rounding mode.
2349
2350 Specials are returned without change. This operation is
2351 quiet: it raises no flags, and uses no information from the
2352 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002353
2354 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002355 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002356 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002357 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002358 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002359 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002360 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002361
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002362 if self._exp >= exp:
2363 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002364 return _dec_from_triple(self._sign,
2365 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002366
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002367 # too many digits; round and lose data. If self.adjusted() <
2368 # exp-1, replace self by 10**(exp-1) before rounding
2369 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002370 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002371 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002372 digits = 0
2373 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002374 changed = this_function(digits)
2375 coeff = self._int[:digits] or '0'
2376 if changed == 1:
2377 coeff = str(int(coeff)+1)
2378 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002379
Christian Heimesf16baeb2008-02-29 14:57:44 +00002380 def _round(self, places, rounding):
2381 """Round a nonzero, nonspecial Decimal to a fixed number of
2382 significant figures, using the given rounding mode.
2383
2384 Infinities, NaNs and zeros are returned unaltered.
2385
2386 This operation is quiet: it raises no flags, and uses no
2387 information from the context.
2388
2389 """
2390 if places <= 0:
2391 raise ValueError("argument should be at least 1 in _round")
2392 if self._is_special or not self:
2393 return Decimal(self)
2394 ans = self._rescale(self.adjusted()+1-places, rounding)
2395 # it can happen that the rescale alters the adjusted exponent;
2396 # for example when rounding 99.97 to 3 significant figures.
2397 # When this happens we end up with an extra 0 at the end of
2398 # the number; a second rescale fixes this.
2399 if ans.adjusted() != self.adjusted():
2400 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2401 return ans
2402
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002403 def to_integral_exact(self, rounding=None, context=None):
2404 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002405
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002406 If no rounding mode is specified, take the rounding mode from
2407 the context. This method raises the Rounded and Inexact flags
2408 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002409
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002410 See also: to_integral_value, which does exactly the same as
2411 this method except that it doesn't raise Inexact or Rounded.
2412 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002413 if self._is_special:
2414 ans = self._check_nans(context=context)
2415 if ans:
2416 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002417 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002418 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002419 return Decimal(self)
2420 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002421 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002422 if context is None:
2423 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002424 if rounding is None:
2425 rounding = context.rounding
2426 context._raise_error(Rounded)
2427 ans = self._rescale(0, rounding)
2428 if ans != self:
2429 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002430 return ans
2431
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002432 def to_integral_value(self, rounding=None, context=None):
2433 """Rounds to the nearest integer, without raising inexact, rounded."""
2434 if context is None:
2435 context = getcontext()
2436 if rounding is None:
2437 rounding = context.rounding
2438 if self._is_special:
2439 ans = self._check_nans(context=context)
2440 if ans:
2441 return ans
2442 return Decimal(self)
2443 if self._exp >= 0:
2444 return Decimal(self)
2445 else:
2446 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002447
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002448 # the method name changed, but we provide also the old one, for compatibility
2449 to_integral = to_integral_value
2450
2451 def sqrt(self, context=None):
2452 """Return the square root of self."""
Christian Heimes0348fb62008-03-26 12:55:56 +00002453 if context is None:
2454 context = getcontext()
2455
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002456 if self._is_special:
2457 ans = self._check_nans(context=context)
2458 if ans:
2459 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002460
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002461 if self._isinfinity() and self._sign == 0:
2462 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002463
2464 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002465 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002466 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002467 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002468
2469 if self._sign == 1:
2470 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2471
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002472 # At this point self represents a positive number. Let p be
2473 # the desired precision and express self in the form c*100**e
2474 # with c a positive real number and e an integer, c and e
2475 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2476 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2477 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2478 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2479 # the closest integer to sqrt(c) with the even integer chosen
2480 # in the case of a tie.
2481 #
2482 # To ensure correct rounding in all cases, we use the
2483 # following trick: we compute the square root to an extra
2484 # place (precision p+1 instead of precision p), rounding down.
2485 # Then, if the result is inexact and its last digit is 0 or 5,
2486 # we increase the last digit to 1 or 6 respectively; if it's
2487 # exact we leave the last digit alone. Now the final round to
2488 # p places (or fewer in the case of underflow) will round
2489 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002490
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002491 # use an extra digit of precision
2492 prec = context.prec+1
2493
2494 # write argument in the form c*100**e where e = self._exp//2
2495 # is the 'ideal' exponent, to be used if the square root is
2496 # exactly representable. l is the number of 'digits' of c in
2497 # base 100, so that 100**(l-1) <= c < 100**l.
2498 op = _WorkRep(self)
2499 e = op.exp >> 1
2500 if op.exp & 1:
2501 c = op.int * 10
2502 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002503 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002504 c = op.int
2505 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002506
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002507 # rescale so that c has exactly prec base 100 'digits'
2508 shift = prec-l
2509 if shift >= 0:
2510 c *= 100**shift
2511 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002512 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002513 c, remainder = divmod(c, 100**-shift)
2514 exact = not remainder
2515 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002516
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002517 # find n = floor(sqrt(c)) using Newton's method
2518 n = 10**prec
2519 while True:
2520 q = c//n
2521 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002522 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002523 else:
2524 n = n + q >> 1
2525 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002526
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002527 if exact:
2528 # result is exact; rescale to use ideal exponent e
2529 if shift >= 0:
2530 # assert n % 10**shift == 0
2531 n //= 10**shift
2532 else:
2533 n *= 10**-shift
2534 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002535 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002536 # result is not exact; fix last digit as described above
2537 if n % 5 == 0:
2538 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002539
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002540 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002541
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002542 # round, and fit to current context
2543 context = context._shallow_copy()
2544 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002545 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002546 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002547
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002548 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002549
2550 def max(self, other, context=None):
2551 """Returns the larger value.
2552
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002553 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002554 NaN (and signals if one is sNaN). Also rounds.
2555 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002556 other = _convert_other(other, raiseit=True)
2557
2558 if context is None:
2559 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002560
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002561 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002562 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002563 # number is always returned
2564 sn = self._isnan()
2565 on = other._isnan()
2566 if sn or on:
2567 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002568 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002569 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002570 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002571 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002572
Christian Heimes77c02eb2008-02-09 02:18:51 +00002573 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002574 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002575 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002576 # then an ordering is applied:
2577 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002578 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002579 # positive sign and min returns the operand with the negative sign
2580 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002581 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002582 # the result. This is exactly the ordering used in compare_total.
2583 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002584
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002585 if c == -1:
2586 ans = other
2587 else:
2588 ans = self
2589
Christian Heimes2c181612007-12-17 20:04:13 +00002590 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002591
2592 def min(self, other, context=None):
2593 """Returns the smaller value.
2594
Guido van Rossumd8faa362007-04-27 19:54:29 +00002595 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002596 NaN (and signals if one is sNaN). Also rounds.
2597 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002598 other = _convert_other(other, raiseit=True)
2599
2600 if context is None:
2601 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002602
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002603 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002604 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002605 # number is always returned
2606 sn = self._isnan()
2607 on = other._isnan()
2608 if sn or on:
2609 if on == 1 and sn != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002610 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002611 if sn == 1 and on != 2:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002612 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002613 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002614
Christian Heimes77c02eb2008-02-09 02:18:51 +00002615 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002616 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002617 c = self.compare_total(other)
2618
2619 if c == -1:
2620 ans = self
2621 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002622 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002623
Christian Heimes2c181612007-12-17 20:04:13 +00002624 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002625
2626 def _isinteger(self):
2627 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002628 if self._is_special:
2629 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002630 if self._exp >= 0:
2631 return True
2632 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002633 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002634
2635 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002636 """Returns True if self is even. Assumes self is an integer."""
2637 if not self or self._exp > 0:
2638 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002639 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002640
2641 def adjusted(self):
2642 """Return the adjusted exponent of self"""
2643 try:
2644 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002645 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002646 except TypeError:
2647 return 0
2648
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002649 def canonical(self, context=None):
2650 """Returns the same Decimal object.
2651
2652 As we do not have different encodings for the same number, the
2653 received object already is in its canonical form.
2654 """
2655 return self
2656
2657 def compare_signal(self, other, context=None):
2658 """Compares self to the other operand numerically.
2659
2660 It's pretty much like compare(), but all NaNs signal, with signaling
2661 NaNs taking precedence over quiet NaNs.
2662 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002663 other = _convert_other(other, raiseit = True)
2664 ans = self._compare_check_nans(other, context)
2665 if ans:
2666 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002667 return self.compare(other, context=context)
2668
2669 def compare_total(self, other):
2670 """Compares self to other using the abstract representations.
2671
2672 This is not like the standard compare, which use their numerical
2673 value. Note that a total ordering is defined for all possible abstract
2674 representations.
2675 """
2676 # if one is negative and the other is positive, it's easy
2677 if self._sign and not other._sign:
2678 return Dec_n1
2679 if not self._sign and other._sign:
2680 return Dec_p1
2681 sign = self._sign
2682
2683 # let's handle both NaN types
2684 self_nan = self._isnan()
2685 other_nan = other._isnan()
2686 if self_nan or other_nan:
2687 if self_nan == other_nan:
2688 if self._int < other._int:
2689 if sign:
2690 return Dec_p1
2691 else:
2692 return Dec_n1
2693 if self._int > other._int:
2694 if sign:
2695 return Dec_n1
2696 else:
2697 return Dec_p1
2698 return Dec_0
2699
2700 if sign:
2701 if self_nan == 1:
2702 return Dec_n1
2703 if other_nan == 1:
2704 return Dec_p1
2705 if self_nan == 2:
2706 return Dec_n1
2707 if other_nan == 2:
2708 return Dec_p1
2709 else:
2710 if self_nan == 1:
2711 return Dec_p1
2712 if other_nan == 1:
2713 return Dec_n1
2714 if self_nan == 2:
2715 return Dec_p1
2716 if other_nan == 2:
2717 return Dec_n1
2718
2719 if self < other:
2720 return Dec_n1
2721 if self > other:
2722 return Dec_p1
2723
2724 if self._exp < other._exp:
2725 if sign:
2726 return Dec_p1
2727 else:
2728 return Dec_n1
2729 if self._exp > other._exp:
2730 if sign:
2731 return Dec_n1
2732 else:
2733 return Dec_p1
2734 return Dec_0
2735
2736
2737 def compare_total_mag(self, other):
2738 """Compares self to other using abstract repr., ignoring sign.
2739
2740 Like compare_total, but with operand's sign ignored and assumed to be 0.
2741 """
2742 s = self.copy_abs()
2743 o = other.copy_abs()
2744 return s.compare_total(o)
2745
2746 def copy_abs(self):
2747 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002748 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002749
2750 def copy_negate(self):
2751 """Returns a copy with the sign inverted."""
2752 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002753 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002754 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002755 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002756
2757 def copy_sign(self, other):
2758 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002759 return _dec_from_triple(other._sign, self._int,
2760 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002761
2762 def exp(self, context=None):
2763 """Returns e ** self."""
2764
2765 if context is None:
2766 context = getcontext()
2767
2768 # exp(NaN) = NaN
2769 ans = self._check_nans(context=context)
2770 if ans:
2771 return ans
2772
2773 # exp(-Infinity) = 0
2774 if self._isinfinity() == -1:
2775 return Dec_0
2776
2777 # exp(0) = 1
2778 if not self:
2779 return Dec_p1
2780
2781 # exp(Infinity) = Infinity
2782 if self._isinfinity() == 1:
2783 return Decimal(self)
2784
2785 # the result is now guaranteed to be inexact (the true
2786 # mathematical result is transcendental). There's no need to
2787 # raise Rounded and Inexact here---they'll always be raised as
2788 # a result of the call to _fix.
2789 p = context.prec
2790 adj = self.adjusted()
2791
2792 # we only need to do any computation for quite a small range
2793 # of adjusted exponents---for example, -29 <= adj <= 10 for
2794 # the default context. For smaller exponent the result is
2795 # indistinguishable from 1 at the given precision, while for
2796 # larger exponent the result either overflows or underflows.
2797 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2798 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002799 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002800 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2801 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002802 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002803 elif self._sign == 0 and adj < -p:
2804 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002805 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002806 elif self._sign == 1 and adj < -p-1:
2807 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002808 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002809 # general case
2810 else:
2811 op = _WorkRep(self)
2812 c, e = op.int, op.exp
2813 if op.sign == 1:
2814 c = -c
2815
2816 # compute correctly rounded result: increase precision by
2817 # 3 digits at a time until we get an unambiguously
2818 # roundable result
2819 extra = 3
2820 while True:
2821 coeff, exp = _dexp(c, e, p+extra)
2822 if coeff % (5*10**(len(str(coeff))-p-1)):
2823 break
2824 extra += 3
2825
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002826 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002827
2828 # at this stage, ans should round correctly with *any*
2829 # rounding mode, not just with ROUND_HALF_EVEN
2830 context = context._shallow_copy()
2831 rounding = context._set_rounding(ROUND_HALF_EVEN)
2832 ans = ans._fix(context)
2833 context.rounding = rounding
2834
2835 return ans
2836
2837 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002838 """Return True if self is canonical; otherwise return False.
2839
2840 Currently, the encoding of a Decimal instance is always
2841 canonical, so this method returns True for any Decimal.
2842 """
2843 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002844
2845 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002846 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002847
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002848 A Decimal instance is considered finite if it is neither
2849 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002850 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002851 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002852
2853 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002854 """Return True if self is infinite; otherwise return False."""
2855 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002856
2857 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002858 """Return True if self is a qNaN or sNaN; otherwise return False."""
2859 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002860
2861 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002862 """Return True if self is a normal number; otherwise return False."""
2863 if self._is_special or not self:
2864 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002865 if context is None:
2866 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002867 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002868
2869 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002870 """Return True if self is a quiet NaN; otherwise return False."""
2871 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002872
2873 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002874 """Return True if self is negative; otherwise return False."""
2875 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002876
2877 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002878 """Return True if self is a signaling NaN; otherwise return False."""
2879 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002880
2881 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002882 """Return True if self is subnormal; otherwise return False."""
2883 if self._is_special or not self:
2884 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002885 if context is None:
2886 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002887 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002888
2889 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002890 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002891 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002892
2893 def _ln_exp_bound(self):
2894 """Compute a lower bound for the adjusted exponent of self.ln().
2895 In other words, compute r such that self.ln() >= 10**r. Assumes
2896 that self is finite and positive and that self != 1.
2897 """
2898
2899 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2900 adj = self._exp + len(self._int) - 1
2901 if adj >= 1:
2902 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2903 return len(str(adj*23//10)) - 1
2904 if adj <= -2:
2905 # argument <= 0.1
2906 return len(str((-1-adj)*23//10)) - 1
2907 op = _WorkRep(self)
2908 c, e = op.int, op.exp
2909 if adj == 0:
2910 # 1 < self < 10
2911 num = str(c-10**-e)
2912 den = str(c)
2913 return len(num) - len(den) - (num < den)
2914 # adj == -1, 0.1 <= self < 1
2915 return e + len(str(10**-e - c)) - 1
2916
2917
2918 def ln(self, context=None):
2919 """Returns the natural (base e) logarithm of self."""
2920
2921 if context is None:
2922 context = getcontext()
2923
2924 # ln(NaN) = NaN
2925 ans = self._check_nans(context=context)
2926 if ans:
2927 return ans
2928
2929 # ln(0.0) == -Infinity
2930 if not self:
2931 return negInf
2932
2933 # ln(Infinity) = Infinity
2934 if self._isinfinity() == 1:
2935 return Inf
2936
2937 # ln(1.0) == 0.0
2938 if self == Dec_p1:
2939 return Dec_0
2940
2941 # ln(negative) raises InvalidOperation
2942 if self._sign == 1:
2943 return context._raise_error(InvalidOperation,
2944 'ln of a negative value')
2945
2946 # result is irrational, so necessarily inexact
2947 op = _WorkRep(self)
2948 c, e = op.int, op.exp
2949 p = context.prec
2950
2951 # correctly rounded result: repeatedly increase precision by 3
2952 # until we get an unambiguously roundable result
2953 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2954 while True:
2955 coeff = _dlog(c, e, places)
2956 # assert len(str(abs(coeff)))-p >= 1
2957 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2958 break
2959 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002960 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002961
2962 context = context._shallow_copy()
2963 rounding = context._set_rounding(ROUND_HALF_EVEN)
2964 ans = ans._fix(context)
2965 context.rounding = rounding
2966 return ans
2967
2968 def _log10_exp_bound(self):
2969 """Compute a lower bound for the adjusted exponent of self.log10().
2970 In other words, find r such that self.log10() >= 10**r.
2971 Assumes that self is finite and positive and that self != 1.
2972 """
2973
2974 # For x >= 10 or x < 0.1 we only need a bound on the integer
2975 # part of log10(self), and this comes directly from the
2976 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2977 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2978 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2979
2980 adj = self._exp + len(self._int) - 1
2981 if adj >= 1:
2982 # self >= 10
2983 return len(str(adj))-1
2984 if adj <= -2:
2985 # self < 0.1
2986 return len(str(-1-adj))-1
2987 op = _WorkRep(self)
2988 c, e = op.int, op.exp
2989 if adj == 0:
2990 # 1 < self < 10
2991 num = str(c-10**-e)
2992 den = str(231*c)
2993 return len(num) - len(den) - (num < den) + 2
2994 # adj == -1, 0.1 <= self < 1
2995 num = str(10**-e-c)
2996 return len(num) + e - (num < "231") - 1
2997
2998 def log10(self, context=None):
2999 """Returns the base 10 logarithm of self."""
3000
3001 if context is None:
3002 context = getcontext()
3003
3004 # log10(NaN) = NaN
3005 ans = self._check_nans(context=context)
3006 if ans:
3007 return ans
3008
3009 # log10(0.0) == -Infinity
3010 if not self:
3011 return negInf
3012
3013 # log10(Infinity) = Infinity
3014 if self._isinfinity() == 1:
3015 return Inf
3016
3017 # log10(negative or -Infinity) raises InvalidOperation
3018 if self._sign == 1:
3019 return context._raise_error(InvalidOperation,
3020 'log10 of a negative value')
3021
3022 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003023 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003024 # answer may need rounding
3025 ans = Decimal(self._exp + len(self._int) - 1)
3026 else:
3027 # result is irrational, so necessarily inexact
3028 op = _WorkRep(self)
3029 c, e = op.int, op.exp
3030 p = context.prec
3031
3032 # correctly rounded result: repeatedly increase precision
3033 # until result is unambiguously roundable
3034 places = p-self._log10_exp_bound()+2
3035 while True:
3036 coeff = _dlog10(c, e, places)
3037 # assert len(str(abs(coeff)))-p >= 1
3038 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3039 break
3040 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003041 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003042
3043 context = context._shallow_copy()
3044 rounding = context._set_rounding(ROUND_HALF_EVEN)
3045 ans = ans._fix(context)
3046 context.rounding = rounding
3047 return ans
3048
3049 def logb(self, context=None):
3050 """ Returns the exponent of the magnitude of self's MSD.
3051
3052 The result is the integer which is the exponent of the magnitude
3053 of the most significant digit of self (as though it were truncated
3054 to a single digit while maintaining the value of that digit and
3055 without limiting the resulting exponent).
3056 """
3057 # logb(NaN) = NaN
3058 ans = self._check_nans(context=context)
3059 if ans:
3060 return ans
3061
3062 if context is None:
3063 context = getcontext()
3064
3065 # logb(+/-Inf) = +Inf
3066 if self._isinfinity():
3067 return Inf
3068
3069 # logb(0) = -Inf, DivisionByZero
3070 if not self:
3071 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3072
3073 # otherwise, simply return the adjusted exponent of self, as a
3074 # Decimal. Note that no attempt is made to fit the result
3075 # into the current context.
3076 return Decimal(self.adjusted())
3077
3078 def _islogical(self):
3079 """Return True if self is a logical operand.
3080
Christian Heimes679db4a2008-01-18 09:56:22 +00003081 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003082 an exponent of 0, and a coefficient whose digits must all be
3083 either 0 or 1.
3084 """
3085 if self._sign != 0 or self._exp != 0:
3086 return False
3087 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003088 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003089 return False
3090 return True
3091
3092 def _fill_logical(self, context, opa, opb):
3093 dif = context.prec - len(opa)
3094 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003095 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003096 elif dif < 0:
3097 opa = opa[-context.prec:]
3098 dif = context.prec - len(opb)
3099 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003100 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003101 elif dif < 0:
3102 opb = opb[-context.prec:]
3103 return opa, opb
3104
3105 def logical_and(self, other, context=None):
3106 """Applies an 'and' operation between self and other's digits."""
3107 if context is None:
3108 context = getcontext()
3109 if not self._islogical() or not other._islogical():
3110 return context._raise_error(InvalidOperation)
3111
3112 # fill to context.prec
3113 (opa, opb) = self._fill_logical(context, self._int, other._int)
3114
3115 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003116 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3117 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003118
3119 def logical_invert(self, context=None):
3120 """Invert all its digits."""
3121 if context is None:
3122 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003123 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3124 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003125
3126 def logical_or(self, other, context=None):
3127 """Applies an 'or' operation between self and other's digits."""
3128 if context is None:
3129 context = getcontext()
3130 if not self._islogical() or not other._islogical():
3131 return context._raise_error(InvalidOperation)
3132
3133 # fill to context.prec
3134 (opa, opb) = self._fill_logical(context, self._int, other._int)
3135
3136 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003137 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3138 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003139
3140 def logical_xor(self, other, context=None):
3141 """Applies an 'xor' operation between self and other's digits."""
3142 if context is None:
3143 context = getcontext()
3144 if not self._islogical() or not other._islogical():
3145 return context._raise_error(InvalidOperation)
3146
3147 # fill to context.prec
3148 (opa, opb) = self._fill_logical(context, self._int, other._int)
3149
3150 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003151 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3152 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003153
3154 def max_mag(self, other, context=None):
3155 """Compares the values numerically with their sign ignored."""
3156 other = _convert_other(other, raiseit=True)
3157
3158 if context is None:
3159 context = getcontext()
3160
3161 if self._is_special or other._is_special:
3162 # If one operand is a quiet NaN and the other is number, then the
3163 # number is always returned
3164 sn = self._isnan()
3165 on = other._isnan()
3166 if sn or on:
3167 if on == 1 and sn != 2:
3168 return self._fix_nan(context)
3169 if sn == 1 and on != 2:
3170 return other._fix_nan(context)
3171 return self._check_nans(other, context)
3172
Christian Heimes77c02eb2008-02-09 02:18:51 +00003173 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003174 if c == 0:
3175 c = self.compare_total(other)
3176
3177 if c == -1:
3178 ans = other
3179 else:
3180 ans = self
3181
Christian Heimes2c181612007-12-17 20:04:13 +00003182 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003183
3184 def min_mag(self, other, context=None):
3185 """Compares the values numerically with their sign ignored."""
3186 other = _convert_other(other, raiseit=True)
3187
3188 if context is None:
3189 context = getcontext()
3190
3191 if self._is_special or other._is_special:
3192 # If one operand is a quiet NaN and the other is number, then the
3193 # number is always returned
3194 sn = self._isnan()
3195 on = other._isnan()
3196 if sn or on:
3197 if on == 1 and sn != 2:
3198 return self._fix_nan(context)
3199 if sn == 1 and on != 2:
3200 return other._fix_nan(context)
3201 return self._check_nans(other, context)
3202
Christian Heimes77c02eb2008-02-09 02:18:51 +00003203 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003204 if c == 0:
3205 c = self.compare_total(other)
3206
3207 if c == -1:
3208 ans = self
3209 else:
3210 ans = other
3211
Christian Heimes2c181612007-12-17 20:04:13 +00003212 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003213
3214 def next_minus(self, context=None):
3215 """Returns the largest representable number smaller than itself."""
3216 if context is None:
3217 context = getcontext()
3218
3219 ans = self._check_nans(context=context)
3220 if ans:
3221 return ans
3222
3223 if self._isinfinity() == -1:
3224 return negInf
3225 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003226 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003227
3228 context = context.copy()
3229 context._set_rounding(ROUND_FLOOR)
3230 context._ignore_all_flags()
3231 new_self = self._fix(context)
3232 if new_self != self:
3233 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003234 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3235 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003236
3237 def next_plus(self, context=None):
3238 """Returns the smallest representable number larger than itself."""
3239 if context is None:
3240 context = getcontext()
3241
3242 ans = self._check_nans(context=context)
3243 if ans:
3244 return ans
3245
3246 if self._isinfinity() == 1:
3247 return Inf
3248 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003249 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003250
3251 context = context.copy()
3252 context._set_rounding(ROUND_CEILING)
3253 context._ignore_all_flags()
3254 new_self = self._fix(context)
3255 if new_self != self:
3256 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003257 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3258 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003259
3260 def next_toward(self, other, context=None):
3261 """Returns the number closest to self, in the direction towards other.
3262
3263 The result is the closest representable number to self
3264 (excluding self) that is in the direction towards other,
3265 unless both have the same value. If the two operands are
3266 numerically equal, then the result is a copy of self with the
3267 sign set to be the same as the sign of other.
3268 """
3269 other = _convert_other(other, raiseit=True)
3270
3271 if context is None:
3272 context = getcontext()
3273
3274 ans = self._check_nans(other, context)
3275 if ans:
3276 return ans
3277
Christian Heimes77c02eb2008-02-09 02:18:51 +00003278 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003279 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003280 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003281
3282 if comparison == -1:
3283 ans = self.next_plus(context)
3284 else: # comparison == 1
3285 ans = self.next_minus(context)
3286
3287 # decide which flags to raise using value of ans
3288 if ans._isinfinity():
3289 context._raise_error(Overflow,
3290 'Infinite result from next_toward',
3291 ans._sign)
3292 context._raise_error(Rounded)
3293 context._raise_error(Inexact)
3294 elif ans.adjusted() < context.Emin:
3295 context._raise_error(Underflow)
3296 context._raise_error(Subnormal)
3297 context._raise_error(Rounded)
3298 context._raise_error(Inexact)
3299 # if precision == 1 then we don't raise Clamped for a
3300 # result 0E-Etiny.
3301 if not ans:
3302 context._raise_error(Clamped)
3303
3304 return ans
3305
3306 def number_class(self, context=None):
3307 """Returns an indication of the class of self.
3308
3309 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003310 sNaN
3311 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003312 -Infinity
3313 -Normal
3314 -Subnormal
3315 -Zero
3316 +Zero
3317 +Subnormal
3318 +Normal
3319 +Infinity
3320 """
3321 if self.is_snan():
3322 return "sNaN"
3323 if self.is_qnan():
3324 return "NaN"
3325 inf = self._isinfinity()
3326 if inf == 1:
3327 return "+Infinity"
3328 if inf == -1:
3329 return "-Infinity"
3330 if self.is_zero():
3331 if self._sign:
3332 return "-Zero"
3333 else:
3334 return "+Zero"
3335 if context is None:
3336 context = getcontext()
3337 if self.is_subnormal(context=context):
3338 if self._sign:
3339 return "-Subnormal"
3340 else:
3341 return "+Subnormal"
3342 # just a normal, regular, boring number, :)
3343 if self._sign:
3344 return "-Normal"
3345 else:
3346 return "+Normal"
3347
3348 def radix(self):
3349 """Just returns 10, as this is Decimal, :)"""
3350 return Decimal(10)
3351
3352 def rotate(self, other, context=None):
3353 """Returns a rotated copy of self, value-of-other times."""
3354 if context is None:
3355 context = getcontext()
3356
3357 ans = self._check_nans(other, context)
3358 if ans:
3359 return ans
3360
3361 if other._exp != 0:
3362 return context._raise_error(InvalidOperation)
3363 if not (-context.prec <= int(other) <= context.prec):
3364 return context._raise_error(InvalidOperation)
3365
3366 if self._isinfinity():
3367 return Decimal(self)
3368
3369 # get values, pad if necessary
3370 torot = int(other)
3371 rotdig = self._int
3372 topad = context.prec - len(rotdig)
3373 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003374 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003375
3376 # let's rotate!
3377 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003378 return _dec_from_triple(self._sign,
3379 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003380
3381 def scaleb (self, other, context=None):
3382 """Returns self operand after adding the second value to its exp."""
3383 if context is None:
3384 context = getcontext()
3385
3386 ans = self._check_nans(other, context)
3387 if ans:
3388 return ans
3389
3390 if other._exp != 0:
3391 return context._raise_error(InvalidOperation)
3392 liminf = -2 * (context.Emax + context.prec)
3393 limsup = 2 * (context.Emax + context.prec)
3394 if not (liminf <= int(other) <= limsup):
3395 return context._raise_error(InvalidOperation)
3396
3397 if self._isinfinity():
3398 return Decimal(self)
3399
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003400 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003401 d = d._fix(context)
3402 return d
3403
3404 def shift(self, other, context=None):
3405 """Returns a shifted copy of self, value-of-other times."""
3406 if context is None:
3407 context = getcontext()
3408
3409 ans = self._check_nans(other, context)
3410 if ans:
3411 return ans
3412
3413 if other._exp != 0:
3414 return context._raise_error(InvalidOperation)
3415 if not (-context.prec <= int(other) <= context.prec):
3416 return context._raise_error(InvalidOperation)
3417
3418 if self._isinfinity():
3419 return Decimal(self)
3420
3421 # get values, pad if necessary
3422 torot = int(other)
3423 if not torot:
3424 return Decimal(self)
3425 rotdig = self._int
3426 topad = context.prec - len(rotdig)
3427 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003428 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003429
3430 # let's shift!
3431 if torot < 0:
3432 rotated = rotdig[:torot]
3433 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003434 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003435 rotated = rotated[-context.prec:]
3436
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003437 return _dec_from_triple(self._sign,
3438 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003439
Guido van Rossumd8faa362007-04-27 19:54:29 +00003440 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003441 def __reduce__(self):
3442 return (self.__class__, (str(self),))
3443
3444 def __copy__(self):
3445 if type(self) == Decimal:
3446 return self # I'm immutable; therefore I am my own clone
3447 return self.__class__(str(self))
3448
3449 def __deepcopy__(self, memo):
3450 if type(self) == Decimal:
3451 return self # My components are also immutable
3452 return self.__class__(str(self))
3453
Christian Heimesf16baeb2008-02-29 14:57:44 +00003454 # PEP 3101 support. See also _parse_format_specifier and _format_align
3455 def __format__(self, specifier, context=None):
3456 """Format a Decimal instance according to the given specifier.
3457
3458 The specifier should be a standard format specifier, with the
3459 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3460 'F', 'g', 'G', and '%' are supported. If the formatting type
3461 is omitted it defaults to 'g' or 'G', depending on the value
3462 of context.capitals.
3463
3464 At this time the 'n' format specifier type (which is supposed
3465 to use the current locale) is not supported.
3466 """
3467
3468 # Note: PEP 3101 says that if the type is not present then
3469 # there should be at least one digit after the decimal point.
3470 # We take the liberty of ignoring this requirement for
3471 # Decimal---it's presumably there to make sure that
3472 # format(float, '') behaves similarly to str(float).
3473 if context is None:
3474 context = getcontext()
3475
3476 spec = _parse_format_specifier(specifier)
3477
3478 # special values don't care about the type or precision...
3479 if self._is_special:
3480 return _format_align(str(self), spec)
3481
3482 # a type of None defaults to 'g' or 'G', depending on context
3483 # if type is '%', adjust exponent of self accordingly
3484 if spec['type'] is None:
3485 spec['type'] = ['g', 'G'][context.capitals]
3486 elif spec['type'] == '%':
3487 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3488
3489 # round if necessary, taking rounding mode from the context
3490 rounding = context.rounding
3491 precision = spec['precision']
3492 if precision is not None:
3493 if spec['type'] in 'eE':
3494 self = self._round(precision+1, rounding)
3495 elif spec['type'] in 'gG':
3496 if len(self._int) > precision:
3497 self = self._round(precision, rounding)
3498 elif spec['type'] in 'fF%':
3499 self = self._rescale(-precision, rounding)
3500 # special case: zeros with a positive exponent can't be
3501 # represented in fixed point; rescale them to 0e0.
3502 elif not self and self._exp > 0 and spec['type'] in 'fF%':
3503 self = self._rescale(0, rounding)
3504
3505 # figure out placement of the decimal point
3506 leftdigits = self._exp + len(self._int)
3507 if spec['type'] in 'fF%':
3508 dotplace = leftdigits
3509 elif spec['type'] in 'eE':
3510 if not self and precision is not None:
3511 dotplace = 1 - precision
3512 else:
3513 dotplace = 1
3514 elif spec['type'] in 'gG':
3515 if self._exp <= 0 and leftdigits > -6:
3516 dotplace = leftdigits
3517 else:
3518 dotplace = 1
3519
3520 # figure out main part of numeric string...
3521 if dotplace <= 0:
3522 num = '0.' + '0'*(-dotplace) + self._int
3523 elif dotplace >= len(self._int):
3524 # make sure we're not padding a '0' with extra zeros on the right
3525 assert dotplace==len(self._int) or self._int != '0'
3526 num = self._int + '0'*(dotplace-len(self._int))
3527 else:
3528 num = self._int[:dotplace] + '.' + self._int[dotplace:]
3529
3530 # ...then the trailing exponent, or trailing '%'
3531 if leftdigits != dotplace or spec['type'] in 'eE':
3532 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3533 num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3534 elif spec['type'] == '%':
3535 num = num + '%'
3536
3537 # add sign
3538 if self._sign == 1:
3539 num = '-' + num
3540 return _format_align(num, spec)
3541
3542
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003543def _dec_from_triple(sign, coefficient, exponent, special=False):
3544 """Create a decimal instance directly, without any validation,
3545 normalization (e.g. removal of leading zeros) or argument
3546 conversion.
3547
3548 This function is for *internal use only*.
3549 """
3550
3551 self = object.__new__(Decimal)
3552 self._sign = sign
3553 self._int = coefficient
3554 self._exp = exponent
3555 self._is_special = special
3556
3557 return self
3558
Guido van Rossumd8faa362007-04-27 19:54:29 +00003559##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003560
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003561
3562# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003563rounding_functions = [name for name in Decimal.__dict__.keys()
3564 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003565for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003566 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003567 globalname = name[1:].upper()
3568 val = globals()[globalname]
3569 Decimal._pick_rounding_function[val] = name
3570
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003571del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003572
Thomas Wouters89f507f2006-12-13 04:49:30 +00003573class _ContextManager(object):
3574 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003575
Thomas Wouters89f507f2006-12-13 04:49:30 +00003576 Sets a copy of the supplied context in __enter__() and restores
3577 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003578 """
3579 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003580 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003581 def __enter__(self):
3582 self.saved_context = getcontext()
3583 setcontext(self.new_context)
3584 return self.new_context
3585 def __exit__(self, t, v, tb):
3586 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003587
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003588class Context(object):
3589 """Contains the context for a Decimal instance.
3590
3591 Contains:
3592 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003593 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003594 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003595 raised when it is caused. Otherwise, a value is
3596 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003597 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003598 (Whether or not the trap_enabler is set)
3599 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003600 Emin - Minimum exponent
3601 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003602 capitals - If 1, 1*10^1 is printed as 1E+1.
3603 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003604 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003605 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003606
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003607 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003608 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003609 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003610 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003611 _ignored_flags=None):
3612 if flags is None:
3613 flags = []
3614 if _ignored_flags is None:
3615 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003616 if not isinstance(flags, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003617 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003618 if traps is not None and not isinstance(traps, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003619 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003620 for name, val in locals().items():
3621 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003622 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003623 else:
3624 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003625 del self.self
3626
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003627 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003628 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003629 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003630 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3631 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3632 % vars(self))
3633 names = [f.__name__ for f, v in self.flags.items() if v]
3634 s.append('flags=[' + ', '.join(names) + ']')
3635 names = [t.__name__ for t, v in self.traps.items() if v]
3636 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003637 return ', '.join(s) + ')'
3638
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003639 def clear_flags(self):
3640 """Reset all flags to zero"""
3641 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003642 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003643
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003644 def _shallow_copy(self):
3645 """Returns a shallow copy from self."""
Christian Heimes2c181612007-12-17 20:04:13 +00003646 nc = Context(self.prec, self.rounding, self.traps,
3647 self.flags, self.Emin, self.Emax,
3648 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003649 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003650
3651 def copy(self):
3652 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003653 nc = Context(self.prec, self.rounding, self.traps.copy(),
Christian Heimes2c181612007-12-17 20:04:13 +00003654 self.flags.copy(), self.Emin, self.Emax,
3655 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003656 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003657 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003658
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003659 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003660 """Handles an error
3661
3662 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003663 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003664 trap_enabler is set, it reaises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00003665 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003666 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003667 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003668 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003669 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003670 return error().handle(self, *args)
3671
Raymond Hettinger86173da2008-02-01 20:38:12 +00003672 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003673 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003674 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003675 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003676
3677 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003678 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003679 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003680
3681 def _ignore_all_flags(self):
3682 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003683 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003684
3685 def _ignore_flags(self, *flags):
3686 """Ignore the flags, if they are raised"""
3687 # Do not mutate-- This way, copies of a context leave the original
3688 # alone.
3689 self._ignored_flags = (self._ignored_flags + list(flags))
3690 return list(flags)
3691
3692 def _regard_flags(self, *flags):
3693 """Stop ignoring the flags, if they are raised"""
3694 if flags and isinstance(flags[0], (tuple,list)):
3695 flags = flags[0]
3696 for flag in flags:
3697 self._ignored_flags.remove(flag)
3698
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003699 def __hash__(self):
3700 """A Context cannot be hashed."""
3701 # We inherit object.__hash__, so we must deny this explicitly
Guido van Rossumd8faa362007-04-27 19:54:29 +00003702 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003703
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003704 def Etiny(self):
3705 """Returns Etiny (= Emin - prec + 1)"""
3706 return int(self.Emin - self.prec + 1)
3707
3708 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003709 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003710 return int(self.Emax - self.prec + 1)
3711
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003712 def _set_rounding(self, type):
3713 """Sets the rounding type.
3714
3715 Sets the rounding type, and returns the current (previous)
3716 rounding type. Often used like:
3717
3718 context = context.copy()
3719 # so you don't change the calling context
3720 # if an error occurs in the middle.
3721 rounding = context._set_rounding(ROUND_UP)
3722 val = self.__sub__(other, context=context)
3723 context._set_rounding(rounding)
3724
3725 This will make it round up for that operation.
3726 """
3727 rounding = self.rounding
3728 self.rounding= type
3729 return rounding
3730
Raymond Hettingerfed52962004-07-14 15:41:57 +00003731 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00003732 """Creates a new Decimal instance but using self as context.
3733
3734 This method implements the to-number operation of the
3735 IBM Decimal specification."""
3736
3737 if isinstance(num, str) and num != num.strip():
3738 return self._raise_error(ConversionSyntax,
3739 "no trailing or leading whitespace is "
3740 "permitted.")
3741
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003742 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003743 if d._isnan() and len(d._int) > self.prec - self._clamp:
3744 return self._raise_error(ConversionSyntax,
3745 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003746 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003747
Guido van Rossumd8faa362007-04-27 19:54:29 +00003748 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003749 def abs(self, a):
3750 """Returns the absolute value of the operand.
3751
3752 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003753 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003754 the plus operation on the operand.
3755
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003756 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003757 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003758 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003759 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003760 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003761 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003762 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003763 Decimal('101.5')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003764 """
3765 return a.__abs__(context=self)
3766
3767 def add(self, a, b):
3768 """Return the sum of the two operands.
3769
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003770 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003771 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003772 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003773 Decimal('1.02E+4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003774 """
3775 return a.__add__(b, context=self)
3776
3777 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003778 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003779
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003780 def canonical(self, a):
3781 """Returns the same Decimal object.
3782
3783 As we do not have different encodings for the same number, the
3784 received object already is in its canonical form.
3785
3786 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003787 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003788 """
3789 return a.canonical(context=self)
3790
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003791 def compare(self, a, b):
3792 """Compares values numerically.
3793
3794 If the signs of the operands differ, a value representing each operand
3795 ('-1' if the operand is less than zero, '0' if the operand is zero or
3796 negative zero, or '1' if the operand is greater than zero) is used in
3797 place of that operand for the comparison instead of the actual
3798 operand.
3799
3800 The comparison is then effected by subtracting the second operand from
3801 the first and then returning a value according to the result of the
3802 subtraction: '-1' if the result is less than zero, '0' if the result is
3803 zero or negative zero, or '1' if the result is greater than zero.
3804
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003805 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003806 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003807 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003808 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003809 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003810 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003811 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003812 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003813 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003814 Decimal('1')
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 Hettinger7c85fa42004-07-01 11:01:35 +00003817 """
3818 return a.compare(b, context=self)
3819
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003820 def compare_signal(self, a, b):
3821 """Compares the values of the two operands numerically.
3822
3823 It's pretty much like compare(), but all NaNs signal, with signaling
3824 NaNs taking precedence over quiet NaNs.
3825
3826 >>> c = ExtendedContext
3827 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003828 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003829 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003830 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003831 >>> c.flags[InvalidOperation] = 0
3832 >>> print(c.flags[InvalidOperation])
3833 0
3834 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003835 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003836 >>> print(c.flags[InvalidOperation])
3837 1
3838 >>> c.flags[InvalidOperation] = 0
3839 >>> print(c.flags[InvalidOperation])
3840 0
3841 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003842 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003843 >>> print(c.flags[InvalidOperation])
3844 1
3845 """
3846 return a.compare_signal(b, context=self)
3847
3848 def compare_total(self, a, b):
3849 """Compares two operands using their abstract representation.
3850
3851 This is not like the standard compare, which use their numerical
3852 value. Note that a total ordering is defined for all possible abstract
3853 representations.
3854
3855 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003856 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003857 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003858 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003859 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003860 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003861 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003862 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003863 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003864 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003865 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003866 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003867 """
3868 return a.compare_total(b)
3869
3870 def compare_total_mag(self, a, b):
3871 """Compares two operands using their abstract representation ignoring sign.
3872
3873 Like compare_total, but with operand's sign ignored and assumed to be 0.
3874 """
3875 return a.compare_total_mag(b)
3876
3877 def copy_abs(self, a):
3878 """Returns a copy of the operand with the sign set to 0.
3879
3880 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003881 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003882 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003883 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003884 """
3885 return a.copy_abs()
3886
3887 def copy_decimal(self, a):
3888 """Returns a copy of the decimal objet.
3889
3890 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003891 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003892 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003893 Decimal('-1.00')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003894 """
3895 return Decimal(a)
3896
3897 def copy_negate(self, a):
3898 """Returns a copy of the operand with the sign inverted.
3899
3900 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003901 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003902 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003903 Decimal('101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003904 """
3905 return a.copy_negate()
3906
3907 def copy_sign(self, a, b):
3908 """Copies the second operand's sign to the first one.
3909
3910 In detail, it returns a copy of the first operand with the sign
3911 equal to the sign of the second operand.
3912
3913 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003914 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003915 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003916 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003917 >>> 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 """
3922 return a.copy_sign(b)
3923
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003924 def divide(self, a, b):
3925 """Decimal division in a specified context.
3926
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003927 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003928 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003929 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003930 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003931 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003932 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003933 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003934 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003935 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003936 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003937 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003938 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003939 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003940 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003941 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003942 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003943 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003944 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003945 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003946 Decimal('1.20E+6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003947 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003948 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003949
3950 def divide_int(self, a, b):
3951 """Divides two numbers and returns the integer part of the result.
3952
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003953 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003954 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003955 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003956 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003957 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003958 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003959 """
3960 return a.__floordiv__(b, context=self)
3961
3962 def divmod(self, a, b):
3963 return a.__divmod__(b, context=self)
3964
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003965 def exp(self, a):
3966 """Returns e ** a.
3967
3968 >>> c = ExtendedContext.copy()
3969 >>> c.Emin = -999
3970 >>> c.Emax = 999
3971 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003972 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003973 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003974 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003975 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003976 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003977 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003978 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003979 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003980 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003981 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003982 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003983 """
3984 return a.exp(context=self)
3985
3986 def fma(self, a, b, c):
3987 """Returns a multiplied by b, plus c.
3988
3989 The first two operands are multiplied together, using multiply,
3990 the third operand is then added to the result of that
3991 multiplication, using add, all with only one final rounding.
3992
3993 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003994 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003995 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003996 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003997 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003998 Decimal('1.38435736E+12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003999 """
4000 return a.fma(b, c, context=self)
4001
4002 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004003 """Return True if the operand is canonical; otherwise return False.
4004
4005 Currently, the encoding of a Decimal instance is always
4006 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004007
4008 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004009 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004010 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004011 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004012
4013 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004014 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004015
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004016 A Decimal instance is considered finite if it is neither
4017 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004018
4019 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004020 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004021 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004022 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004023 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004024 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004025 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004026 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004027 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004028 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004029 """
4030 return a.is_finite()
4031
4032 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004033 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004034
4035 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004036 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004037 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004038 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004039 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004040 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004041 """
4042 return a.is_infinite()
4043
4044 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004045 """Return True if the operand is a qNaN or sNaN;
4046 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004047
4048 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004049 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004050 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004051 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004052 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004053 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004054 """
4055 return a.is_nan()
4056
4057 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004058 """Return True if the operand is a normal number;
4059 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004060
4061 >>> c = ExtendedContext.copy()
4062 >>> c.Emin = -999
4063 >>> c.Emax = 999
4064 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004065 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004066 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004067 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004068 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004069 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004070 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004071 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004072 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004073 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004074 """
4075 return a.is_normal(context=self)
4076
4077 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004078 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004079
4080 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004081 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004082 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004083 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004084 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004085 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004086 """
4087 return a.is_qnan()
4088
4089 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004090 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004091
4092 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004093 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004094 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004095 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004096 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004097 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004098 """
4099 return a.is_signed()
4100
4101 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004102 """Return True if the operand is a signaling NaN;
4103 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004104
4105 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004106 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004107 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004108 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004109 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004110 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004111 """
4112 return a.is_snan()
4113
4114 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004115 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004116
4117 >>> c = ExtendedContext.copy()
4118 >>> c.Emin = -999
4119 >>> c.Emax = 999
4120 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004121 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004122 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004123 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004124 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004125 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004126 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004127 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004128 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004129 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004130 """
4131 return a.is_subnormal(context=self)
4132
4133 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004134 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004135
4136 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004137 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004138 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004139 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004140 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004141 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004142 """
4143 return a.is_zero()
4144
4145 def ln(self, a):
4146 """Returns the natural (base e) logarithm of the operand.
4147
4148 >>> c = ExtendedContext.copy()
4149 >>> c.Emin = -999
4150 >>> c.Emax = 999
4151 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004152 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004153 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004154 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004155 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004156 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004157 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004158 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004159 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004160 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004161 """
4162 return a.ln(context=self)
4163
4164 def log10(self, a):
4165 """Returns the base 10 logarithm of the operand.
4166
4167 >>> c = ExtendedContext.copy()
4168 >>> c.Emin = -999
4169 >>> c.Emax = 999
4170 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004171 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004172 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004173 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004174 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004175 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004176 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004177 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004178 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004179 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004180 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004181 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004182 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004183 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004184 """
4185 return a.log10(context=self)
4186
4187 def logb(self, a):
4188 """ Returns the exponent of the magnitude of the operand's MSD.
4189
4190 The result is the integer which is the exponent of the magnitude
4191 of the most significant digit of the operand (as though the
4192 operand were truncated to a single digit while maintaining the
4193 value of that digit and without limiting the resulting exponent).
4194
4195 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004196 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004197 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004198 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004199 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004200 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004201 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004202 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004203 """
4204 return a.logb(context=self)
4205
4206 def logical_and(self, a, b):
4207 """Applies the logical operation 'and' between each operand's digits.
4208
4209 The operands must be both logical numbers.
4210
4211 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004212 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004213 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004214 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004215 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004216 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004217 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004218 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004219 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004220 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004221 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004222 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004223 """
4224 return a.logical_and(b, context=self)
4225
4226 def logical_invert(self, a):
4227 """Invert all the digits in the operand.
4228
4229 The operand must be a logical number.
4230
4231 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004232 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004233 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004234 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004235 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004236 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004237 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004238 Decimal('10101010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004239 """
4240 return a.logical_invert(context=self)
4241
4242 def logical_or(self, a, b):
4243 """Applies the logical operation 'or' between each operand's digits.
4244
4245 The operands must be both logical numbers.
4246
4247 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004248 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004249 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004250 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004251 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004252 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004253 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004254 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004255 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004256 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004257 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004258 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004259 """
4260 return a.logical_or(b, context=self)
4261
4262 def logical_xor(self, a, b):
4263 """Applies the logical operation 'xor' between each operand's digits.
4264
4265 The operands must be both logical numbers.
4266
4267 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004268 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004269 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004270 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004271 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004272 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004273 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004274 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004275 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004276 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004277 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004278 Decimal('1101')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004279 """
4280 return a.logical_xor(b, context=self)
4281
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004282 def max(self, a,b):
4283 """max compares two values numerically and returns the maximum.
4284
4285 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004286 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004287 operation. If they are numerically equal then the left-hand operand
4288 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004289 infinity) of the two operands is chosen as the result.
4290
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004291 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004292 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004293 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004294 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004295 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004296 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004297 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004298 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004299 """
4300 return a.max(b, context=self)
4301
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004302 def max_mag(self, a, b):
4303 """Compares the values numerically with their sign ignored."""
4304 return a.max_mag(b, context=self)
4305
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004306 def min(self, a,b):
4307 """min compares two values numerically and returns the minimum.
4308
4309 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004310 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004311 operation. If they are numerically equal then the left-hand operand
4312 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004313 infinity) of the two operands is chosen as the result.
4314
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004315 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004316 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004317 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004318 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004319 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004320 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004321 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004322 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004323 """
4324 return a.min(b, context=self)
4325
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004326 def min_mag(self, a, b):
4327 """Compares the values numerically with their sign ignored."""
4328 return a.min_mag(b, context=self)
4329
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004330 def minus(self, a):
4331 """Minus corresponds to unary prefix minus in Python.
4332
4333 The operation is evaluated using the same rules as subtract; the
4334 operation minus(a) is calculated as subtract('0', a) where the '0'
4335 has the same exponent as the operand.
4336
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004337 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004338 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004339 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004340 Decimal('1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004341 """
4342 return a.__neg__(context=self)
4343
4344 def multiply(self, a, b):
4345 """multiply multiplies two operands.
4346
4347 If either operand is a special value then the general rules apply.
4348 Otherwise, the operands are multiplied together ('long multiplication'),
4349 resulting in a number which may be as long as the sum of the lengths
4350 of the two operands.
4351
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004352 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004353 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004354 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004355 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004356 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004357 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004358 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004359 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004360 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004361 Decimal('4.28135971E+11')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004362 """
4363 return a.__mul__(b, context=self)
4364
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004365 def next_minus(self, a):
4366 """Returns the largest representable number smaller than a.
4367
4368 >>> c = ExtendedContext.copy()
4369 >>> c.Emin = -999
4370 >>> c.Emax = 999
4371 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004372 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004373 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004374 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004375 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004376 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004377 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004378 Decimal('9.99999999E+999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004379 """
4380 return a.next_minus(context=self)
4381
4382 def next_plus(self, a):
4383 """Returns the smallest representable number larger than a.
4384
4385 >>> c = ExtendedContext.copy()
4386 >>> c.Emin = -999
4387 >>> c.Emax = 999
4388 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004389 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004390 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004391 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004392 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004393 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004394 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004395 Decimal('-9.99999999E+999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004396 """
4397 return a.next_plus(context=self)
4398
4399 def next_toward(self, a, b):
4400 """Returns the number closest to a, in direction towards b.
4401
4402 The result is the closest representable number from the first
4403 operand (but not the first operand) that is in the direction
4404 towards the second operand, unless the operands have the same
4405 value.
4406
4407 >>> c = ExtendedContext.copy()
4408 >>> c.Emin = -999
4409 >>> c.Emax = 999
4410 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004411 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004412 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004413 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004414 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004415 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004416 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004417 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004418 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004419 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004420 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004421 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004422 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004423 Decimal('-0.00')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004424 """
4425 return a.next_toward(b, context=self)
4426
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004427 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004428 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004429
4430 Essentially a plus operation with all trailing zeros removed from the
4431 result.
4432
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004433 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004434 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004435 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004436 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004437 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004438 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004439 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004440 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004441 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004442 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004443 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004444 Decimal('0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004445 """
4446 return a.normalize(context=self)
4447
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004448 def number_class(self, a):
4449 """Returns an indication of the class of the operand.
4450
4451 The class is one of the following strings:
4452 -sNaN
4453 -NaN
4454 -Infinity
4455 -Normal
4456 -Subnormal
4457 -Zero
4458 +Zero
4459 +Subnormal
4460 +Normal
4461 +Infinity
4462
4463 >>> c = Context(ExtendedContext)
4464 >>> c.Emin = -999
4465 >>> c.Emax = 999
4466 >>> c.number_class(Decimal('Infinity'))
4467 '+Infinity'
4468 >>> c.number_class(Decimal('1E-10'))
4469 '+Normal'
4470 >>> c.number_class(Decimal('2.50'))
4471 '+Normal'
4472 >>> c.number_class(Decimal('0.1E-999'))
4473 '+Subnormal'
4474 >>> c.number_class(Decimal('0'))
4475 '+Zero'
4476 >>> c.number_class(Decimal('-0'))
4477 '-Zero'
4478 >>> c.number_class(Decimal('-0.1E-999'))
4479 '-Subnormal'
4480 >>> c.number_class(Decimal('-1E-10'))
4481 '-Normal'
4482 >>> c.number_class(Decimal('-2.50'))
4483 '-Normal'
4484 >>> c.number_class(Decimal('-Infinity'))
4485 '-Infinity'
4486 >>> c.number_class(Decimal('NaN'))
4487 'NaN'
4488 >>> c.number_class(Decimal('-NaN'))
4489 'NaN'
4490 >>> c.number_class(Decimal('sNaN'))
4491 'sNaN'
4492 """
4493 return a.number_class(context=self)
4494
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004495 def plus(self, a):
4496 """Plus corresponds to unary prefix plus in Python.
4497
4498 The operation is evaluated using the same rules as add; the
4499 operation plus(a) is calculated as add('0', a) where the '0'
4500 has the same exponent as the operand.
4501
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004502 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004503 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004504 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004505 Decimal('-1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004506 """
4507 return a.__pos__(context=self)
4508
4509 def power(self, a, b, modulo=None):
4510 """Raises a to the power of b, to modulo if given.
4511
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004512 With two arguments, compute a**b. If a is negative then b
4513 must be integral. The result will be inexact unless b is
4514 integral and the result is finite and can be expressed exactly
4515 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004516
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004517 With three arguments, compute (a**b) % modulo. For the
4518 three argument form, the following restrictions on the
4519 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004520
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004521 - all three arguments must be integral
4522 - b must be nonnegative
4523 - at least one of a or b must be nonzero
4524 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004525
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004526 The result of pow(a, b, modulo) is identical to the result
4527 that would be obtained by computing (a**b) % modulo with
4528 unbounded precision, but is computed more efficiently. It is
4529 always exact.
4530
4531 >>> c = ExtendedContext.copy()
4532 >>> c.Emin = -999
4533 >>> c.Emax = 999
4534 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004535 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004536 >>> c.power(Decimal('-2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004537 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004538 >>> c.power(Decimal('2'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004539 Decimal('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004540 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004541 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004542 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004543 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004544 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004545 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004546 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004547 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004548 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004549 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004550 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004551 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004552 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004553 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004554 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004555 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004556 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004557 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004558 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004559 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004560
4561 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004562 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004563 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004564 Decimal('-11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004565 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004566 Decimal('1')
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('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004570 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004571 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004572 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004573 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004574 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004575 """
4576 return a.__pow__(b, modulo, context=self)
4577
4578 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004579 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004580
4581 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004582 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004583 exponent is being increased), multiplied by a positive power of ten (if
4584 the exponent is being decreased), or is unchanged (if the exponent is
4585 already equal to that of the right-hand operand).
4586
4587 Unlike other operations, if the length of the coefficient after the
4588 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004589 operation condition is raised. This guarantees that, unless there is
4590 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004591 equal to that of the right-hand operand.
4592
4593 Also unlike other operations, quantize will never raise Underflow, even
4594 if the result is subnormal and inexact.
4595
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004596 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004597 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004598 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004599 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004600 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004601 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004602 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004603 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004604 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004605 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004606 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004607 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004608 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004609 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004610 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004611 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004612 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004613 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004614 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004615 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004616 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004617 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004618 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004619 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004620 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004621 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004622 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004623 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004624 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004625 Decimal('2E+2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004626 """
4627 return a.quantize(b, context=self)
4628
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004629 def radix(self):
4630 """Just returns 10, as this is Decimal, :)
4631
4632 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004633 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004634 """
4635 return Decimal(10)
4636
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004637 def remainder(self, a, b):
4638 """Returns the remainder from integer division.
4639
4640 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004641 calculating integer division as described for divide-integer, rounded
4642 to precision digits if necessary. The sign of the result, if
4643 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004644
4645 This operation will fail under the same conditions as integer division
4646 (that is, if integer division on the same two operands would fail, the
4647 remainder cannot be calculated).
4648
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004649 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004650 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004651 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004652 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004653 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004654 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004655 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004656 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004657 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004658 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004659 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004660 Decimal('1.0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004661 """
4662 return a.__mod__(b, context=self)
4663
4664 def remainder_near(self, a, b):
4665 """Returns to be "a - b * n", where n is the integer nearest the exact
4666 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004667 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004668 sign of a.
4669
4670 This operation will fail under the same conditions as integer division
4671 (that is, if integer division on the same two operands would fail, the
4672 remainder cannot be calculated).
4673
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004674 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004675 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004676 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004677 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004678 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004679 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004680 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004681 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004682 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004683 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004684 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004685 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004686 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004687 Decimal('-0.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004688 """
4689 return a.remainder_near(b, context=self)
4690
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004691 def rotate(self, a, b):
4692 """Returns a rotated copy of a, b times.
4693
4694 The coefficient of the result is a rotated copy of the digits in
4695 the coefficient of the first operand. The number of places of
4696 rotation is taken from the absolute value of the second operand,
4697 with the rotation being to the left if the second operand is
4698 positive or to the right otherwise.
4699
4700 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004701 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004702 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004703 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004704 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004705 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004706 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004707 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004708 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004709 Decimal('345678912')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004710 """
4711 return a.rotate(b, context=self)
4712
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004713 def same_quantum(self, a, b):
4714 """Returns True if the two operands have the same exponent.
4715
4716 The result is never affected by either the sign or the coefficient of
4717 either operand.
4718
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004719 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004720 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004721 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004722 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004723 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004724 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004725 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004726 True
4727 """
4728 return a.same_quantum(b)
4729
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004730 def scaleb (self, a, b):
4731 """Returns the first operand after adding the second value its exp.
4732
4733 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004734 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004735 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004736 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004737 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004738 Decimal('7.50E+3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004739 """
4740 return a.scaleb (b, context=self)
4741
4742 def shift(self, a, b):
4743 """Returns a shifted copy of a, b times.
4744
4745 The coefficient of the result is a shifted copy of the digits
4746 in the coefficient of the first operand. The number of places
4747 to shift is taken from the absolute value of the second operand,
4748 with the shift being to the left if the second operand is
4749 positive or to the right otherwise. Digits shifted into the
4750 coefficient are zeros.
4751
4752 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004753 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004754 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004755 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004756 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004757 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004758 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004759 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004760 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004761 Decimal('345678900')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004762 """
4763 return a.shift(b, context=self)
4764
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004765 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004766 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004767
4768 If the result must be inexact, it is rounded using the round-half-even
4769 algorithm.
4770
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004771 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004772 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004773 >>> ExtendedContext.sqrt(Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004774 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004775 >>> ExtendedContext.sqrt(Decimal('0.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004776 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004777 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004778 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004779 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004780 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004781 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004782 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004783 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004784 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004785 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004786 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004787 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004788 Decimal('3.16227766')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004789 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004790 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004791 """
4792 return a.sqrt(context=self)
4793
4794 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004795 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004796
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004797 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004798 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004799 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004800 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004801 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004802 Decimal('-0.77')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004803 """
4804 return a.__sub__(b, context=self)
4805
4806 def to_eng_string(self, a):
4807 """Converts a number to a string, using scientific notation.
4808
4809 The operation is not affected by the context.
4810 """
4811 return a.to_eng_string(context=self)
4812
4813 def to_sci_string(self, a):
4814 """Converts a number to a string, using scientific notation.
4815
4816 The operation is not affected by the context.
4817 """
4818 return a.__str__(context=self)
4819
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004820 def to_integral_exact(self, a):
4821 """Rounds to an integer.
4822
4823 When the operand has a negative exponent, the result is the same
4824 as using the quantize() operation using the given operand as the
4825 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4826 of the operand as the precision setting; Inexact and Rounded flags
4827 are allowed in this operation. The rounding mode is taken from the
4828 context.
4829
4830 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004831 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004832 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004833 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004834 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004835 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004836 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004837 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004838 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004839 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004840 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004841 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004842 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004843 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004844 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004845 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004846 """
4847 return a.to_integral_exact(context=self)
4848
4849 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004850 """Rounds to an integer.
4851
4852 When the operand has a negative exponent, the result is the same
4853 as using the quantize() operation using the given operand as the
4854 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4855 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004856 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004857
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004858 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004859 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004860 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004861 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004862 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004863 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004864 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004865 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004866 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004867 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004868 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004869 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004870 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004871 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004872 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004873 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004874 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004875 return a.to_integral_value(context=self)
4876
4877 # the method name changed, but we provide also the old one, for compatibility
4878 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004879
4880class _WorkRep(object):
4881 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004882 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004883 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004884 # exp: None, int, or string
4885
4886 def __init__(self, value=None):
4887 if value is None:
4888 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004889 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004890 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004891 elif isinstance(value, Decimal):
4892 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00004893 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004894 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004895 else:
4896 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004897 self.sign = value[0]
4898 self.int = value[1]
4899 self.exp = value[2]
4900
4901 def __repr__(self):
4902 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4903
4904 __str__ = __repr__
4905
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004906
4907
Christian Heimes2c181612007-12-17 20:04:13 +00004908def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004909 """Normalizes op1, op2 to have the same exp and length of coefficient.
4910
4911 Done during addition.
4912 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004913 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004914 tmp = op2
4915 other = op1
4916 else:
4917 tmp = op1
4918 other = op2
4919
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004920 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4921 # Then adding 10**exp to tmp has the same effect (after rounding)
4922 # as adding any positive quantity smaller than 10**exp; similarly
4923 # for subtraction. So if other is smaller than 10**exp we replace
4924 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00004925 tmp_len = len(str(tmp.int))
4926 other_len = len(str(other.int))
4927 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4928 if other_len + other.exp - 1 < exp:
4929 other.int = 1
4930 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004931
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004932 tmp.int *= 10 ** (tmp.exp - other.exp)
4933 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004934 return op1, op2
4935
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004936##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004937
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004938# This function from Tim Peters was taken from here:
4939# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4940# The correction being in the function definition is for speed, and
4941# the whole function is not resolved with math.log because of avoiding
4942# the use of floats.
4943def _nbits(n, correction = {
4944 '0': 4, '1': 3, '2': 2, '3': 2,
4945 '4': 1, '5': 1, '6': 1, '7': 1,
4946 '8': 0, '9': 0, 'a': 0, 'b': 0,
4947 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4948 """Number of bits in binary representation of the positive integer n,
4949 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004950 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004951 if n < 0:
4952 raise ValueError("The argument to _nbits should be nonnegative.")
4953 hex_n = "%x" % n
4954 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004955
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004956def _sqrt_nearest(n, a):
4957 """Closest integer to the square root of the positive integer n. a is
4958 an initial approximation to the square root. Any positive integer
4959 will do for a, but the closer a is to the square root of n the
4960 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004961
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004962 """
4963 if n <= 0 or a <= 0:
4964 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4965
4966 b=0
4967 while a != b:
4968 b, a = a, a--n//a>>1
4969 return a
4970
4971def _rshift_nearest(x, shift):
4972 """Given an integer x and a nonnegative integer shift, return closest
4973 integer to x / 2**shift; use round-to-even in case of a tie.
4974
4975 """
4976 b, q = 1 << shift, x >> shift
4977 return q + (2*(x & (b-1)) + (q&1) > b)
4978
4979def _div_nearest(a, b):
4980 """Closest integer to a/b, a and b positive integers; rounds to even
4981 in the case of a tie.
4982
4983 """
4984 q, r = divmod(a, b)
4985 return q + (2*r + (q&1) > b)
4986
4987def _ilog(x, M, L = 8):
4988 """Integer approximation to M*log(x/M), with absolute error boundable
4989 in terms only of x/M.
4990
4991 Given positive integers x and M, return an integer approximation to
4992 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4993 between the approximation and the exact result is at most 22. For
4994 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4995 both cases these are upper bounds on the error; it will usually be
4996 much smaller."""
4997
4998 # The basic algorithm is the following: let log1p be the function
4999 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5000 # the reduction
5001 #
5002 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5003 #
5004 # repeatedly until the argument to log1p is small (< 2**-L in
5005 # absolute value). For small y we can use the Taylor series
5006 # expansion
5007 #
5008 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5009 #
5010 # truncating at T such that y**T is small enough. The whole
5011 # computation is carried out in a form of fixed-point arithmetic,
5012 # with a real number z being represented by an integer
5013 # approximation to z*M. To avoid loss of precision, the y below
5014 # is actually an integer approximation to 2**R*y*M, where R is the
5015 # number of reductions performed so far.
5016
5017 y = x-M
5018 # argument reduction; R = number of reductions performed
5019 R = 0
5020 while (R <= L and abs(y) << L-R >= M or
5021 R > L and abs(y) >> R-L >= M):
5022 y = _div_nearest((M*y) << 1,
5023 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5024 R += 1
5025
5026 # Taylor series with T terms
5027 T = -int(-10*len(str(M))//(3*L))
5028 yshift = _rshift_nearest(y, R)
5029 w = _div_nearest(M, T)
5030 for k in range(T-1, 0, -1):
5031 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5032
5033 return _div_nearest(w*y, M)
5034
5035def _dlog10(c, e, p):
5036 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5037 approximation to 10**p * log10(c*10**e), with an absolute error of
5038 at most 1. Assumes that c*10**e is not exactly 1."""
5039
5040 # increase precision by 2; compensate for this by dividing
5041 # final result by 100
5042 p += 2
5043
5044 # write c*10**e as d*10**f with either:
5045 # f >= 0 and 1 <= d <= 10, or
5046 # f <= 0 and 0.1 <= d <= 1.
5047 # Thus for c*10**e close to 1, f = 0
5048 l = len(str(c))
5049 f = e+l - (e+l >= 1)
5050
5051 if p > 0:
5052 M = 10**p
5053 k = e+p-f
5054 if k >= 0:
5055 c *= 10**k
5056 else:
5057 c = _div_nearest(c, 10**-k)
5058
5059 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005060 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005061 log_d = _div_nearest(log_d*M, log_10)
5062 log_tenpower = f*M # exact
5063 else:
5064 log_d = 0 # error < 2.31
5065 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
5066
5067 return _div_nearest(log_tenpower+log_d, 100)
5068
5069def _dlog(c, e, p):
5070 """Given integers c, e and p with c > 0, compute an integer
5071 approximation to 10**p * log(c*10**e), with an absolute error of
5072 at most 1. Assumes that c*10**e is not exactly 1."""
5073
5074 # Increase precision by 2. The precision increase is compensated
5075 # for at the end with a division by 100.
5076 p += 2
5077
5078 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5079 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5080 # as 10**p * log(d) + 10**p*f * log(10).
5081 l = len(str(c))
5082 f = e+l - (e+l >= 1)
5083
5084 # compute approximation to 10**p*log(d), with error < 27
5085 if p > 0:
5086 k = e+p-f
5087 if k >= 0:
5088 c *= 10**k
5089 else:
5090 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5091
5092 # _ilog magnifies existing error in c by a factor of at most 10
5093 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5094 else:
5095 # p <= 0: just approximate the whole thing by 0; error < 2.31
5096 log_d = 0
5097
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005098 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005099 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005100 extra = len(str(abs(f)))-1
5101 if p + extra >= 0:
5102 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5103 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5104 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005105 else:
5106 f_log_ten = 0
5107 else:
5108 f_log_ten = 0
5109
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005110 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005111 return _div_nearest(f_log_ten + log_d, 100)
5112
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005113class _Log10Memoize(object):
5114 """Class to compute, store, and allow retrieval of, digits of the
5115 constant log(10) = 2.302585.... This constant is needed by
5116 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5117 def __init__(self):
5118 self.digits = "23025850929940456840179914546843642076011014886"
5119
5120 def getdigits(self, p):
5121 """Given an integer p >= 0, return floor(10**p)*log(10).
5122
5123 For example, self.getdigits(3) returns 2302.
5124 """
5125 # digits are stored as a string, for quick conversion to
5126 # integer in the case that we've already computed enough
5127 # digits; the stored digits should always be correct
5128 # (truncated, not rounded to nearest).
5129 if p < 0:
5130 raise ValueError("p should be nonnegative")
5131
5132 if p >= len(self.digits):
5133 # compute p+3, p+6, p+9, ... digits; continue until at
5134 # least one of the extra digits is nonzero
5135 extra = 3
5136 while True:
5137 # compute p+extra digits, correct to within 1ulp
5138 M = 10**(p+extra+2)
5139 digits = str(_div_nearest(_ilog(10*M, M), 100))
5140 if digits[-extra:] != '0'*extra:
5141 break
5142 extra += 3
5143 # keep all reliable digits so far; remove trailing zeros
5144 # and next nonzero digit
5145 self.digits = digits.rstrip('0')[:-1]
5146 return int(self.digits[:p+1])
5147
5148_log10_digits = _Log10Memoize().getdigits
5149
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005150def _iexp(x, M, L=8):
5151 """Given integers x and M, M > 0, such that x/M is small in absolute
5152 value, compute an integer approximation to M*exp(x/M). For 0 <=
5153 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5154 is usually much smaller)."""
5155
5156 # Algorithm: to compute exp(z) for a real number z, first divide z
5157 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5158 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5159 # series
5160 #
5161 # expm1(x) = x + x**2/2! + x**3/3! + ...
5162 #
5163 # Now use the identity
5164 #
5165 # expm1(2x) = expm1(x)*(expm1(x)+2)
5166 #
5167 # R times to compute the sequence expm1(z/2**R),
5168 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5169
5170 # Find R such that x/2**R/M <= 2**-L
5171 R = _nbits((x<<L)//M)
5172
5173 # Taylor series. (2**L)**T > M
5174 T = -int(-10*len(str(M))//(3*L))
5175 y = _div_nearest(x, T)
5176 Mshift = M<<R
5177 for i in range(T-1, 0, -1):
5178 y = _div_nearest(x*(Mshift + y), Mshift * i)
5179
5180 # Expansion
5181 for k in range(R-1, -1, -1):
5182 Mshift = M<<(k+2)
5183 y = _div_nearest(y*(y+Mshift), Mshift)
5184
5185 return M+y
5186
5187def _dexp(c, e, p):
5188 """Compute an approximation to exp(c*10**e), with p decimal places of
5189 precision.
5190
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005191 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005192
5193 10**(p-1) <= d <= 10**p, and
5194 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5195
5196 In other words, d*10**f is an approximation to exp(c*10**e) with p
5197 digits of precision, and with an error in d of at most 1. This is
5198 almost, but not quite, the same as the error being < 1ulp: when d
5199 = 10**(p-1) the error could be up to 10 ulp."""
5200
5201 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5202 p += 2
5203
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005204 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005205 extra = max(0, e + len(str(c)) - 1)
5206 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005207
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005208 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005209 # rounding down
5210 shift = e+q
5211 if shift >= 0:
5212 cshift = c*10**shift
5213 else:
5214 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005215 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005216
5217 # reduce remainder back to original precision
5218 rem = _div_nearest(rem, 10**extra)
5219
5220 # error in result of _iexp < 120; error after division < 0.62
5221 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5222
5223def _dpower(xc, xe, yc, ye, p):
5224 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5225 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5226
5227 10**(p-1) <= c <= 10**p, and
5228 (c-1)*10**e < x**y < (c+1)*10**e
5229
5230 in other words, c*10**e is an approximation to x**y with p digits
5231 of precision, and with an error in c of at most 1. (This is
5232 almost, but not quite, the same as the error being < 1ulp: when c
5233 == 10**(p-1) we can only guarantee error < 10ulp.)
5234
5235 We assume that: x is positive and not equal to 1, and y is nonzero.
5236 """
5237
5238 # Find b such that 10**(b-1) <= |y| <= 10**b
5239 b = len(str(abs(yc))) + ye
5240
5241 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5242 lxc = _dlog(xc, xe, p+b+1)
5243
5244 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5245 shift = ye-b
5246 if shift >= 0:
5247 pc = lxc*yc*10**shift
5248 else:
5249 pc = _div_nearest(lxc*yc, 10**-shift)
5250
5251 if pc == 0:
5252 # we prefer a result that isn't exactly 1; this makes it
5253 # easier to compute a correctly rounded result in __pow__
5254 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5255 coeff, exp = 10**(p-1)+1, 1-p
5256 else:
5257 coeff, exp = 10**p-1, -p
5258 else:
5259 coeff, exp = _dexp(pc, -(p+1), p+1)
5260 coeff = _div_nearest(coeff, 10)
5261 exp += 1
5262
5263 return coeff, exp
5264
5265def _log10_lb(c, correction = {
5266 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5267 '6': 23, '7': 16, '8': 10, '9': 5}):
5268 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5269 if c <= 0:
5270 raise ValueError("The argument to _log10_lb should be nonnegative.")
5271 str_c = str(c)
5272 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005273
Guido van Rossumd8faa362007-04-27 19:54:29 +00005274##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005275
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005276def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005277 """Convert other to Decimal.
5278
5279 Verifies that it's ok to use in an implicit construction.
5280 """
5281 if isinstance(other, Decimal):
5282 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005283 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005284 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005285 if raiseit:
5286 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005287 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005288
Guido van Rossumd8faa362007-04-27 19:54:29 +00005289##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005290
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005291# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005292# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005293
5294DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005295 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005296 traps=[DivisionByZero, Overflow, InvalidOperation],
5297 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005298 Emax=999999999,
5299 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005300 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005301)
5302
5303# Pre-made alternate contexts offered by the specification
5304# Don't change these; the user should be able to select these
5305# contexts and be able to reproduce results from other implementations
5306# of the spec.
5307
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005308BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005309 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005310 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5311 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005312)
5313
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005314ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005315 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005316 traps=[],
5317 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005318)
5319
5320
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005321##### crud for parsing strings #############################################
Christian Heimes23daade2008-02-25 12:39:23 +00005322#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005323# Regular expression used for parsing numeric strings. Additional
5324# comments:
5325#
5326# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5327# whitespace. But note that the specification disallows whitespace in
5328# a numeric string.
5329#
5330# 2. For finite numbers (not infinities and NaNs) the body of the
5331# number between the optional sign and the optional exponent must have
5332# at least one decimal digit, possibly after the decimal point. The
5333# lookahead expression '(?=\d|\.\d)' checks this.
5334#
5335# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5336# other meaning for \d than the numbers [0-9].
5337
5338import re
5339_parser = re.compile(r""" # A numeric string consists of:
5340# \s*
5341 (?P<sign>[-+])? # an optional sign, followed by either...
5342 (
5343 (?=\d|\.\d) # ...a number (with at least one digit)
5344 (?P<int>\d*) # consisting of a (possibly empty) integer part
5345 (\.(?P<frac>\d*))? # followed by an optional fractional part
5346 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5347 |
5348 Inf(inity)? # ...an infinity, or...
5349 |
5350 (?P<signal>s)? # ...an (optionally signaling)
5351 NaN # NaN
5352 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5353 )
5354# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00005355 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005356""", re.VERBOSE | re.IGNORECASE).match
5357
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005358_all_zeros = re.compile('0*$').match
5359_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00005360
5361##### PEP3101 support functions ##############################################
5362# The functions parse_format_specifier and format_align have little to do
5363# with the Decimal class, and could potentially be reused for other pure
5364# Python numeric classes that want to implement __format__
5365#
5366# A format specifier for Decimal looks like:
5367#
5368# [[fill]align][sign][0][minimumwidth][.precision][type]
5369#
5370
5371_parse_format_specifier_regex = re.compile(r"""\A
5372(?:
5373 (?P<fill>.)?
5374 (?P<align>[<>=^])
5375)?
5376(?P<sign>[-+ ])?
5377(?P<zeropad>0)?
5378(?P<minimumwidth>(?!0)\d+)?
5379(?:\.(?P<precision>0|(?!0)\d+))?
5380(?P<type>[eEfFgG%])?
5381\Z
5382""", re.VERBOSE)
5383
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005384del re
5385
Christian Heimesf16baeb2008-02-29 14:57:44 +00005386def _parse_format_specifier(format_spec):
5387 """Parse and validate a format specifier.
5388
5389 Turns a standard numeric format specifier into a dict, with the
5390 following entries:
5391
5392 fill: fill character to pad field to minimum width
5393 align: alignment type, either '<', '>', '=' or '^'
5394 sign: either '+', '-' or ' '
5395 minimumwidth: nonnegative integer giving minimum width
5396 precision: nonnegative integer giving precision, or None
5397 type: one of the characters 'eEfFgG%', or None
5398 unicode: either True or False (always True for Python 3.x)
5399
5400 """
5401 m = _parse_format_specifier_regex.match(format_spec)
5402 if m is None:
5403 raise ValueError("Invalid format specifier: " + format_spec)
5404
5405 # get the dictionary
5406 format_dict = m.groupdict()
5407
5408 # defaults for fill and alignment
5409 fill = format_dict['fill']
5410 align = format_dict['align']
5411 if format_dict.pop('zeropad') is not None:
5412 # in the face of conflict, refuse the temptation to guess
5413 if fill is not None and fill != '0':
5414 raise ValueError("Fill character conflicts with '0'"
5415 " in format specifier: " + format_spec)
5416 if align is not None and align != '=':
5417 raise ValueError("Alignment conflicts with '0' in "
5418 "format specifier: " + format_spec)
5419 fill = '0'
5420 align = '='
5421 format_dict['fill'] = fill or ' '
5422 format_dict['align'] = align or '<'
5423
5424 if format_dict['sign'] is None:
5425 format_dict['sign'] = '-'
5426
5427 # turn minimumwidth and precision entries into integers.
5428 # minimumwidth defaults to 0; precision remains None if not given
5429 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5430 if format_dict['precision'] is not None:
5431 format_dict['precision'] = int(format_dict['precision'])
5432
5433 # if format type is 'g' or 'G' then a precision of 0 makes little
5434 # sense; convert it to 1. Same if format type is unspecified.
5435 if format_dict['precision'] == 0:
5436 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5437 format_dict['precision'] = 1
5438
5439 # record whether return type should be str or unicode
Christian Heimes295f4fa2008-02-29 15:03:39 +00005440 format_dict['unicode'] = True
Christian Heimesf16baeb2008-02-29 14:57:44 +00005441
5442 return format_dict
5443
5444def _format_align(body, spec_dict):
5445 """Given an unpadded, non-aligned numeric string, add padding and
5446 aligment to conform with the given format specifier dictionary (as
5447 output from parse_format_specifier).
5448
5449 It's assumed that if body is negative then it starts with '-'.
5450 Any leading sign ('-' or '+') is stripped from the body before
5451 applying the alignment and padding rules, and replaced in the
5452 appropriate position.
5453
5454 """
5455 # figure out the sign; we only examine the first character, so if
5456 # body has leading whitespace the results may be surprising.
5457 if len(body) > 0 and body[0] in '-+':
5458 sign = body[0]
5459 body = body[1:]
5460 else:
5461 sign = ''
5462
5463 if sign != '-':
5464 if spec_dict['sign'] in ' +':
5465 sign = spec_dict['sign']
5466 else:
5467 sign = ''
5468
5469 # how much extra space do we have to play with?
5470 minimumwidth = spec_dict['minimumwidth']
5471 fill = spec_dict['fill']
5472 padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5473
5474 align = spec_dict['align']
5475 if align == '<':
5476 result = padding + sign + body
5477 elif align == '>':
5478 result = sign + body + padding
5479 elif align == '=':
5480 result = sign + padding + body
5481 else: #align == '^'
5482 half = len(padding)//2
5483 result = padding[:half] + sign + body + padding[half:]
5484
Christian Heimesf16baeb2008-02-29 14:57:44 +00005485 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005486
Guido van Rossumd8faa362007-04-27 19:54:29 +00005487##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005488
Guido van Rossumd8faa362007-04-27 19:54:29 +00005489# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005490Inf = Decimal('Inf')
5491negInf = Decimal('-Inf')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005492NaN = Decimal('NaN')
5493Dec_0 = Decimal(0)
5494Dec_p1 = Decimal(1)
5495Dec_n1 = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005496
Guido van Rossumd8faa362007-04-27 19:54:29 +00005497# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005498Infsign = (Inf, negInf)
5499
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005500
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005501
5502if __name__ == '__main__':
5503 import doctest, sys
5504 doctest.testmod(sys.modules[__name__])