blob: 26bc8efef0e9fe2e42f9c7c2481f3fe7b6775543 [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
Raymond Hettingereb260842005-06-07 18:52:34 +0000137import copy as _copy
Raymond Hettinger771ed762009-01-03 19:20:32 +0000138import math as _math
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)
Mark Dickinsonf9236412009-01-02 23:23:21 +0000220 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000221
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):
Mark Dickinsonf9236412009-01-02 23:23:21 +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):
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000246 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000247
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):
Mark Dickinsonf9236412009-01-02 23:23:21 +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):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000268 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000269
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):
Mark Dickinsonf9236412009-01-02 23:23:21 +0000294 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000295
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):
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000344 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000345 if sign == 0:
346 if context.rounding == ROUND_CEILING:
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000347 return _SignedInfinity[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:
Mark Dickinson627cf6a2009-01-03 12:11:47 +0000352 return _SignedInfinity[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
Georg Brandlf9926402008-06-13 06:32:25 +0000386# is not available, use threading.current_thread() 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.
Georg Brandlf9926402008-06-13 06:32:25 +0000408 if hasattr(threading.current_thread(), '__decimal_context__'):
409 del threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000410
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()
Georg Brandlf9926402008-06-13 06:32:25 +0000416 threading.current_thread().__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:
Georg Brandlf9926402008-06-13 06:32:25 +0000426 return threading.current_thread().__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000427 except AttributeError:
428 context = Context()
Georg Brandlf9926402008-06-13 06:32:25 +0000429 threading.current_thread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000430 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
Raymond Hettingera0fd8882009-01-20 07:24:44 +0000503# Do not subclass Decimal from numbers.Real and do not register it as such
504# (because Decimals are not interoperable with floats). See the notes in
505# numbers.py for more detail.
506
507class Decimal(object):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000508 """Floating point class for decimal arithmetic."""
509
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000510 __slots__ = ('_exp','_int','_sign', '_is_special')
511 # Generally, the value of the Decimal instance is given by
512 # (-1)**_sign * _int * 10**_exp
513 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000514
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000515 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000516 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000517 """Create a decimal point instance.
518
519 >>> Decimal('3.14') # string input
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000520 Decimal('3.14')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000521 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000522 Decimal('3.14')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000523 >>> Decimal(314) # int
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000524 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000525 >>> Decimal(Decimal(314)) # another decimal instance
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000526 Decimal('314')
Christian Heimesa62da1d2008-01-12 19:39:10 +0000527 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000528 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000529 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000530
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000531 # Note that the coefficient, self._int, is actually stored as
532 # a string rather than as a tuple of digits. This speeds up
533 # the "digits to integer" and "integer to digits" conversions
534 # that are used in almost every arithmetic operation on
535 # Decimals. This is an internal detail: the as_tuple function
536 # and the Decimal constructor still deal with tuples of
537 # digits.
538
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000539 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000540
Christian Heimesd59c64c2007-11-30 19:27:20 +0000541 # From a string
542 # REs insist on real strings, so we can too.
543 if isinstance(value, str):
Christian Heimesa62da1d2008-01-12 19:39:10 +0000544 m = _parser(value.strip())
Christian Heimesd59c64c2007-11-30 19:27:20 +0000545 if m is None:
546 if context is None:
547 context = getcontext()
548 return context._raise_error(ConversionSyntax,
549 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000550
Christian Heimesd59c64c2007-11-30 19:27:20 +0000551 if m.group('sign') == "-":
552 self._sign = 1
553 else:
554 self._sign = 0
555 intpart = m.group('int')
556 if intpart is not None:
557 # finite number
558 fracpart = m.group('frac')
559 exp = int(m.group('exp') or '0')
560 if fracpart is not None:
561 self._int = (intpart+fracpart).lstrip('0') or '0'
562 self._exp = exp - len(fracpart)
563 else:
564 self._int = intpart.lstrip('0') or '0'
565 self._exp = exp
566 self._is_special = False
567 else:
568 diag = m.group('diag')
569 if diag is not None:
570 # NaN
571 self._int = diag.lstrip('0')
572 if m.group('signal'):
573 self._exp = 'N'
574 else:
575 self._exp = 'n'
576 else:
577 # infinity
578 self._int = '0'
579 self._exp = 'F'
580 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000581 return self
582
583 # From an integer
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000584 if isinstance(value, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000585 if value >= 0:
586 self._sign = 0
587 else:
588 self._sign = 1
589 self._exp = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000590 self._int = str(abs(value))
Christian Heimesd59c64c2007-11-30 19:27:20 +0000591 self._is_special = False
592 return self
593
594 # From another decimal
595 if isinstance(value, Decimal):
596 self._exp = value._exp
597 self._sign = value._sign
598 self._int = value._int
599 self._is_special = value._is_special
600 return self
601
602 # From an internal working value
603 if isinstance(value, _WorkRep):
604 self._sign = value.sign
605 self._int = str(value.int)
606 self._exp = int(value.exp)
607 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000608 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000609
610 # tuple/list conversion (possibly from as_tuple())
611 if isinstance(value, (list,tuple)):
612 if len(value) != 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000613 raise ValueError('Invalid tuple size in creation of Decimal '
614 'from list or tuple. The list or tuple '
615 'should have exactly three elements.')
616 # process sign. The isinstance test rejects floats
617 if not (isinstance(value[0], int) and value[0] in (0,1)):
618 raise ValueError("Invalid sign. The first value in the tuple "
619 "should be an integer; either 0 for a "
620 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000621 self._sign = value[0]
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000622 if value[2] == 'F':
623 # infinity: value[1] is ignored
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000624 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000625 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000626 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000627 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000628 # process and validate the digits in value[1]
629 digits = []
630 for digit in value[1]:
631 if isinstance(digit, int) and 0 <= digit <= 9:
632 # skip leading zeros
633 if digits or digit != 0:
634 digits.append(digit)
635 else:
636 raise ValueError("The second value in the tuple must "
637 "be composed of integers in the range "
638 "0 through 9.")
639 if value[2] in ('n', 'N'):
640 # NaN: digits form the diagnostic
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000641 self._int = ''.join(map(str, digits))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000642 self._exp = value[2]
643 self._is_special = True
644 elif isinstance(value[2], int):
645 # finite number: digits give the coefficient
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000646 self._int = ''.join(map(str, digits or [0]))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000647 self._exp = value[2]
648 self._is_special = False
649 else:
650 raise ValueError("The third value in the tuple must "
651 "be an integer, or one of the "
652 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000653 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000654
Raymond Hettingerbf440692004-07-10 14:14:37 +0000655 if isinstance(value, float):
656 raise TypeError("Cannot convert float to Decimal. " +
657 "First convert the float to a string")
658
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000659 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000660
Mark Dickinsonba298e42009-01-04 21:17:43 +0000661 # @classmethod, but @decorator is not valid Python 2.3 syntax, so
662 # don't use it (see notes on Py2.3 compatibility at top of file)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000663 def from_float(cls, f):
664 """Converts a float to a decimal number, exactly.
665
666 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
667 Since 0.1 is not exactly representable in binary floating point, the
668 value is stored as the nearest representable value which is
669 0x1.999999999999ap-4. The exact equivalent of the value in decimal
670 is 0.1000000000000000055511151231257827021181583404541015625.
671
672 >>> Decimal.from_float(0.1)
673 Decimal('0.1000000000000000055511151231257827021181583404541015625')
674 >>> Decimal.from_float(float('nan'))
675 Decimal('NaN')
676 >>> Decimal.from_float(float('inf'))
677 Decimal('Infinity')
678 >>> Decimal.from_float(-float('inf'))
679 Decimal('-Infinity')
680 >>> Decimal.from_float(-0.0)
681 Decimal('-0')
682
683 """
684 if isinstance(f, int): # handle integer inputs
685 return cls(f)
686 if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float
687 return cls(repr(f))
Mark Dickinsonba298e42009-01-04 21:17:43 +0000688 if _math.copysign(1.0, f) == 1.0:
689 sign = 0
690 else:
691 sign = 1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000692 n, d = abs(f).as_integer_ratio()
693 k = d.bit_length() - 1
694 result = _dec_from_triple(sign, str(n*5**k), -k)
Mark Dickinsonba298e42009-01-04 21:17:43 +0000695 if cls is Decimal:
696 return result
697 else:
698 return cls(result)
699 from_float = classmethod(from_float)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000700
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000701 def _isnan(self):
702 """Returns whether the number is not actually one.
703
704 0 if a number
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000705 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000706 2 if sNaN
707 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000708 if self._is_special:
709 exp = self._exp
710 if exp == 'n':
711 return 1
712 elif exp == 'N':
713 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000714 return 0
715
716 def _isinfinity(self):
717 """Returns whether the number is infinite
718
719 0 if finite or not a number
720 1 if +INF
721 -1 if -INF
722 """
723 if self._exp == 'F':
724 if self._sign:
725 return -1
726 return 1
727 return 0
728
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000729 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000730 """Returns whether the number is not actually one.
731
732 if self, other are sNaN, signal
733 if self, other are NaN return nan
734 return 0
735
736 Done before operations.
737 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000738
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000739 self_is_nan = self._isnan()
740 if other is None:
741 other_is_nan = False
742 else:
743 other_is_nan = other._isnan()
744
745 if self_is_nan or other_is_nan:
746 if context is None:
747 context = getcontext()
748
749 if self_is_nan == 2:
750 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000751 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000752 if other_is_nan == 2:
753 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000754 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000755 if self_is_nan:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000756 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000757
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000758 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000759 return 0
760
Christian Heimes77c02eb2008-02-09 02:18:51 +0000761 def _compare_check_nans(self, other, context):
762 """Version of _check_nans used for the signaling comparisons
763 compare_signal, __le__, __lt__, __ge__, __gt__.
764
765 Signal InvalidOperation if either self or other is a (quiet
766 or signaling) NaN. Signaling NaNs take precedence over quiet
767 NaNs.
768
769 Return 0 if neither operand is a NaN.
770
771 """
772 if context is None:
773 context = getcontext()
774
775 if self._is_special or other._is_special:
776 if self.is_snan():
777 return context._raise_error(InvalidOperation,
778 'comparison involving sNaN',
779 self)
780 elif other.is_snan():
781 return context._raise_error(InvalidOperation,
782 'comparison involving sNaN',
783 other)
784 elif self.is_qnan():
785 return context._raise_error(InvalidOperation,
786 'comparison involving NaN',
787 self)
788 elif other.is_qnan():
789 return context._raise_error(InvalidOperation,
790 'comparison involving NaN',
791 other)
792 return 0
793
Jack Diederich4dafcc42006-11-28 19:15:13 +0000794 def __bool__(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000795 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000796
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000797 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000798 """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000799 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000800
Christian Heimes77c02eb2008-02-09 02:18:51 +0000801 def _cmp(self, other):
802 """Compare the two non-NaN decimal instances self and other.
803
804 Returns -1 if self < other, 0 if self == other and 1
805 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000806
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000807 if self._is_special or other._is_special:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000808 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000809
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000810 # check for zeros; note that cmp(0, -0) should return 0
811 if not self:
812 if not other:
813 return 0
814 else:
815 return -((-1)**other._sign)
816 if not other:
817 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000818
Guido van Rossumd8faa362007-04-27 19:54:29 +0000819 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000820 if other._sign < self._sign:
821 return -1
822 if self._sign < other._sign:
823 return 1
824
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000825 self_adjusted = self.adjusted()
826 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000827 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000828 self_padded = self._int + '0'*(self._exp - other._exp)
829 other_padded = other._int + '0'*(other._exp - self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000830 return cmp(self_padded, other_padded) * (-1)**self._sign
831 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000832 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000833 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000834 return -((-1)**self._sign)
835
Christian Heimes77c02eb2008-02-09 02:18:51 +0000836 # Note: The Decimal standard doesn't cover rich comparisons for
837 # Decimals. In particular, the specification is silent on the
838 # subject of what should happen for a comparison involving a NaN.
839 # We take the following approach:
840 #
841 # == comparisons involving a NaN always return False
842 # != comparisons involving a NaN always return True
843 # <, >, <= and >= comparisons involving a (quiet or signaling)
844 # NaN signal InvalidOperation, and return False if the
Christian Heimes3feef612008-02-11 06:19:17 +0000845 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000846 #
847 # This behavior is designed to conform as closely as possible to
848 # that specified by IEEE 754.
849
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000850 def __eq__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000851 other = _convert_other(other)
852 if other is NotImplemented:
853 return other
854 if self.is_nan() or other.is_nan():
855 return False
856 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000857
858 def __ne__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000859 other = _convert_other(other)
860 if other is NotImplemented:
861 return other
862 if self.is_nan() or other.is_nan():
863 return True
864 return self._cmp(other) != 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000865
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000866
Christian Heimes77c02eb2008-02-09 02:18:51 +0000867 def __lt__(self, other, context=None):
868 other = _convert_other(other)
869 if other is NotImplemented:
870 return other
871 ans = self._compare_check_nans(other, context)
872 if ans:
873 return False
874 return self._cmp(other) < 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000875
Christian Heimes77c02eb2008-02-09 02:18:51 +0000876 def __le__(self, other, context=None):
877 other = _convert_other(other)
878 if other is NotImplemented:
879 return other
880 ans = self._compare_check_nans(other, context)
881 if ans:
882 return False
883 return self._cmp(other) <= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000884
Christian Heimes77c02eb2008-02-09 02:18:51 +0000885 def __gt__(self, other, context=None):
886 other = _convert_other(other)
887 if other is NotImplemented:
888 return other
889 ans = self._compare_check_nans(other, context)
890 if ans:
891 return False
892 return self._cmp(other) > 0
893
894 def __ge__(self, other, context=None):
895 other = _convert_other(other)
896 if other is NotImplemented:
897 return other
898 ans = self._compare_check_nans(other, context)
899 if ans:
900 return False
901 return self._cmp(other) >= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000902
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000903 def compare(self, other, context=None):
904 """Compares one to another.
905
906 -1 => a < b
907 0 => a = b
908 1 => a > b
909 NaN => one is NaN
910 Like __cmp__, but returns Decimal instances.
911 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000912 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000913
Guido van Rossumd8faa362007-04-27 19:54:29 +0000914 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000915 if (self._is_special or other and other._is_special):
916 ans = self._check_nans(other, context)
917 if ans:
918 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000919
Christian Heimes77c02eb2008-02-09 02:18:51 +0000920 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000921
922 def __hash__(self):
923 """x.__hash__() <==> hash(x)"""
924 # Decimal integers must hash the same as the ints
Christian Heimes2380ac72008-01-09 00:17:24 +0000925 #
926 # The hash of a nonspecial noninteger Decimal must depend only
927 # on the value of that Decimal, and not on its representation.
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000928 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000929 if self._is_special:
930 if self._isnan():
931 raise TypeError('Cannot hash a NaN value.')
932 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000933 if not self:
934 return 0
935 if self._isinteger():
936 op = _WorkRep(self.to_integral_value())
937 # to make computation feasible for Decimals with large
938 # exponent, we use the fact that hash(n) == hash(m) for
939 # any two nonzero integers n and m such that (i) n and m
940 # have the same sign, and (ii) n is congruent to m modulo
941 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
942 # hash((-1)**s*c*pow(10, e, 2**64-1).
943 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Christian Heimes2380ac72008-01-09 00:17:24 +0000944 # The value of a nonzero nonspecial Decimal instance is
945 # faithfully represented by the triple consisting of its sign,
946 # its adjusted exponent, and its coefficient with trailing
947 # zeros removed.
948 return hash((self._sign,
949 self._exp+len(self._int),
950 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000951
952 def as_tuple(self):
953 """Represents the number as a triple tuple.
954
955 To show the internals exactly as they are.
956 """
Christian Heimes25bb7832008-01-11 16:17:00 +0000957 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000958
959 def __repr__(self):
960 """Represents the number as an instance of Decimal."""
961 # Invariant: eval(repr(d)) == d
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000962 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000963
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000964 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000965 """Return string representation of the number in scientific notation.
966
967 Captures all of the information in the underlying representation.
968 """
969
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000970 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000971 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000972 if self._exp == 'F':
973 return sign + 'Infinity'
974 elif self._exp == 'n':
975 return sign + 'NaN' + self._int
976 else: # self._exp == 'N'
977 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000978
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000979 # number of digits of self._int to left of decimal point
980 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000981
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000982 # dotplace is number of digits of self._int to the left of the
983 # decimal point in the mantissa of the output string (that is,
984 # after adjusting the exponent)
985 if self._exp <= 0 and leftdigits > -6:
986 # no exponent required
987 dotplace = leftdigits
988 elif not eng:
989 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000990 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000991 elif self._int == '0':
992 # engineering notation, zero
993 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000994 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000995 # engineering notation, nonzero
996 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000997
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000998 if dotplace <= 0:
999 intpart = '0'
1000 fracpart = '.' + '0'*(-dotplace) + self._int
1001 elif dotplace >= len(self._int):
1002 intpart = self._int+'0'*(dotplace-len(self._int))
1003 fracpart = ''
1004 else:
1005 intpart = self._int[:dotplace]
1006 fracpart = '.' + self._int[dotplace:]
1007 if leftdigits == dotplace:
1008 exp = ''
1009 else:
1010 if context is None:
1011 context = getcontext()
1012 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1013
1014 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001015
1016 def to_eng_string(self, context=None):
1017 """Convert to engineering-type string.
1018
1019 Engineering notation has an exponent which is a multiple of 3, so there
1020 are up to 3 digits left of the decimal place.
1021
1022 Same rules for when in exponential and when as a value as in __str__.
1023 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001024 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001025
1026 def __neg__(self, context=None):
1027 """Returns a copy with the sign switched.
1028
1029 Rounds, if it has reason.
1030 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001031 if self._is_special:
1032 ans = self._check_nans(context=context)
1033 if ans:
1034 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001035
1036 if not self:
1037 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001038 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001039 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001040 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001041
1042 if context is None:
1043 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001044 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001045
1046 def __pos__(self, context=None):
1047 """Returns a copy, unless it is a sNaN.
1048
1049 Rounds the number (if more then precision digits)
1050 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001051 if self._is_special:
1052 ans = self._check_nans(context=context)
1053 if ans:
1054 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001056 if not self:
1057 # + (-0) = 0
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001058 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001059 else:
1060 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001061
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001062 if context is None:
1063 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001064 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001065
Christian Heimes2c181612007-12-17 20:04:13 +00001066 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001067 """Returns the absolute value of self.
1068
Christian Heimes2c181612007-12-17 20:04:13 +00001069 If the keyword argument 'round' is false, do not round. The
1070 expression self.__abs__(round=False) is equivalent to
1071 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001072 """
Christian Heimes2c181612007-12-17 20:04:13 +00001073 if not round:
1074 return self.copy_abs()
1075
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001076 if self._is_special:
1077 ans = self._check_nans(context=context)
1078 if ans:
1079 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001080
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081 if self._sign:
1082 ans = self.__neg__(context=context)
1083 else:
1084 ans = self.__pos__(context=context)
1085
1086 return ans
1087
1088 def __add__(self, other, context=None):
1089 """Returns self + other.
1090
1091 -INF + INF (or the reverse) cause InvalidOperation errors.
1092 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001093 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001094 if other is NotImplemented:
1095 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001096
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001097 if context is None:
1098 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001099
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001100 if self._is_special or other._is_special:
1101 ans = self._check_nans(other, context)
1102 if ans:
1103 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001104
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001105 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001106 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001107 if self._sign != other._sign and other._isinfinity():
1108 return context._raise_error(InvalidOperation, '-INF + INF')
1109 return Decimal(self)
1110 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001111 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001112
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001113 exp = min(self._exp, other._exp)
1114 negativezero = 0
1115 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001116 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001117 negativezero = 1
1118
1119 if not self and not other:
1120 sign = min(self._sign, other._sign)
1121 if negativezero:
1122 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001123 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001124 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001125 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001126 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001127 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001128 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001129 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001130 return ans
1131 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001132 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001133 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001134 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001135 return ans
1136
1137 op1 = _WorkRep(self)
1138 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001139 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001140
1141 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001142 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001143 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001144 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001145 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001146 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001147 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001148 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001149 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001150 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001151 if op1.sign == 1:
1152 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001153 op1.sign, op2.sign = op2.sign, op1.sign
1154 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001155 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001156 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001157 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001158 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001159 op1.sign, op2.sign = (0, 0)
1160 else:
1161 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001162 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001163
Raymond Hettinger17931de2004-10-27 06:21:46 +00001164 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001165 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001166 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001167 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001168
1169 result.exp = op1.exp
1170 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001171 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001172 return ans
1173
1174 __radd__ = __add__
1175
1176 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001177 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001178 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001179 if other is NotImplemented:
1180 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001181
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001182 if self._is_special or other._is_special:
1183 ans = self._check_nans(other, context=context)
1184 if ans:
1185 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001186
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001187 # self - other is computed as self + other.copy_negate()
1188 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001189
1190 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001191 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001192 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001193 if other is NotImplemented:
1194 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001195
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001196 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001197
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001198 def __mul__(self, other, context=None):
1199 """Return self * other.
1200
1201 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1202 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001203 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001204 if other is NotImplemented:
1205 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001206
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001207 if context is None:
1208 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001209
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001210 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001211
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001212 if self._is_special or other._is_special:
1213 ans = self._check_nans(other, context)
1214 if ans:
1215 return ans
1216
1217 if self._isinfinity():
1218 if not other:
1219 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001220 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001221
1222 if other._isinfinity():
1223 if not self:
1224 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001225 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001226
1227 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001228
1229 # Special case for multiplying by zero
1230 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001231 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001232 # Fixing in case the exponent is out of bounds
1233 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001234 return ans
1235
1236 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001237 if self._int == '1':
1238 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001239 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001240 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001241 if other._int == '1':
1242 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001243 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001244 return ans
1245
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001246 op1 = _WorkRep(self)
1247 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001248
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001249 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001250 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001251
1252 return ans
1253 __rmul__ = __mul__
1254
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001255 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001256 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001257 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001258 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001259 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001260
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001261 if context is None:
1262 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001263
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001264 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001265
1266 if self._is_special or other._is_special:
1267 ans = self._check_nans(other, context)
1268 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001269 return ans
1270
1271 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001272 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001273
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001274 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001275 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001276
1277 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001278 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001279 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001280
1281 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001282 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001283 if not self:
1284 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001285 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001286
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001287 if not self:
1288 exp = self._exp - other._exp
1289 coeff = 0
1290 else:
1291 # OK, so neither = 0, INF or NaN
1292 shift = len(other._int) - len(self._int) + context.prec + 1
1293 exp = self._exp - other._exp - shift
1294 op1 = _WorkRep(self)
1295 op2 = _WorkRep(other)
1296 if shift >= 0:
1297 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1298 else:
1299 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1300 if remainder:
1301 # result is not exact; adjust to ensure correct rounding
1302 if coeff % 5 == 0:
1303 coeff += 1
1304 else:
1305 # result is exact; get as close to ideal exponent as possible
1306 ideal_exp = self._exp - other._exp
1307 while exp < ideal_exp and coeff % 10 == 0:
1308 coeff //= 10
1309 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001310
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001311 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001312 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001313
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001314 def _divide(self, other, context):
1315 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001316
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001317 Assumes that neither self nor other is a NaN, that self is not
1318 infinite and that other is nonzero.
1319 """
1320 sign = self._sign ^ other._sign
1321 if other._isinfinity():
1322 ideal_exp = self._exp
1323 else:
1324 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001325
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001326 expdiff = self.adjusted() - other.adjusted()
1327 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001328 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001329 self._rescale(ideal_exp, context.rounding))
1330 if expdiff <= context.prec:
1331 op1 = _WorkRep(self)
1332 op2 = _WorkRep(other)
1333 if op1.exp >= op2.exp:
1334 op1.int *= 10**(op1.exp - op2.exp)
1335 else:
1336 op2.int *= 10**(op2.exp - op1.exp)
1337 q, r = divmod(op1.int, op2.int)
1338 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001339 return (_dec_from_triple(sign, str(q), 0),
1340 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001341
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001342 # Here the quotient is too large to be representable
1343 ans = context._raise_error(DivisionImpossible,
1344 'quotient too large in //, % or divmod')
1345 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001346
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001347 def __rtruediv__(self, other, context=None):
1348 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001349 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001350 if other is NotImplemented:
1351 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001352 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001353
1354 def __divmod__(self, other, context=None):
1355 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001356 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001357 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001358 other = _convert_other(other)
1359 if other is NotImplemented:
1360 return other
1361
1362 if context is None:
1363 context = getcontext()
1364
1365 ans = self._check_nans(other, context)
1366 if ans:
1367 return (ans, ans)
1368
1369 sign = self._sign ^ other._sign
1370 if self._isinfinity():
1371 if other._isinfinity():
1372 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1373 return ans, ans
1374 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001375 return (_SignedInfinity[sign],
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001376 context._raise_error(InvalidOperation, 'INF % x'))
1377
1378 if not other:
1379 if not self:
1380 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1381 return ans, ans
1382 else:
1383 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1384 context._raise_error(InvalidOperation, 'x % 0'))
1385
1386 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001387 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001388 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001389
1390 def __rdivmod__(self, other, context=None):
1391 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001392 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001393 if other is NotImplemented:
1394 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001395 return other.__divmod__(self, context=context)
1396
1397 def __mod__(self, other, context=None):
1398 """
1399 self % other
1400 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001401 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001402 if other is NotImplemented:
1403 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001404
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001405 if context is None:
1406 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001407
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001408 ans = self._check_nans(other, context)
1409 if ans:
1410 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001411
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001412 if self._isinfinity():
1413 return context._raise_error(InvalidOperation, 'INF % x')
1414 elif not other:
1415 if self:
1416 return context._raise_error(InvalidOperation, 'x % 0')
1417 else:
1418 return context._raise_error(DivisionUndefined, '0 % 0')
1419
1420 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001421 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001422 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001423
1424 def __rmod__(self, other, context=None):
1425 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001426 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001427 if other is NotImplemented:
1428 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001429 return other.__mod__(self, context=context)
1430
1431 def remainder_near(self, other, context=None):
1432 """
1433 Remainder nearest to 0- abs(remainder-near) <= other/2
1434 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001435 if context is None:
1436 context = getcontext()
1437
1438 other = _convert_other(other, raiseit=True)
1439
1440 ans = self._check_nans(other, context)
1441 if ans:
1442 return ans
1443
1444 # self == +/-infinity -> InvalidOperation
1445 if self._isinfinity():
1446 return context._raise_error(InvalidOperation,
1447 'remainder_near(infinity, x)')
1448
1449 # other == 0 -> either InvalidOperation or DivisionUndefined
1450 if not other:
1451 if self:
1452 return context._raise_error(InvalidOperation,
1453 'remainder_near(x, 0)')
1454 else:
1455 return context._raise_error(DivisionUndefined,
1456 'remainder_near(0, 0)')
1457
1458 # other = +/-infinity -> remainder = self
1459 if other._isinfinity():
1460 ans = Decimal(self)
1461 return ans._fix(context)
1462
1463 # self = 0 -> remainder = self, with ideal exponent
1464 ideal_exponent = min(self._exp, other._exp)
1465 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001466 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001467 return ans._fix(context)
1468
1469 # catch most cases of large or small quotient
1470 expdiff = self.adjusted() - other.adjusted()
1471 if expdiff >= context.prec + 1:
1472 # expdiff >= prec+1 => abs(self/other) > 10**prec
1473 return context._raise_error(DivisionImpossible)
1474 if expdiff <= -2:
1475 # expdiff <= -2 => abs(self/other) < 0.1
1476 ans = self._rescale(ideal_exponent, context.rounding)
1477 return ans._fix(context)
1478
1479 # adjust both arguments to have the same exponent, then divide
1480 op1 = _WorkRep(self)
1481 op2 = _WorkRep(other)
1482 if op1.exp >= op2.exp:
1483 op1.int *= 10**(op1.exp - op2.exp)
1484 else:
1485 op2.int *= 10**(op2.exp - op1.exp)
1486 q, r = divmod(op1.int, op2.int)
1487 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1488 # 10**ideal_exponent. Apply correction to ensure that
1489 # abs(remainder) <= abs(other)/2
1490 if 2*r + (q&1) > op2.int:
1491 r -= op2.int
1492 q += 1
1493
1494 if q >= 10**context.prec:
1495 return context._raise_error(DivisionImpossible)
1496
1497 # result has same sign as self unless r is negative
1498 sign = self._sign
1499 if r < 0:
1500 sign = 1-sign
1501 r = -r
1502
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001503 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001504 return ans._fix(context)
1505
1506 def __floordiv__(self, other, context=None):
1507 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001508 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001509 if other is NotImplemented:
1510 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001511
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001512 if context is None:
1513 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001514
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001515 ans = self._check_nans(other, context)
1516 if ans:
1517 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001518
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001519 if self._isinfinity():
1520 if other._isinfinity():
1521 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001522 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001523 return _SignedInfinity[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001524
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001525 if not other:
1526 if self:
1527 return context._raise_error(DivisionByZero, 'x // 0',
1528 self._sign ^ other._sign)
1529 else:
1530 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001531
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001532 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001533
1534 def __rfloordiv__(self, other, context=None):
1535 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001536 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001537 if other is NotImplemented:
1538 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001539 return other.__floordiv__(self, context=context)
1540
1541 def __float__(self):
1542 """Float representation."""
1543 return float(str(self))
1544
1545 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001546 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001547 if self._is_special:
1548 if self._isnan():
1549 context = getcontext()
1550 return context._raise_error(InvalidContext)
1551 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001552 raise OverflowError("Cannot convert infinity to int")
1553 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001554 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001555 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001556 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001557 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001558
Christian Heimes969fe572008-01-25 11:23:10 +00001559 __trunc__ = __int__
1560
Christian Heimes0bd4e112008-02-12 22:59:25 +00001561 def real(self):
1562 return self
Mark Dickinson315a20a2009-01-04 21:34:18 +00001563 real = property(real)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001564
Christian Heimes0bd4e112008-02-12 22:59:25 +00001565 def imag(self):
1566 return Decimal(0)
Mark Dickinson315a20a2009-01-04 21:34:18 +00001567 imag = property(imag)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001568
1569 def conjugate(self):
1570 return self
1571
1572 def __complex__(self):
1573 return complex(float(self))
1574
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001575 def _fix_nan(self, context):
1576 """Decapitate the payload of a NaN to fit the context"""
1577 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001578
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001579 # maximum length of payload is precision if _clamp=0,
1580 # precision-1 if _clamp=1.
1581 max_payload_len = context.prec - context._clamp
1582 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001583 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1584 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001585 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001586
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001587 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001588 """Round if it is necessary to keep self within prec precision.
1589
1590 Rounds and fixes the exponent. Does not raise on a sNaN.
1591
1592 Arguments:
1593 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001594 context - context used.
1595 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001596
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001597 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001598 if self._isnan():
1599 # decapitate payload if necessary
1600 return self._fix_nan(context)
1601 else:
1602 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001603 return Decimal(self)
1604
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001605 # if self is zero then exponent should be between Etiny and
1606 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1607 Etiny = context.Etiny()
1608 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001609 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001610 exp_max = [context.Emax, Etop][context._clamp]
1611 new_exp = min(max(self._exp, Etiny), exp_max)
1612 if new_exp != self._exp:
1613 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001614 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001615 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001616 return Decimal(self)
1617
1618 # exp_min is the smallest allowable exponent of the result,
1619 # equal to max(self.adjusted()-context.prec+1, Etiny)
1620 exp_min = len(self._int) + self._exp - context.prec
1621 if exp_min > Etop:
1622 # overflow: exp_min > Etop iff self.adjusted() > Emax
1623 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001624 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001625 return context._raise_error(Overflow, 'above Emax', self._sign)
1626 self_is_subnormal = exp_min < Etiny
1627 if self_is_subnormal:
1628 context._raise_error(Subnormal)
1629 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001630
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001631 # round if self has too many digits
1632 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001633 context._raise_error(Rounded)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001634 digits = len(self._int) + self._exp - exp_min
1635 if digits < 0:
1636 self = _dec_from_triple(self._sign, '1', exp_min-1)
1637 digits = 0
1638 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1639 changed = this_function(digits)
1640 coeff = self._int[:digits] or '0'
1641 if changed == 1:
1642 coeff = str(int(coeff)+1)
1643 ans = _dec_from_triple(self._sign, coeff, exp_min)
1644
1645 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001646 context._raise_error(Inexact)
1647 if self_is_subnormal:
1648 context._raise_error(Underflow)
1649 if not ans:
1650 # raise Clamped on underflow to 0
1651 context._raise_error(Clamped)
1652 elif len(ans._int) == context.prec+1:
1653 # we get here only if rescaling rounds the
1654 # cofficient up to exactly 10**context.prec
1655 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001656 ans = _dec_from_triple(ans._sign,
1657 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001658 else:
1659 # Inexact and Rounded have already been raised
1660 ans = context._raise_error(Overflow, 'above Emax',
1661 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001662 return ans
1663
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001664 # fold down if _clamp == 1 and self has too few digits
1665 if context._clamp == 1 and self._exp > Etop:
1666 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001667 self_padded = self._int + '0'*(self._exp - Etop)
1668 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001669
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001670 # here self was representable to begin with; return unchanged
1671 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001672
1673 _pick_rounding_function = {}
1674
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001675 # for each of the rounding functions below:
1676 # self is a finite, nonzero Decimal
1677 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001678 #
1679 # each function returns either -1, 0, or 1, as follows:
1680 # 1 indicates that self should be rounded up (away from zero)
1681 # 0 indicates that self should be truncated, and that all the
1682 # digits to be truncated are zeros (so the value is unchanged)
1683 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001684
1685 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001686 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001687 if _all_zeros(self._int, prec):
1688 return 0
1689 else:
1690 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001691
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001692 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001693 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001694 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001695
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001696 def _round_half_up(self, prec):
1697 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001698 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001699 return 1
1700 elif _all_zeros(self._int, prec):
1701 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001702 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001703 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001704
1705 def _round_half_down(self, prec):
1706 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001707 if _exact_half(self._int, prec):
1708 return -1
1709 else:
1710 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001711
1712 def _round_half_even(self, prec):
1713 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001714 if _exact_half(self._int, prec) and \
1715 (prec == 0 or self._int[prec-1] in '02468'):
1716 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001717 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001718 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001719
1720 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001721 """Rounds up (not away from 0 if negative.)"""
1722 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001723 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001724 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001725 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001726
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001727 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001728 """Rounds down (not towards 0 if negative)"""
1729 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001730 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001731 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001732 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001733
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001734 def _round_05up(self, prec):
1735 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001736 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001737 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001738 else:
1739 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001740
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001741 def __round__(self, n=None):
1742 """Round self to the nearest integer, or to a given precision.
1743
1744 If only one argument is supplied, round a finite Decimal
1745 instance self to the nearest integer. If self is infinite or
1746 a NaN then a Python exception is raised. If self is finite
1747 and lies exactly halfway between two integers then it is
1748 rounded to the integer with even last digit.
1749
1750 >>> round(Decimal('123.456'))
1751 123
1752 >>> round(Decimal('-456.789'))
1753 -457
1754 >>> round(Decimal('-3.0'))
1755 -3
1756 >>> round(Decimal('2.5'))
1757 2
1758 >>> round(Decimal('3.5'))
1759 4
1760 >>> round(Decimal('Inf'))
1761 Traceback (most recent call last):
1762 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001763 OverflowError: cannot round an infinity
1764 >>> round(Decimal('NaN'))
1765 Traceback (most recent call last):
1766 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001767 ValueError: cannot round a NaN
1768
1769 If a second argument n is supplied, self is rounded to n
1770 decimal places using the rounding mode for the current
1771 context.
1772
1773 For an integer n, round(self, -n) is exactly equivalent to
1774 self.quantize(Decimal('1En')).
1775
1776 >>> round(Decimal('123.456'), 0)
1777 Decimal('123')
1778 >>> round(Decimal('123.456'), 2)
1779 Decimal('123.46')
1780 >>> round(Decimal('123.456'), -2)
1781 Decimal('1E+2')
1782 >>> round(Decimal('-Infinity'), 37)
1783 Decimal('NaN')
1784 >>> round(Decimal('sNaN123'), 0)
1785 Decimal('NaN123')
1786
1787 """
1788 if n is not None:
1789 # two-argument form: use the equivalent quantize call
1790 if not isinstance(n, int):
1791 raise TypeError('Second argument to round should be integral')
1792 exp = _dec_from_triple(0, '1', -n)
1793 return self.quantize(exp)
1794
1795 # one-argument form
1796 if self._is_special:
1797 if self.is_nan():
1798 raise ValueError("cannot round a NaN")
1799 else:
1800 raise OverflowError("cannot round an infinity")
1801 return int(self._rescale(0, ROUND_HALF_EVEN))
1802
1803 def __floor__(self):
1804 """Return the floor of self, as an integer.
1805
1806 For a finite Decimal instance self, return the greatest
1807 integer n such that n <= self. If self is infinite or a NaN
1808 then a Python exception is raised.
1809
1810 """
1811 if self._is_special:
1812 if self.is_nan():
1813 raise ValueError("cannot round a NaN")
1814 else:
1815 raise OverflowError("cannot round an infinity")
1816 return int(self._rescale(0, ROUND_FLOOR))
1817
1818 def __ceil__(self):
1819 """Return the ceiling of self, as an integer.
1820
1821 For a finite Decimal instance self, return the least integer n
1822 such that n >= self. If self is infinite or a NaN then a
1823 Python exception is raised.
1824
1825 """
1826 if self._is_special:
1827 if self.is_nan():
1828 raise ValueError("cannot round a NaN")
1829 else:
1830 raise OverflowError("cannot round an infinity")
1831 return int(self._rescale(0, ROUND_CEILING))
1832
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001833 def fma(self, other, third, context=None):
1834 """Fused multiply-add.
1835
1836 Returns self*other+third with no rounding of the intermediate
1837 product self*other.
1838
1839 self and other are multiplied together, with no rounding of
1840 the result. The third operand is then added to the result,
1841 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001842 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001843
1844 other = _convert_other(other, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001845
1846 # compute product; raise InvalidOperation if either operand is
1847 # a signaling NaN or if the product is zero times infinity.
1848 if self._is_special or other._is_special:
1849 if context is None:
1850 context = getcontext()
1851 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001852 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001853 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001854 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001855 if self._exp == 'n':
1856 product = self
1857 elif other._exp == 'n':
1858 product = other
1859 elif self._exp == 'F':
1860 if not other:
1861 return context._raise_error(InvalidOperation,
1862 'INF * 0 in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001863 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001864 elif other._exp == 'F':
1865 if not self:
1866 return context._raise_error(InvalidOperation,
1867 '0 * INF in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001868 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001869 else:
1870 product = _dec_from_triple(self._sign ^ other._sign,
1871 str(int(self._int) * int(other._int)),
1872 self._exp + other._exp)
1873
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001874 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001875 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001876
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001877 def _power_modulo(self, other, modulo, context=None):
1878 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001879
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001880 # if can't convert other and modulo to Decimal, raise
1881 # TypeError; there's no point returning NotImplemented (no
1882 # equivalent of __rpow__ for three argument pow)
1883 other = _convert_other(other, raiseit=True)
1884 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001885
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001886 if context is None:
1887 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001888
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001889 # deal with NaNs: if there are any sNaNs then first one wins,
1890 # (i.e. behaviour for NaNs is identical to that of fma)
1891 self_is_nan = self._isnan()
1892 other_is_nan = other._isnan()
1893 modulo_is_nan = modulo._isnan()
1894 if self_is_nan or other_is_nan or modulo_is_nan:
1895 if self_is_nan == 2:
1896 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001897 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001898 if other_is_nan == 2:
1899 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001900 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001901 if modulo_is_nan == 2:
1902 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001903 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001904 if self_is_nan:
1905 return self._fix_nan(context)
1906 if other_is_nan:
1907 return other._fix_nan(context)
1908 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001909
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001910 # check inputs: we apply same restrictions as Python's pow()
1911 if not (self._isinteger() and
1912 other._isinteger() and
1913 modulo._isinteger()):
1914 return context._raise_error(InvalidOperation,
1915 'pow() 3rd argument not allowed '
1916 'unless all arguments are integers')
1917 if other < 0:
1918 return context._raise_error(InvalidOperation,
1919 'pow() 2nd argument cannot be '
1920 'negative when 3rd argument specified')
1921 if not modulo:
1922 return context._raise_error(InvalidOperation,
1923 'pow() 3rd argument cannot be 0')
1924
1925 # additional restriction for decimal: the modulus must be less
1926 # than 10**prec in absolute value
1927 if modulo.adjusted() >= context.prec:
1928 return context._raise_error(InvalidOperation,
1929 'insufficient precision: pow() 3rd '
1930 'argument must not have more than '
1931 'precision digits')
1932
1933 # define 0**0 == NaN, for consistency with two-argument pow
1934 # (even though it hurts!)
1935 if not other and not self:
1936 return context._raise_error(InvalidOperation,
1937 'at least one of pow() 1st argument '
1938 'and 2nd argument must be nonzero ;'
1939 '0**0 is not defined')
1940
1941 # compute sign of result
1942 if other._iseven():
1943 sign = 0
1944 else:
1945 sign = self._sign
1946
1947 # convert modulo to a Python integer, and self and other to
1948 # Decimal integers (i.e. force their exponents to be >= 0)
1949 modulo = abs(int(modulo))
1950 base = _WorkRep(self.to_integral_value())
1951 exponent = _WorkRep(other.to_integral_value())
1952
1953 # compute result using integer pow()
1954 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1955 for i in range(exponent.exp):
1956 base = pow(base, 10, modulo)
1957 base = pow(base, exponent.int, modulo)
1958
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001959 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001960
1961 def _power_exact(self, other, p):
1962 """Attempt to compute self**other exactly.
1963
1964 Given Decimals self and other and an integer p, attempt to
1965 compute an exact result for the power self**other, with p
1966 digits of precision. Return None if self**other is not
1967 exactly representable in p digits.
1968
1969 Assumes that elimination of special cases has already been
1970 performed: self and other must both be nonspecial; self must
1971 be positive and not numerically equal to 1; other must be
1972 nonzero. For efficiency, other._exp should not be too large,
1973 so that 10**abs(other._exp) is a feasible calculation."""
1974
1975 # In the comments below, we write x for the value of self and
1976 # y for the value of other. Write x = xc*10**xe and y =
1977 # yc*10**ye.
1978
1979 # The main purpose of this method is to identify the *failure*
1980 # of x**y to be exactly representable with as little effort as
1981 # possible. So we look for cheap and easy tests that
1982 # eliminate the possibility of x**y being exact. Only if all
1983 # these tests are passed do we go on to actually compute x**y.
1984
1985 # Here's the main idea. First normalize both x and y. We
1986 # express y as a rational m/n, with m and n relatively prime
1987 # and n>0. Then for x**y to be exactly representable (at
1988 # *any* precision), xc must be the nth power of a positive
1989 # integer and xe must be divisible by n. If m is negative
1990 # then additionally xc must be a power of either 2 or 5, hence
1991 # a power of 2**n or 5**n.
1992 #
1993 # There's a limit to how small |y| can be: if y=m/n as above
1994 # then:
1995 #
1996 # (1) if xc != 1 then for the result to be representable we
1997 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1998 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1999 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
2000 # representable.
2001 #
2002 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
2003 # |y| < 1/|xe| then the result is not representable.
2004 #
2005 # Note that since x is not equal to 1, at least one of (1) and
2006 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2007 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2008 #
2009 # There's also a limit to how large y can be, at least if it's
2010 # positive: the normalized result will have coefficient xc**y,
2011 # so if it's representable then xc**y < 10**p, and y <
2012 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
2013 # not exactly representable.
2014
2015 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2016 # so |y| < 1/xe and the result is not representable.
2017 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2018 # < 1/nbits(xc).
2019
2020 x = _WorkRep(self)
2021 xc, xe = x.int, x.exp
2022 while xc % 10 == 0:
2023 xc //= 10
2024 xe += 1
2025
2026 y = _WorkRep(other)
2027 yc, ye = y.int, y.exp
2028 while yc % 10 == 0:
2029 yc //= 10
2030 ye += 1
2031
2032 # case where xc == 1: result is 10**(xe*y), with xe*y
2033 # required to be an integer
2034 if xc == 1:
2035 if ye >= 0:
2036 exponent = xe*yc*10**ye
2037 else:
2038 exponent, remainder = divmod(xe*yc, 10**-ye)
2039 if remainder:
2040 return None
2041 if y.sign == 1:
2042 exponent = -exponent
2043 # if other is a nonnegative integer, use ideal exponent
2044 if other._isinteger() and other._sign == 0:
2045 ideal_exponent = self._exp*int(other)
2046 zeros = min(exponent-ideal_exponent, p-1)
2047 else:
2048 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002049 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002050
2051 # case where y is negative: xc must be either a power
2052 # of 2 or a power of 5.
2053 if y.sign == 1:
2054 last_digit = xc % 10
2055 if last_digit in (2,4,6,8):
2056 # quick test for power of 2
2057 if xc & -xc != xc:
2058 return None
2059 # now xc is a power of 2; e is its exponent
2060 e = _nbits(xc)-1
2061 # find e*y and xe*y; both must be integers
2062 if ye >= 0:
2063 y_as_int = yc*10**ye
2064 e = e*y_as_int
2065 xe = xe*y_as_int
2066 else:
2067 ten_pow = 10**-ye
2068 e, remainder = divmod(e*yc, ten_pow)
2069 if remainder:
2070 return None
2071 xe, remainder = divmod(xe*yc, ten_pow)
2072 if remainder:
2073 return None
2074
2075 if e*65 >= p*93: # 93/65 > log(10)/log(5)
2076 return None
2077 xc = 5**e
2078
2079 elif last_digit == 5:
2080 # e >= log_5(xc) if xc is a power of 5; we have
2081 # equality all the way up to xc=5**2658
2082 e = _nbits(xc)*28//65
2083 xc, remainder = divmod(5**e, xc)
2084 if remainder:
2085 return None
2086 while xc % 5 == 0:
2087 xc //= 5
2088 e -= 1
2089 if ye >= 0:
2090 y_as_integer = yc*10**ye
2091 e = e*y_as_integer
2092 xe = xe*y_as_integer
2093 else:
2094 ten_pow = 10**-ye
2095 e, remainder = divmod(e*yc, ten_pow)
2096 if remainder:
2097 return None
2098 xe, remainder = divmod(xe*yc, ten_pow)
2099 if remainder:
2100 return None
2101 if e*3 >= p*10: # 10/3 > log(10)/log(2)
2102 return None
2103 xc = 2**e
2104 else:
2105 return None
2106
2107 if xc >= 10**p:
2108 return None
2109 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002110 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002111
2112 # now y is positive; find m and n such that y = m/n
2113 if ye >= 0:
2114 m, n = yc*10**ye, 1
2115 else:
2116 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2117 return None
2118 xc_bits = _nbits(xc)
2119 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2120 return None
2121 m, n = yc, 10**(-ye)
2122 while m % 2 == n % 2 == 0:
2123 m //= 2
2124 n //= 2
2125 while m % 5 == n % 5 == 0:
2126 m //= 5
2127 n //= 5
2128
2129 # compute nth root of xc*10**xe
2130 if n > 1:
2131 # if 1 < xc < 2**n then xc isn't an nth power
2132 if xc != 1 and xc_bits <= n:
2133 return None
2134
2135 xe, rem = divmod(xe, n)
2136 if rem != 0:
2137 return None
2138
2139 # compute nth root of xc using Newton's method
2140 a = 1 << -(-_nbits(xc)//n) # initial estimate
2141 while True:
2142 q, r = divmod(xc, a**(n-1))
2143 if a <= q:
2144 break
2145 else:
2146 a = (a*(n-1) + q)//n
2147 if not (a == q and r == 0):
2148 return None
2149 xc = a
2150
2151 # now xc*10**xe is the nth root of the original xc*10**xe
2152 # compute mth power of xc*10**xe
2153
2154 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2155 # 10**p and the result is not representable.
2156 if xc > 1 and m > p*100//_log10_lb(xc):
2157 return None
2158 xc = xc**m
2159 xe *= m
2160 if xc > 10**p:
2161 return None
2162
2163 # by this point the result *is* exactly representable
2164 # adjust the exponent to get as close as possible to the ideal
2165 # exponent, if necessary
2166 str_xc = str(xc)
2167 if other._isinteger() and other._sign == 0:
2168 ideal_exponent = self._exp*int(other)
2169 zeros = min(xe-ideal_exponent, p-len(str_xc))
2170 else:
2171 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002172 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002173
2174 def __pow__(self, other, modulo=None, context=None):
2175 """Return self ** other [ % modulo].
2176
2177 With two arguments, compute self**other.
2178
2179 With three arguments, compute (self**other) % modulo. For the
2180 three argument form, the following restrictions on the
2181 arguments hold:
2182
2183 - all three arguments must be integral
2184 - other must be nonnegative
2185 - either self or other (or both) must be nonzero
2186 - modulo must be nonzero and must have at most p digits,
2187 where p is the context precision.
2188
2189 If any of these restrictions is violated the InvalidOperation
2190 flag is raised.
2191
2192 The result of pow(self, other, modulo) is identical to the
2193 result that would be obtained by computing (self**other) %
2194 modulo with unbounded precision, but is computed more
2195 efficiently. It is always exact.
2196 """
2197
2198 if modulo is not None:
2199 return self._power_modulo(other, modulo, context)
2200
2201 other = _convert_other(other)
2202 if other is NotImplemented:
2203 return other
2204
2205 if context is None:
2206 context = getcontext()
2207
2208 # either argument is a NaN => result is NaN
2209 ans = self._check_nans(other, context)
2210 if ans:
2211 return ans
2212
2213 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2214 if not other:
2215 if not self:
2216 return context._raise_error(InvalidOperation, '0 ** 0')
2217 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002218 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002219
2220 # result has sign 1 iff self._sign is 1 and other is an odd integer
2221 result_sign = 0
2222 if self._sign == 1:
2223 if other._isinteger():
2224 if not other._iseven():
2225 result_sign = 1
2226 else:
2227 # -ve**noninteger = NaN
2228 # (-0)**noninteger = 0**noninteger
2229 if self:
2230 return context._raise_error(InvalidOperation,
2231 'x ** y with x negative and y not an integer')
2232 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002233 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002234
2235 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2236 if not self:
2237 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002238 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002239 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002240 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002241
2242 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002243 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002244 if other._sign == 0:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002245 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002246 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002247 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002248
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002249 # 1**other = 1, but the choice of exponent and the flags
2250 # depend on the exponent of self, and on whether other is a
2251 # positive integer, a negative integer, or neither
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002252 if self == _One:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002253 if other._isinteger():
2254 # exp = max(self._exp*max(int(other), 0),
2255 # 1-context.prec) but evaluating int(other) directly
2256 # is dangerous until we know other is small (other
2257 # could be 1e999999999)
2258 if other._sign == 1:
2259 multiplier = 0
2260 elif other > context.prec:
2261 multiplier = context.prec
2262 else:
2263 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002264
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002265 exp = self._exp * multiplier
2266 if exp < 1-context.prec:
2267 exp = 1-context.prec
2268 context._raise_error(Rounded)
2269 else:
2270 context._raise_error(Inexact)
2271 context._raise_error(Rounded)
2272 exp = 1-context.prec
2273
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002274 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002275
2276 # compute adjusted exponent of self
2277 self_adj = self.adjusted()
2278
2279 # self ** infinity is infinity if self > 1, 0 if self < 1
2280 # self ** -infinity is infinity if self < 1, 0 if self > 1
2281 if other._isinfinity():
2282 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002283 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002284 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002285 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002286
2287 # from here on, the result always goes through the call
2288 # to _fix at the end of this function.
2289 ans = None
2290
2291 # crude test to catch cases of extreme overflow/underflow. If
2292 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2293 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2294 # self**other >= 10**(Emax+1), so overflow occurs. The test
2295 # for underflow is similar.
2296 bound = self._log10_exp_bound() + other.adjusted()
2297 if (self_adj >= 0) == (other._sign == 0):
2298 # self > 1 and other +ve, or self < 1 and other -ve
2299 # possibility of overflow
2300 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002301 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002302 else:
2303 # self > 1 and other -ve, or self < 1 and other +ve
2304 # possibility of underflow to 0
2305 Etiny = context.Etiny()
2306 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002307 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002308
2309 # try for an exact result with precision +1
2310 if ans is None:
2311 ans = self._power_exact(other, context.prec + 1)
2312 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002313 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002314
2315 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2316 if ans is None:
2317 p = context.prec
2318 x = _WorkRep(self)
2319 xc, xe = x.int, x.exp
2320 y = _WorkRep(other)
2321 yc, ye = y.int, y.exp
2322 if y.sign == 1:
2323 yc = -yc
2324
2325 # compute correctly rounded result: start with precision +3,
2326 # then increase precision until result is unambiguously roundable
2327 extra = 3
2328 while True:
2329 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2330 if coeff % (5*10**(len(str(coeff))-p-1)):
2331 break
2332 extra += 3
2333
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002334 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002335
2336 # the specification says that for non-integer other we need to
2337 # raise Inexact, even when the result is actually exact. In
2338 # the same way, we need to raise Underflow here if the result
2339 # is subnormal. (The call to _fix will take care of raising
2340 # Rounded and Subnormal, as usual.)
2341 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002342 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002343 # pad with zeros up to length context.prec+1 if necessary
2344 if len(ans._int) <= context.prec:
2345 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002346 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2347 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002348 if ans.adjusted() < context.Emin:
2349 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002350
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002351 # unlike exp, ln and log10, the power function respects the
2352 # rounding mode; no need to use ROUND_HALF_EVEN here
2353 ans = ans._fix(context)
2354 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002355
2356 def __rpow__(self, other, context=None):
2357 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002358 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002359 if other is NotImplemented:
2360 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002361 return other.__pow__(self, context=context)
2362
2363 def normalize(self, context=None):
2364 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002365
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002366 if context is None:
2367 context = getcontext()
2368
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002369 if self._is_special:
2370 ans = self._check_nans(context=context)
2371 if ans:
2372 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002373
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002374 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002375 if dup._isinfinity():
2376 return dup
2377
2378 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002379 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002380 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002381 end = len(dup._int)
2382 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002383 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002384 exp += 1
2385 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002386 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002387
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002388 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002389 """Quantize self so its exponent is the same as that of exp.
2390
2391 Similar to self._rescale(exp._exp) but with error checking.
2392 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002393 exp = _convert_other(exp, raiseit=True)
2394
2395 if context is None:
2396 context = getcontext()
2397 if rounding is None:
2398 rounding = context.rounding
2399
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002400 if self._is_special or exp._is_special:
2401 ans = self._check_nans(exp, context)
2402 if ans:
2403 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002404
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002405 if exp._isinfinity() or self._isinfinity():
2406 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002407 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002408 return context._raise_error(InvalidOperation,
2409 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002410
2411 # if we're not watching exponents, do a simple rescale
2412 if not watchexp:
2413 ans = self._rescale(exp._exp, rounding)
2414 # raise Inexact and Rounded where appropriate
2415 if ans._exp > self._exp:
2416 context._raise_error(Rounded)
2417 if ans != self:
2418 context._raise_error(Inexact)
2419 return ans
2420
2421 # exp._exp should be between Etiny and Emax
2422 if not (context.Etiny() <= exp._exp <= context.Emax):
2423 return context._raise_error(InvalidOperation,
2424 'target exponent out of bounds in quantize')
2425
2426 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002427 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002428 return ans._fix(context)
2429
2430 self_adjusted = self.adjusted()
2431 if self_adjusted > context.Emax:
2432 return context._raise_error(InvalidOperation,
2433 'exponent of quantize result too large for current context')
2434 if self_adjusted - exp._exp + 1 > context.prec:
2435 return context._raise_error(InvalidOperation,
2436 'quantize result has too many digits for current context')
2437
2438 ans = self._rescale(exp._exp, rounding)
2439 if ans.adjusted() > context.Emax:
2440 return context._raise_error(InvalidOperation,
2441 'exponent of quantize result too large for current context')
2442 if len(ans._int) > context.prec:
2443 return context._raise_error(InvalidOperation,
2444 'quantize result has too many digits for current context')
2445
2446 # raise appropriate flags
2447 if ans._exp > self._exp:
2448 context._raise_error(Rounded)
2449 if ans != self:
2450 context._raise_error(Inexact)
2451 if ans and ans.adjusted() < context.Emin:
2452 context._raise_error(Subnormal)
2453
2454 # call to fix takes care of any necessary folddown
2455 ans = ans._fix(context)
2456 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002457
2458 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002459 """Return True if self and other have the same exponent; otherwise
2460 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002461
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002462 If either operand is a special value, the following rules are used:
2463 * return True if both operands are infinities
2464 * return True if both operands are NaNs
2465 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002466 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002467 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002468 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002469 return (self.is_nan() and other.is_nan() or
2470 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002471 return self._exp == other._exp
2472
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002473 def _rescale(self, exp, rounding):
2474 """Rescale self so that the exponent is exp, either by padding with zeros
2475 or by truncating digits, using the given rounding mode.
2476
2477 Specials are returned without change. This operation is
2478 quiet: it raises no flags, and uses no information from the
2479 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002480
2481 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002482 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002483 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002484 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002485 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002486 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002487 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002488
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002489 if self._exp >= exp:
2490 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002491 return _dec_from_triple(self._sign,
2492 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002493
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002494 # too many digits; round and lose data. If self.adjusted() <
2495 # exp-1, replace self by 10**(exp-1) before rounding
2496 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002497 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002498 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002499 digits = 0
2500 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002501 changed = this_function(digits)
2502 coeff = self._int[:digits] or '0'
2503 if changed == 1:
2504 coeff = str(int(coeff)+1)
2505 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002506
Christian Heimesf16baeb2008-02-29 14:57:44 +00002507 def _round(self, places, rounding):
2508 """Round a nonzero, nonspecial Decimal to a fixed number of
2509 significant figures, using the given rounding mode.
2510
2511 Infinities, NaNs and zeros are returned unaltered.
2512
2513 This operation is quiet: it raises no flags, and uses no
2514 information from the context.
2515
2516 """
2517 if places <= 0:
2518 raise ValueError("argument should be at least 1 in _round")
2519 if self._is_special or not self:
2520 return Decimal(self)
2521 ans = self._rescale(self.adjusted()+1-places, rounding)
2522 # it can happen that the rescale alters the adjusted exponent;
2523 # for example when rounding 99.97 to 3 significant figures.
2524 # When this happens we end up with an extra 0 at the end of
2525 # the number; a second rescale fixes this.
2526 if ans.adjusted() != self.adjusted():
2527 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2528 return ans
2529
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002530 def to_integral_exact(self, rounding=None, context=None):
2531 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002532
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002533 If no rounding mode is specified, take the rounding mode from
2534 the context. This method raises the Rounded and Inexact flags
2535 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002536
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002537 See also: to_integral_value, which does exactly the same as
2538 this method except that it doesn't raise Inexact or Rounded.
2539 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002540 if self._is_special:
2541 ans = self._check_nans(context=context)
2542 if ans:
2543 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002544 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002545 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002546 return Decimal(self)
2547 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002548 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002549 if context is None:
2550 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002551 if rounding is None:
2552 rounding = context.rounding
2553 context._raise_error(Rounded)
2554 ans = self._rescale(0, rounding)
2555 if ans != self:
2556 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002557 return ans
2558
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002559 def to_integral_value(self, rounding=None, context=None):
2560 """Rounds to the nearest integer, without raising inexact, rounded."""
2561 if context is None:
2562 context = getcontext()
2563 if rounding is None:
2564 rounding = context.rounding
2565 if self._is_special:
2566 ans = self._check_nans(context=context)
2567 if ans:
2568 return ans
2569 return Decimal(self)
2570 if self._exp >= 0:
2571 return Decimal(self)
2572 else:
2573 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002574
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002575 # the method name changed, but we provide also the old one, for compatibility
2576 to_integral = to_integral_value
2577
2578 def sqrt(self, context=None):
2579 """Return the square root of self."""
Christian Heimes0348fb62008-03-26 12:55:56 +00002580 if context is None:
2581 context = getcontext()
2582
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002583 if self._is_special:
2584 ans = self._check_nans(context=context)
2585 if ans:
2586 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002587
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002588 if self._isinfinity() and self._sign == 0:
2589 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002590
2591 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002592 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002593 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002594 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002595
2596 if self._sign == 1:
2597 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2598
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002599 # At this point self represents a positive number. Let p be
2600 # the desired precision and express self in the form c*100**e
2601 # with c a positive real number and e an integer, c and e
2602 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2603 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2604 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2605 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2606 # the closest integer to sqrt(c) with the even integer chosen
2607 # in the case of a tie.
2608 #
2609 # To ensure correct rounding in all cases, we use the
2610 # following trick: we compute the square root to an extra
2611 # place (precision p+1 instead of precision p), rounding down.
2612 # Then, if the result is inexact and its last digit is 0 or 5,
2613 # we increase the last digit to 1 or 6 respectively; if it's
2614 # exact we leave the last digit alone. Now the final round to
2615 # p places (or fewer in the case of underflow) will round
2616 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002617
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002618 # use an extra digit of precision
2619 prec = context.prec+1
2620
2621 # write argument in the form c*100**e where e = self._exp//2
2622 # is the 'ideal' exponent, to be used if the square root is
2623 # exactly representable. l is the number of 'digits' of c in
2624 # base 100, so that 100**(l-1) <= c < 100**l.
2625 op = _WorkRep(self)
2626 e = op.exp >> 1
2627 if op.exp & 1:
2628 c = op.int * 10
2629 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002630 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002631 c = op.int
2632 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002633
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002634 # rescale so that c has exactly prec base 100 'digits'
2635 shift = prec-l
2636 if shift >= 0:
2637 c *= 100**shift
2638 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002639 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002640 c, remainder = divmod(c, 100**-shift)
2641 exact = not remainder
2642 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002643
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002644 # find n = floor(sqrt(c)) using Newton's method
2645 n = 10**prec
2646 while True:
2647 q = c//n
2648 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002649 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002650 else:
2651 n = n + q >> 1
2652 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002653
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002654 if exact:
2655 # result is exact; rescale to use ideal exponent e
2656 if shift >= 0:
2657 # assert n % 10**shift == 0
2658 n //= 10**shift
2659 else:
2660 n *= 10**-shift
2661 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002662 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002663 # result is not exact; fix last digit as described above
2664 if n % 5 == 0:
2665 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002666
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002667 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002668
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002669 # round, and fit to current context
2670 context = context._shallow_copy()
2671 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002672 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002673 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002674
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002675 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002676
2677 def max(self, other, context=None):
2678 """Returns the larger value.
2679
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002680 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002681 NaN (and signals if one is sNaN). Also rounds.
2682 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002683 other = _convert_other(other, raiseit=True)
2684
2685 if context is None:
2686 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002687
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002688 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002689 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002690 # number is always returned
2691 sn = self._isnan()
2692 on = other._isnan()
2693 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002694 if on == 1 and sn == 0:
2695 return self._fix(context)
2696 if sn == 1 and on == 0:
2697 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002698 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002699
Christian Heimes77c02eb2008-02-09 02:18:51 +00002700 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002701 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002702 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002703 # then an ordering is applied:
2704 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002705 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002706 # positive sign and min returns the operand with the negative sign
2707 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002708 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002709 # the result. This is exactly the ordering used in compare_total.
2710 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002711
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002712 if c == -1:
2713 ans = other
2714 else:
2715 ans = self
2716
Christian Heimes2c181612007-12-17 20:04:13 +00002717 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002718
2719 def min(self, other, context=None):
2720 """Returns the smaller value.
2721
Guido van Rossumd8faa362007-04-27 19:54:29 +00002722 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002723 NaN (and signals if one is sNaN). Also rounds.
2724 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002725 other = _convert_other(other, raiseit=True)
2726
2727 if context is None:
2728 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002729
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002730 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002731 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002732 # number is always returned
2733 sn = self._isnan()
2734 on = other._isnan()
2735 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002736 if on == 1 and sn == 0:
2737 return self._fix(context)
2738 if sn == 1 and on == 0:
2739 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002740 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002741
Christian Heimes77c02eb2008-02-09 02:18:51 +00002742 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002743 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002744 c = self.compare_total(other)
2745
2746 if c == -1:
2747 ans = self
2748 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002749 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002750
Christian Heimes2c181612007-12-17 20:04:13 +00002751 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002752
2753 def _isinteger(self):
2754 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002755 if self._is_special:
2756 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002757 if self._exp >= 0:
2758 return True
2759 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002760 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002761
2762 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002763 """Returns True if self is even. Assumes self is an integer."""
2764 if not self or self._exp > 0:
2765 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002766 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002767
2768 def adjusted(self):
2769 """Return the adjusted exponent of self"""
2770 try:
2771 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002772 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002773 except TypeError:
2774 return 0
2775
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002776 def canonical(self, context=None):
2777 """Returns the same Decimal object.
2778
2779 As we do not have different encodings for the same number, the
2780 received object already is in its canonical form.
2781 """
2782 return self
2783
2784 def compare_signal(self, other, context=None):
2785 """Compares self to the other operand numerically.
2786
2787 It's pretty much like compare(), but all NaNs signal, with signaling
2788 NaNs taking precedence over quiet NaNs.
2789 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002790 other = _convert_other(other, raiseit = True)
2791 ans = self._compare_check_nans(other, context)
2792 if ans:
2793 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002794 return self.compare(other, context=context)
2795
2796 def compare_total(self, other):
2797 """Compares self to other using the abstract representations.
2798
2799 This is not like the standard compare, which use their numerical
2800 value. Note that a total ordering is defined for all possible abstract
2801 representations.
2802 """
2803 # if one is negative and the other is positive, it's easy
2804 if self._sign and not other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002805 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002806 if not self._sign and other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002807 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002808 sign = self._sign
2809
2810 # let's handle both NaN types
2811 self_nan = self._isnan()
2812 other_nan = other._isnan()
2813 if self_nan or other_nan:
2814 if self_nan == other_nan:
2815 if self._int < other._int:
2816 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002817 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002818 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002819 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002820 if self._int > other._int:
2821 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002822 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002823 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002824 return _One
2825 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002826
2827 if sign:
2828 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002829 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002830 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002831 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002832 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002833 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002834 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002835 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002836 else:
2837 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002838 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002839 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002840 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002841 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002842 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002843 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002844 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002845
2846 if self < other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002847 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002848 if self > other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002849 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002850
2851 if self._exp < other._exp:
2852 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002853 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002854 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002855 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002856 if self._exp > other._exp:
2857 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002858 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002859 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002860 return _One
2861 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002862
2863
2864 def compare_total_mag(self, other):
2865 """Compares self to other using abstract repr., ignoring sign.
2866
2867 Like compare_total, but with operand's sign ignored and assumed to be 0.
2868 """
2869 s = self.copy_abs()
2870 o = other.copy_abs()
2871 return s.compare_total(o)
2872
2873 def copy_abs(self):
2874 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002875 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002876
2877 def copy_negate(self):
2878 """Returns a copy with the sign inverted."""
2879 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002880 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002881 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002882 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002883
2884 def copy_sign(self, other):
2885 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002886 return _dec_from_triple(other._sign, self._int,
2887 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002888
2889 def exp(self, context=None):
2890 """Returns e ** self."""
2891
2892 if context is None:
2893 context = getcontext()
2894
2895 # exp(NaN) = NaN
2896 ans = self._check_nans(context=context)
2897 if ans:
2898 return ans
2899
2900 # exp(-Infinity) = 0
2901 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002902 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002903
2904 # exp(0) = 1
2905 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002906 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002907
2908 # exp(Infinity) = Infinity
2909 if self._isinfinity() == 1:
2910 return Decimal(self)
2911
2912 # the result is now guaranteed to be inexact (the true
2913 # mathematical result is transcendental). There's no need to
2914 # raise Rounded and Inexact here---they'll always be raised as
2915 # a result of the call to _fix.
2916 p = context.prec
2917 adj = self.adjusted()
2918
2919 # we only need to do any computation for quite a small range
2920 # of adjusted exponents---for example, -29 <= adj <= 10 for
2921 # the default context. For smaller exponent the result is
2922 # indistinguishable from 1 at the given precision, while for
2923 # larger exponent the result either overflows or underflows.
2924 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2925 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002926 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002927 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2928 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002929 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002930 elif self._sign == 0 and adj < -p:
2931 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002932 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002933 elif self._sign == 1 and adj < -p-1:
2934 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002935 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002936 # general case
2937 else:
2938 op = _WorkRep(self)
2939 c, e = op.int, op.exp
2940 if op.sign == 1:
2941 c = -c
2942
2943 # compute correctly rounded result: increase precision by
2944 # 3 digits at a time until we get an unambiguously
2945 # roundable result
2946 extra = 3
2947 while True:
2948 coeff, exp = _dexp(c, e, p+extra)
2949 if coeff % (5*10**(len(str(coeff))-p-1)):
2950 break
2951 extra += 3
2952
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002953 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002954
2955 # at this stage, ans should round correctly with *any*
2956 # rounding mode, not just with ROUND_HALF_EVEN
2957 context = context._shallow_copy()
2958 rounding = context._set_rounding(ROUND_HALF_EVEN)
2959 ans = ans._fix(context)
2960 context.rounding = rounding
2961
2962 return ans
2963
2964 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002965 """Return True if self is canonical; otherwise return False.
2966
2967 Currently, the encoding of a Decimal instance is always
2968 canonical, so this method returns True for any Decimal.
2969 """
2970 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002971
2972 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002973 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002974
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002975 A Decimal instance is considered finite if it is neither
2976 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002977 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002978 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002979
2980 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002981 """Return True if self is infinite; otherwise return False."""
2982 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002983
2984 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002985 """Return True if self is a qNaN or sNaN; otherwise return False."""
2986 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002987
2988 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002989 """Return True if self is a normal number; otherwise return False."""
2990 if self._is_special or not self:
2991 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002992 if context is None:
2993 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002994 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002995
2996 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002997 """Return True if self is a quiet NaN; otherwise return False."""
2998 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002999
3000 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003001 """Return True if self is negative; otherwise return False."""
3002 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003003
3004 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003005 """Return True if self is a signaling NaN; otherwise return False."""
3006 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003007
3008 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003009 """Return True if self is subnormal; otherwise return False."""
3010 if self._is_special or not self:
3011 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003012 if context is None:
3013 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003014 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003015
3016 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003017 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003018 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003019
3020 def _ln_exp_bound(self):
3021 """Compute a lower bound for the adjusted exponent of self.ln().
3022 In other words, compute r such that self.ln() >= 10**r. Assumes
3023 that self is finite and positive and that self != 1.
3024 """
3025
3026 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
3027 adj = self._exp + len(self._int) - 1
3028 if adj >= 1:
3029 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
3030 return len(str(adj*23//10)) - 1
3031 if adj <= -2:
3032 # argument <= 0.1
3033 return len(str((-1-adj)*23//10)) - 1
3034 op = _WorkRep(self)
3035 c, e = op.int, op.exp
3036 if adj == 0:
3037 # 1 < self < 10
3038 num = str(c-10**-e)
3039 den = str(c)
3040 return len(num) - len(den) - (num < den)
3041 # adj == -1, 0.1 <= self < 1
3042 return e + len(str(10**-e - c)) - 1
3043
3044
3045 def ln(self, context=None):
3046 """Returns the natural (base e) logarithm of self."""
3047
3048 if context is None:
3049 context = getcontext()
3050
3051 # ln(NaN) = NaN
3052 ans = self._check_nans(context=context)
3053 if ans:
3054 return ans
3055
3056 # ln(0.0) == -Infinity
3057 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003058 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003059
3060 # ln(Infinity) = Infinity
3061 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003062 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003063
3064 # ln(1.0) == 0.0
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003065 if self == _One:
3066 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003067
3068 # ln(negative) raises InvalidOperation
3069 if self._sign == 1:
3070 return context._raise_error(InvalidOperation,
3071 'ln of a negative value')
3072
3073 # result is irrational, so necessarily inexact
3074 op = _WorkRep(self)
3075 c, e = op.int, op.exp
3076 p = context.prec
3077
3078 # correctly rounded result: repeatedly increase precision by 3
3079 # until we get an unambiguously roundable result
3080 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3081 while True:
3082 coeff = _dlog(c, e, places)
3083 # assert len(str(abs(coeff)))-p >= 1
3084 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3085 break
3086 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003087 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003088
3089 context = context._shallow_copy()
3090 rounding = context._set_rounding(ROUND_HALF_EVEN)
3091 ans = ans._fix(context)
3092 context.rounding = rounding
3093 return ans
3094
3095 def _log10_exp_bound(self):
3096 """Compute a lower bound for the adjusted exponent of self.log10().
3097 In other words, find r such that self.log10() >= 10**r.
3098 Assumes that self is finite and positive and that self != 1.
3099 """
3100
3101 # For x >= 10 or x < 0.1 we only need a bound on the integer
3102 # part of log10(self), and this comes directly from the
3103 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3104 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3105 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3106
3107 adj = self._exp + len(self._int) - 1
3108 if adj >= 1:
3109 # self >= 10
3110 return len(str(adj))-1
3111 if adj <= -2:
3112 # self < 0.1
3113 return len(str(-1-adj))-1
3114 op = _WorkRep(self)
3115 c, e = op.int, op.exp
3116 if adj == 0:
3117 # 1 < self < 10
3118 num = str(c-10**-e)
3119 den = str(231*c)
3120 return len(num) - len(den) - (num < den) + 2
3121 # adj == -1, 0.1 <= self < 1
3122 num = str(10**-e-c)
3123 return len(num) + e - (num < "231") - 1
3124
3125 def log10(self, context=None):
3126 """Returns the base 10 logarithm of self."""
3127
3128 if context is None:
3129 context = getcontext()
3130
3131 # log10(NaN) = NaN
3132 ans = self._check_nans(context=context)
3133 if ans:
3134 return ans
3135
3136 # log10(0.0) == -Infinity
3137 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003138 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003139
3140 # log10(Infinity) = Infinity
3141 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003142 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003143
3144 # log10(negative or -Infinity) raises InvalidOperation
3145 if self._sign == 1:
3146 return context._raise_error(InvalidOperation,
3147 'log10 of a negative value')
3148
3149 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003150 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003151 # answer may need rounding
3152 ans = Decimal(self._exp + len(self._int) - 1)
3153 else:
3154 # result is irrational, so necessarily inexact
3155 op = _WorkRep(self)
3156 c, e = op.int, op.exp
3157 p = context.prec
3158
3159 # correctly rounded result: repeatedly increase precision
3160 # until result is unambiguously roundable
3161 places = p-self._log10_exp_bound()+2
3162 while True:
3163 coeff = _dlog10(c, e, places)
3164 # assert len(str(abs(coeff)))-p >= 1
3165 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3166 break
3167 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003168 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003169
3170 context = context._shallow_copy()
3171 rounding = context._set_rounding(ROUND_HALF_EVEN)
3172 ans = ans._fix(context)
3173 context.rounding = rounding
3174 return ans
3175
3176 def logb(self, context=None):
3177 """ Returns the exponent of the magnitude of self's MSD.
3178
3179 The result is the integer which is the exponent of the magnitude
3180 of the most significant digit of self (as though it were truncated
3181 to a single digit while maintaining the value of that digit and
3182 without limiting the resulting exponent).
3183 """
3184 # logb(NaN) = NaN
3185 ans = self._check_nans(context=context)
3186 if ans:
3187 return ans
3188
3189 if context is None:
3190 context = getcontext()
3191
3192 # logb(+/-Inf) = +Inf
3193 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003194 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003195
3196 # logb(0) = -Inf, DivisionByZero
3197 if not self:
3198 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3199
3200 # otherwise, simply return the adjusted exponent of self, as a
3201 # Decimal. Note that no attempt is made to fit the result
3202 # into the current context.
3203 return Decimal(self.adjusted())
3204
3205 def _islogical(self):
3206 """Return True if self is a logical operand.
3207
Christian Heimes679db4a2008-01-18 09:56:22 +00003208 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003209 an exponent of 0, and a coefficient whose digits must all be
3210 either 0 or 1.
3211 """
3212 if self._sign != 0 or self._exp != 0:
3213 return False
3214 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003215 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003216 return False
3217 return True
3218
3219 def _fill_logical(self, context, opa, opb):
3220 dif = context.prec - len(opa)
3221 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003222 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003223 elif dif < 0:
3224 opa = opa[-context.prec:]
3225 dif = context.prec - len(opb)
3226 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003227 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003228 elif dif < 0:
3229 opb = opb[-context.prec:]
3230 return opa, opb
3231
3232 def logical_and(self, other, context=None):
3233 """Applies an 'and' operation between self and other's digits."""
3234 if context is None:
3235 context = getcontext()
3236 if not self._islogical() or not other._islogical():
3237 return context._raise_error(InvalidOperation)
3238
3239 # fill to context.prec
3240 (opa, opb) = self._fill_logical(context, self._int, other._int)
3241
3242 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003243 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3244 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003245
3246 def logical_invert(self, context=None):
3247 """Invert all its digits."""
3248 if context is None:
3249 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003250 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3251 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003252
3253 def logical_or(self, other, context=None):
3254 """Applies an 'or' operation between self and other's digits."""
3255 if context is None:
3256 context = getcontext()
3257 if not self._islogical() or not other._islogical():
3258 return context._raise_error(InvalidOperation)
3259
3260 # fill to context.prec
3261 (opa, opb) = self._fill_logical(context, self._int, other._int)
3262
3263 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003264 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003265 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003266
3267 def logical_xor(self, other, context=None):
3268 """Applies an 'xor' operation between self and other's digits."""
3269 if context is None:
3270 context = getcontext()
3271 if not self._islogical() or not other._islogical():
3272 return context._raise_error(InvalidOperation)
3273
3274 # fill to context.prec
3275 (opa, opb) = self._fill_logical(context, self._int, other._int)
3276
3277 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003278 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003279 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003280
3281 def max_mag(self, other, context=None):
3282 """Compares the values numerically with their sign ignored."""
3283 other = _convert_other(other, raiseit=True)
3284
3285 if context is None:
3286 context = getcontext()
3287
3288 if self._is_special or other._is_special:
3289 # If one operand is a quiet NaN and the other is number, then the
3290 # number is always returned
3291 sn = self._isnan()
3292 on = other._isnan()
3293 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003294 if on == 1 and sn == 0:
3295 return self._fix(context)
3296 if sn == 1 and on == 0:
3297 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003298 return self._check_nans(other, context)
3299
Christian Heimes77c02eb2008-02-09 02:18:51 +00003300 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003301 if c == 0:
3302 c = self.compare_total(other)
3303
3304 if c == -1:
3305 ans = other
3306 else:
3307 ans = self
3308
Christian Heimes2c181612007-12-17 20:04:13 +00003309 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003310
3311 def min_mag(self, other, context=None):
3312 """Compares the values numerically with their sign ignored."""
3313 other = _convert_other(other, raiseit=True)
3314
3315 if context is None:
3316 context = getcontext()
3317
3318 if self._is_special or other._is_special:
3319 # If one operand is a quiet NaN and the other is number, then the
3320 # number is always returned
3321 sn = self._isnan()
3322 on = other._isnan()
3323 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003324 if on == 1 and sn == 0:
3325 return self._fix(context)
3326 if sn == 1 and on == 0:
3327 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003328 return self._check_nans(other, context)
3329
Christian Heimes77c02eb2008-02-09 02:18:51 +00003330 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003331 if c == 0:
3332 c = self.compare_total(other)
3333
3334 if c == -1:
3335 ans = self
3336 else:
3337 ans = other
3338
Christian Heimes2c181612007-12-17 20:04:13 +00003339 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003340
3341 def next_minus(self, context=None):
3342 """Returns the largest representable number smaller than itself."""
3343 if context is None:
3344 context = getcontext()
3345
3346 ans = self._check_nans(context=context)
3347 if ans:
3348 return ans
3349
3350 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003351 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003352 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003353 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003354
3355 context = context.copy()
3356 context._set_rounding(ROUND_FLOOR)
3357 context._ignore_all_flags()
3358 new_self = self._fix(context)
3359 if new_self != self:
3360 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003361 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3362 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003363
3364 def next_plus(self, context=None):
3365 """Returns the smallest representable number larger than itself."""
3366 if context is None:
3367 context = getcontext()
3368
3369 ans = self._check_nans(context=context)
3370 if ans:
3371 return ans
3372
3373 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003374 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003375 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003376 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003377
3378 context = context.copy()
3379 context._set_rounding(ROUND_CEILING)
3380 context._ignore_all_flags()
3381 new_self = self._fix(context)
3382 if new_self != self:
3383 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003384 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3385 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003386
3387 def next_toward(self, other, context=None):
3388 """Returns the number closest to self, in the direction towards other.
3389
3390 The result is the closest representable number to self
3391 (excluding self) that is in the direction towards other,
3392 unless both have the same value. If the two operands are
3393 numerically equal, then the result is a copy of self with the
3394 sign set to be the same as the sign of other.
3395 """
3396 other = _convert_other(other, raiseit=True)
3397
3398 if context is None:
3399 context = getcontext()
3400
3401 ans = self._check_nans(other, context)
3402 if ans:
3403 return ans
3404
Christian Heimes77c02eb2008-02-09 02:18:51 +00003405 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003406 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003407 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003408
3409 if comparison == -1:
3410 ans = self.next_plus(context)
3411 else: # comparison == 1
3412 ans = self.next_minus(context)
3413
3414 # decide which flags to raise using value of ans
3415 if ans._isinfinity():
3416 context._raise_error(Overflow,
3417 'Infinite result from next_toward',
3418 ans._sign)
3419 context._raise_error(Rounded)
3420 context._raise_error(Inexact)
3421 elif ans.adjusted() < context.Emin:
3422 context._raise_error(Underflow)
3423 context._raise_error(Subnormal)
3424 context._raise_error(Rounded)
3425 context._raise_error(Inexact)
3426 # if precision == 1 then we don't raise Clamped for a
3427 # result 0E-Etiny.
3428 if not ans:
3429 context._raise_error(Clamped)
3430
3431 return ans
3432
3433 def number_class(self, context=None):
3434 """Returns an indication of the class of self.
3435
3436 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003437 sNaN
3438 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003439 -Infinity
3440 -Normal
3441 -Subnormal
3442 -Zero
3443 +Zero
3444 +Subnormal
3445 +Normal
3446 +Infinity
3447 """
3448 if self.is_snan():
3449 return "sNaN"
3450 if self.is_qnan():
3451 return "NaN"
3452 inf = self._isinfinity()
3453 if inf == 1:
3454 return "+Infinity"
3455 if inf == -1:
3456 return "-Infinity"
3457 if self.is_zero():
3458 if self._sign:
3459 return "-Zero"
3460 else:
3461 return "+Zero"
3462 if context is None:
3463 context = getcontext()
3464 if self.is_subnormal(context=context):
3465 if self._sign:
3466 return "-Subnormal"
3467 else:
3468 return "+Subnormal"
3469 # just a normal, regular, boring number, :)
3470 if self._sign:
3471 return "-Normal"
3472 else:
3473 return "+Normal"
3474
3475 def radix(self):
3476 """Just returns 10, as this is Decimal, :)"""
3477 return Decimal(10)
3478
3479 def rotate(self, other, context=None):
3480 """Returns a rotated copy of self, value-of-other times."""
3481 if context is None:
3482 context = getcontext()
3483
3484 ans = self._check_nans(other, context)
3485 if ans:
3486 return ans
3487
3488 if other._exp != 0:
3489 return context._raise_error(InvalidOperation)
3490 if not (-context.prec <= int(other) <= context.prec):
3491 return context._raise_error(InvalidOperation)
3492
3493 if self._isinfinity():
3494 return Decimal(self)
3495
3496 # get values, pad if necessary
3497 torot = int(other)
3498 rotdig = self._int
3499 topad = context.prec - len(rotdig)
3500 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003501 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003502
3503 # let's rotate!
3504 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003505 return _dec_from_triple(self._sign,
3506 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003507
3508 def scaleb (self, other, context=None):
3509 """Returns self operand after adding the second value to its exp."""
3510 if context is None:
3511 context = getcontext()
3512
3513 ans = self._check_nans(other, context)
3514 if ans:
3515 return ans
3516
3517 if other._exp != 0:
3518 return context._raise_error(InvalidOperation)
3519 liminf = -2 * (context.Emax + context.prec)
3520 limsup = 2 * (context.Emax + context.prec)
3521 if not (liminf <= int(other) <= limsup):
3522 return context._raise_error(InvalidOperation)
3523
3524 if self._isinfinity():
3525 return Decimal(self)
3526
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003527 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003528 d = d._fix(context)
3529 return d
3530
3531 def shift(self, other, context=None):
3532 """Returns a shifted copy of self, value-of-other times."""
3533 if context is None:
3534 context = getcontext()
3535
3536 ans = self._check_nans(other, context)
3537 if ans:
3538 return ans
3539
3540 if other._exp != 0:
3541 return context._raise_error(InvalidOperation)
3542 if not (-context.prec <= int(other) <= context.prec):
3543 return context._raise_error(InvalidOperation)
3544
3545 if self._isinfinity():
3546 return Decimal(self)
3547
3548 # get values, pad if necessary
3549 torot = int(other)
3550 if not torot:
3551 return Decimal(self)
3552 rotdig = self._int
3553 topad = context.prec - len(rotdig)
3554 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003555 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003556
3557 # let's shift!
3558 if torot < 0:
3559 rotated = rotdig[:torot]
3560 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003561 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003562 rotated = rotated[-context.prec:]
3563
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003564 return _dec_from_triple(self._sign,
3565 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003566
Guido van Rossumd8faa362007-04-27 19:54:29 +00003567 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003568 def __reduce__(self):
3569 return (self.__class__, (str(self),))
3570
3571 def __copy__(self):
3572 if type(self) == Decimal:
3573 return self # I'm immutable; therefore I am my own clone
3574 return self.__class__(str(self))
3575
3576 def __deepcopy__(self, memo):
3577 if type(self) == Decimal:
3578 return self # My components are also immutable
3579 return self.__class__(str(self))
3580
Christian Heimesf16baeb2008-02-29 14:57:44 +00003581 # PEP 3101 support. See also _parse_format_specifier and _format_align
3582 def __format__(self, specifier, context=None):
3583 """Format a Decimal instance according to the given specifier.
3584
3585 The specifier should be a standard format specifier, with the
3586 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3587 'F', 'g', 'G', and '%' are supported. If the formatting type
3588 is omitted it defaults to 'g' or 'G', depending on the value
3589 of context.capitals.
3590
3591 At this time the 'n' format specifier type (which is supposed
3592 to use the current locale) is not supported.
3593 """
3594
3595 # Note: PEP 3101 says that if the type is not present then
3596 # there should be at least one digit after the decimal point.
3597 # We take the liberty of ignoring this requirement for
3598 # Decimal---it's presumably there to make sure that
3599 # format(float, '') behaves similarly to str(float).
3600 if context is None:
3601 context = getcontext()
3602
3603 spec = _parse_format_specifier(specifier)
3604
3605 # special values don't care about the type or precision...
3606 if self._is_special:
3607 return _format_align(str(self), spec)
3608
3609 # a type of None defaults to 'g' or 'G', depending on context
3610 # if type is '%', adjust exponent of self accordingly
3611 if spec['type'] is None:
3612 spec['type'] = ['g', 'G'][context.capitals]
3613 elif spec['type'] == '%':
3614 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3615
3616 # round if necessary, taking rounding mode from the context
3617 rounding = context.rounding
3618 precision = spec['precision']
3619 if precision is not None:
3620 if spec['type'] in 'eE':
3621 self = self._round(precision+1, rounding)
3622 elif spec['type'] in 'gG':
3623 if len(self._int) > precision:
3624 self = self._round(precision, rounding)
3625 elif spec['type'] in 'fF%':
3626 self = self._rescale(-precision, rounding)
3627 # special case: zeros with a positive exponent can't be
3628 # represented in fixed point; rescale them to 0e0.
3629 elif not self and self._exp > 0 and spec['type'] in 'fF%':
3630 self = self._rescale(0, rounding)
3631
3632 # figure out placement of the decimal point
3633 leftdigits = self._exp + len(self._int)
3634 if spec['type'] in 'fF%':
3635 dotplace = leftdigits
3636 elif spec['type'] in 'eE':
3637 if not self and precision is not None:
3638 dotplace = 1 - precision
3639 else:
3640 dotplace = 1
3641 elif spec['type'] in 'gG':
3642 if self._exp <= 0 and leftdigits > -6:
3643 dotplace = leftdigits
3644 else:
3645 dotplace = 1
3646
3647 # figure out main part of numeric string...
3648 if dotplace <= 0:
3649 num = '0.' + '0'*(-dotplace) + self._int
3650 elif dotplace >= len(self._int):
3651 # make sure we're not padding a '0' with extra zeros on the right
3652 assert dotplace==len(self._int) or self._int != '0'
3653 num = self._int + '0'*(dotplace-len(self._int))
3654 else:
3655 num = self._int[:dotplace] + '.' + self._int[dotplace:]
3656
3657 # ...then the trailing exponent, or trailing '%'
3658 if leftdigits != dotplace or spec['type'] in 'eE':
3659 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3660 num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3661 elif spec['type'] == '%':
3662 num = num + '%'
3663
3664 # add sign
3665 if self._sign == 1:
3666 num = '-' + num
3667 return _format_align(num, spec)
3668
3669
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003670def _dec_from_triple(sign, coefficient, exponent, special=False):
3671 """Create a decimal instance directly, without any validation,
3672 normalization (e.g. removal of leading zeros) or argument
3673 conversion.
3674
3675 This function is for *internal use only*.
3676 """
3677
3678 self = object.__new__(Decimal)
3679 self._sign = sign
3680 self._int = coefficient
3681 self._exp = exponent
3682 self._is_special = special
3683
3684 return self
3685
Guido van Rossumd8faa362007-04-27 19:54:29 +00003686##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003687
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003688
3689# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003690rounding_functions = [name for name in Decimal.__dict__.keys()
3691 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003692for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003693 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003694 globalname = name[1:].upper()
3695 val = globals()[globalname]
3696 Decimal._pick_rounding_function[val] = name
3697
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003698del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003699
Thomas Wouters89f507f2006-12-13 04:49:30 +00003700class _ContextManager(object):
3701 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003702
Thomas Wouters89f507f2006-12-13 04:49:30 +00003703 Sets a copy of the supplied context in __enter__() and restores
3704 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003705 """
3706 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003707 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003708 def __enter__(self):
3709 self.saved_context = getcontext()
3710 setcontext(self.new_context)
3711 return self.new_context
3712 def __exit__(self, t, v, tb):
3713 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003714
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003715class Context(object):
3716 """Contains the context for a Decimal instance.
3717
3718 Contains:
3719 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003720 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003721 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003722 raised when it is caused. Otherwise, a value is
3723 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003724 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003725 (Whether or not the trap_enabler is set)
3726 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003727 Emin - Minimum exponent
3728 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003729 capitals - If 1, 1*10^1 is printed as 1E+1.
3730 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003731 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003732 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003733
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003734 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003735 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003736 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003737 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003738 _ignored_flags=None):
3739 if flags is None:
3740 flags = []
3741 if _ignored_flags is None:
3742 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003743 if not isinstance(flags, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003744 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003745 if traps is not None and not isinstance(traps, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003746 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003747 for name, val in locals().items():
3748 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003749 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003750 else:
3751 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003752 del self.self
3753
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003754 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003755 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003756 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003757 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3758 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3759 % vars(self))
3760 names = [f.__name__ for f, v in self.flags.items() if v]
3761 s.append('flags=[' + ', '.join(names) + ']')
3762 names = [t.__name__ for t, v in self.traps.items() if v]
3763 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003764 return ', '.join(s) + ')'
3765
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003766 def clear_flags(self):
3767 """Reset all flags to zero"""
3768 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003769 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003770
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003771 def _shallow_copy(self):
3772 """Returns a shallow copy from self."""
Christian Heimes2c181612007-12-17 20:04:13 +00003773 nc = Context(self.prec, self.rounding, self.traps,
3774 self.flags, self.Emin, self.Emax,
3775 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003776 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003777
3778 def copy(self):
3779 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003780 nc = Context(self.prec, self.rounding, self.traps.copy(),
Christian Heimes2c181612007-12-17 20:04:13 +00003781 self.flags.copy(), self.Emin, self.Emax,
3782 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003783 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003784 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003785
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003786 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003787 """Handles an error
3788
3789 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003790 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003791 trap_enabler is set, it reaises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00003792 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003793 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003794 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003795 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003796 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003797 return error().handle(self, *args)
3798
Raymond Hettinger86173da2008-02-01 20:38:12 +00003799 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003800 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003801 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003802 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003803
3804 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003805 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003806 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003807
3808 def _ignore_all_flags(self):
3809 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003810 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003811
3812 def _ignore_flags(self, *flags):
3813 """Ignore the flags, if they are raised"""
3814 # Do not mutate-- This way, copies of a context leave the original
3815 # alone.
3816 self._ignored_flags = (self._ignored_flags + list(flags))
3817 return list(flags)
3818
3819 def _regard_flags(self, *flags):
3820 """Stop ignoring the flags, if they are raised"""
3821 if flags and isinstance(flags[0], (tuple,list)):
3822 flags = flags[0]
3823 for flag in flags:
3824 self._ignored_flags.remove(flag)
3825
Nick Coghland1abd252008-07-15 15:46:38 +00003826 # We inherit object.__hash__, so we must deny this explicitly
3827 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003828
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003829 def Etiny(self):
3830 """Returns Etiny (= Emin - prec + 1)"""
3831 return int(self.Emin - self.prec + 1)
3832
3833 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003834 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003835 return int(self.Emax - self.prec + 1)
3836
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003837 def _set_rounding(self, type):
3838 """Sets the rounding type.
3839
3840 Sets the rounding type, and returns the current (previous)
3841 rounding type. Often used like:
3842
3843 context = context.copy()
3844 # so you don't change the calling context
3845 # if an error occurs in the middle.
3846 rounding = context._set_rounding(ROUND_UP)
3847 val = self.__sub__(other, context=context)
3848 context._set_rounding(rounding)
3849
3850 This will make it round up for that operation.
3851 """
3852 rounding = self.rounding
3853 self.rounding= type
3854 return rounding
3855
Raymond Hettingerfed52962004-07-14 15:41:57 +00003856 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00003857 """Creates a new Decimal instance but using self as context.
3858
3859 This method implements the to-number operation of the
3860 IBM Decimal specification."""
3861
3862 if isinstance(num, str) and num != num.strip():
3863 return self._raise_error(ConversionSyntax,
3864 "no trailing or leading whitespace is "
3865 "permitted.")
3866
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003867 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003868 if d._isnan() and len(d._int) > self.prec - self._clamp:
3869 return self._raise_error(ConversionSyntax,
3870 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003871 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003872
Raymond Hettinger771ed762009-01-03 19:20:32 +00003873 def create_decimal_from_float(self, f):
3874 """Creates a new Decimal instance from a float but rounding using self
3875 as the context.
3876
3877 >>> context = Context(prec=5, rounding=ROUND_DOWN)
3878 >>> context.create_decimal_from_float(3.1415926535897932)
3879 Decimal('3.1415')
3880 >>> context = Context(prec=5, traps=[Inexact])
3881 >>> context.create_decimal_from_float(3.1415926535897932)
3882 Traceback (most recent call last):
3883 ...
3884 decimal.Inexact: None
3885
3886 """
3887 d = Decimal.from_float(f) # An exact conversion
3888 return d._fix(self) # Apply the context rounding
3889
Guido van Rossumd8faa362007-04-27 19:54:29 +00003890 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003891 def abs(self, a):
3892 """Returns the absolute value of the operand.
3893
3894 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003895 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003896 the plus operation on the operand.
3897
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003898 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003899 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003900 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003901 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003902 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003903 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003904 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003905 Decimal('101.5')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003906 """
3907 return a.__abs__(context=self)
3908
3909 def add(self, a, b):
3910 """Return the sum of the two operands.
3911
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003912 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003913 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003914 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003915 Decimal('1.02E+4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003916 """
3917 return a.__add__(b, context=self)
3918
3919 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003920 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003921
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003922 def canonical(self, a):
3923 """Returns the same Decimal object.
3924
3925 As we do not have different encodings for the same number, the
3926 received object already is in its canonical form.
3927
3928 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003929 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003930 """
3931 return a.canonical(context=self)
3932
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003933 def compare(self, a, b):
3934 """Compares values numerically.
3935
3936 If the signs of the operands differ, a value representing each operand
3937 ('-1' if the operand is less than zero, '0' if the operand is zero or
3938 negative zero, or '1' if the operand is greater than zero) is used in
3939 place of that operand for the comparison instead of the actual
3940 operand.
3941
3942 The comparison is then effected by subtracting the second operand from
3943 the first and then returning a value according to the result of the
3944 subtraction: '-1' if the result is less than zero, '0' if the result is
3945 zero or negative zero, or '1' if the result is greater than zero.
3946
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003947 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003948 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003949 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003950 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003951 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003952 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003953 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003954 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003955 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003956 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003957 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003958 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003959 """
3960 return a.compare(b, context=self)
3961
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003962 def compare_signal(self, a, b):
3963 """Compares the values of the two operands numerically.
3964
3965 It's pretty much like compare(), but all NaNs signal, with signaling
3966 NaNs taking precedence over quiet NaNs.
3967
3968 >>> c = ExtendedContext
3969 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003970 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003971 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003972 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003973 >>> c.flags[InvalidOperation] = 0
3974 >>> print(c.flags[InvalidOperation])
3975 0
3976 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003977 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003978 >>> print(c.flags[InvalidOperation])
3979 1
3980 >>> c.flags[InvalidOperation] = 0
3981 >>> print(c.flags[InvalidOperation])
3982 0
3983 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003984 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003985 >>> print(c.flags[InvalidOperation])
3986 1
3987 """
3988 return a.compare_signal(b, context=self)
3989
3990 def compare_total(self, a, b):
3991 """Compares two operands using their abstract representation.
3992
3993 This is not like the standard compare, which use their numerical
3994 value. Note that a total ordering is defined for all possible abstract
3995 representations.
3996
3997 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003998 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003999 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004000 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004001 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004002 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004003 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004004 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004005 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004006 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004007 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004008 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004009 """
4010 return a.compare_total(b)
4011
4012 def compare_total_mag(self, a, b):
4013 """Compares two operands using their abstract representation ignoring sign.
4014
4015 Like compare_total, but with operand's sign ignored and assumed to be 0.
4016 """
4017 return a.compare_total_mag(b)
4018
4019 def copy_abs(self, a):
4020 """Returns a copy of the operand with the sign set to 0.
4021
4022 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004023 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004024 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004025 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004026 """
4027 return a.copy_abs()
4028
4029 def copy_decimal(self, a):
4030 """Returns a copy of the decimal objet.
4031
4032 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004033 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004034 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004035 Decimal('-1.00')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004036 """
4037 return Decimal(a)
4038
4039 def copy_negate(self, a):
4040 """Returns a copy of the operand with the sign inverted.
4041
4042 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004043 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004044 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004045 Decimal('101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004046 """
4047 return a.copy_negate()
4048
4049 def copy_sign(self, a, b):
4050 """Copies the second operand's sign to the first one.
4051
4052 In detail, it returns a copy of the first operand with the sign
4053 equal to the sign of the second operand.
4054
4055 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004056 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004057 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004058 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004059 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004060 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004061 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004062 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004063 """
4064 return a.copy_sign(b)
4065
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004066 def divide(self, a, b):
4067 """Decimal division in a specified context.
4068
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004069 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004070 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004071 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004072 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004073 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004074 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004075 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004076 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004077 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004078 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004079 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004080 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004081 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004082 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004083 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004084 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004085 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004086 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004087 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004088 Decimal('1.20E+6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004089 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00004090 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004091
4092 def divide_int(self, a, b):
4093 """Divides two numbers and returns the integer part of the result.
4094
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004095 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004096 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004097 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004098 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004099 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004100 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004101 """
4102 return a.__floordiv__(b, context=self)
4103
4104 def divmod(self, a, b):
4105 return a.__divmod__(b, context=self)
4106
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004107 def exp(self, a):
4108 """Returns e ** a.
4109
4110 >>> c = ExtendedContext.copy()
4111 >>> c.Emin = -999
4112 >>> c.Emax = 999
4113 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004114 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004115 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004116 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004117 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004118 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004119 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004120 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004121 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004122 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004123 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004124 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004125 """
4126 return a.exp(context=self)
4127
4128 def fma(self, a, b, c):
4129 """Returns a multiplied by b, plus c.
4130
4131 The first two operands are multiplied together, using multiply,
4132 the third operand is then added to the result of that
4133 multiplication, using add, all with only one final rounding.
4134
4135 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004136 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004137 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004138 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004139 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004140 Decimal('1.38435736E+12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004141 """
4142 return a.fma(b, c, context=self)
4143
4144 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004145 """Return True if the operand is canonical; otherwise return False.
4146
4147 Currently, the encoding of a Decimal instance is always
4148 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004149
4150 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004151 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004152 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004153 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004154
4155 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004156 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004157
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004158 A Decimal instance is considered finite if it is neither
4159 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004160
4161 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004162 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004163 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004164 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004165 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004166 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004167 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004168 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004169 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004170 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004171 """
4172 return a.is_finite()
4173
4174 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004175 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004176
4177 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004178 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004179 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004180 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004181 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004182 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004183 """
4184 return a.is_infinite()
4185
4186 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004187 """Return True if the operand is a qNaN or sNaN;
4188 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004189
4190 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004191 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004192 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004193 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004194 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004195 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004196 """
4197 return a.is_nan()
4198
4199 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004200 """Return True if the operand is a normal number;
4201 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004202
4203 >>> c = ExtendedContext.copy()
4204 >>> c.Emin = -999
4205 >>> c.Emax = 999
4206 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004207 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004208 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004209 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004210 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004211 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004212 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004213 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004214 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004215 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004216 """
4217 return a.is_normal(context=self)
4218
4219 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004220 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004221
4222 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004223 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004224 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004225 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004226 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004227 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004228 """
4229 return a.is_qnan()
4230
4231 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004232 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004233
4234 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004235 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004236 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004237 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004238 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004239 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004240 """
4241 return a.is_signed()
4242
4243 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004244 """Return True if the operand is a signaling NaN;
4245 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004246
4247 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004248 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004249 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004250 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004251 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004252 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004253 """
4254 return a.is_snan()
4255
4256 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004257 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004258
4259 >>> c = ExtendedContext.copy()
4260 >>> c.Emin = -999
4261 >>> c.Emax = 999
4262 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004263 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004264 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004265 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004266 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004267 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004268 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004269 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004270 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004271 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004272 """
4273 return a.is_subnormal(context=self)
4274
4275 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004276 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004277
4278 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004279 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004280 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004281 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004282 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004283 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004284 """
4285 return a.is_zero()
4286
4287 def ln(self, a):
4288 """Returns the natural (base e) logarithm of the operand.
4289
4290 >>> c = ExtendedContext.copy()
4291 >>> c.Emin = -999
4292 >>> c.Emax = 999
4293 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004294 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004295 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004296 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004297 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004298 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004299 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004300 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004301 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004302 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004303 """
4304 return a.ln(context=self)
4305
4306 def log10(self, a):
4307 """Returns the base 10 logarithm of the operand.
4308
4309 >>> c = ExtendedContext.copy()
4310 >>> c.Emin = -999
4311 >>> c.Emax = 999
4312 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004313 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004314 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004315 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004316 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004317 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004318 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004319 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004320 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004321 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004322 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004323 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004324 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004325 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004326 """
4327 return a.log10(context=self)
4328
4329 def logb(self, a):
4330 """ Returns the exponent of the magnitude of the operand's MSD.
4331
4332 The result is the integer which is the exponent of the magnitude
4333 of the most significant digit of the operand (as though the
4334 operand were truncated to a single digit while maintaining the
4335 value of that digit and without limiting the resulting exponent).
4336
4337 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004338 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004339 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004340 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004341 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004342 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004343 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004344 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004345 """
4346 return a.logb(context=self)
4347
4348 def logical_and(self, a, b):
4349 """Applies the logical operation 'and' between each operand's digits.
4350
4351 The operands must be both logical numbers.
4352
4353 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004354 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004355 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004356 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004357 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004358 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004359 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004360 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004361 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004362 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004363 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004364 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004365 """
4366 return a.logical_and(b, context=self)
4367
4368 def logical_invert(self, a):
4369 """Invert all the digits in the operand.
4370
4371 The operand must be a logical number.
4372
4373 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004374 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004375 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004376 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004377 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004378 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004379 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004380 Decimal('10101010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004381 """
4382 return a.logical_invert(context=self)
4383
4384 def logical_or(self, a, b):
4385 """Applies the logical operation 'or' between each operand's digits.
4386
4387 The operands must be both logical numbers.
4388
4389 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004390 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004391 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004392 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004393 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004394 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004395 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004396 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004397 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004398 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004399 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004400 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004401 """
4402 return a.logical_or(b, context=self)
4403
4404 def logical_xor(self, a, b):
4405 """Applies the logical operation 'xor' between each operand's digits.
4406
4407 The operands must be both logical numbers.
4408
4409 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004410 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004411 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004412 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004413 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004414 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004415 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004416 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004417 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004418 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004419 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004420 Decimal('1101')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004421 """
4422 return a.logical_xor(b, context=self)
4423
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004424 def max(self, a,b):
4425 """max compares two values numerically and returns the maximum.
4426
4427 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004428 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004429 operation. If they are numerically equal then the left-hand operand
4430 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004431 infinity) of the two operands is chosen as the result.
4432
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004433 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004434 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004435 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004436 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004437 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004438 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004439 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004440 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004441 """
4442 return a.max(b, context=self)
4443
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004444 def max_mag(self, a, b):
4445 """Compares the values numerically with their sign ignored."""
4446 return a.max_mag(b, context=self)
4447
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004448 def min(self, a,b):
4449 """min compares two values numerically and returns the minimum.
4450
4451 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004452 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004453 operation. If they are numerically equal then the left-hand operand
4454 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004455 infinity) of the two operands is chosen as the result.
4456
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004457 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004458 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004459 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004460 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004461 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004462 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004463 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004464 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004465 """
4466 return a.min(b, context=self)
4467
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004468 def min_mag(self, a, b):
4469 """Compares the values numerically with their sign ignored."""
4470 return a.min_mag(b, context=self)
4471
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004472 def minus(self, a):
4473 """Minus corresponds to unary prefix minus in Python.
4474
4475 The operation is evaluated using the same rules as subtract; the
4476 operation minus(a) is calculated as subtract('0', a) where the '0'
4477 has the same exponent as the operand.
4478
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004479 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004480 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004481 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004482 Decimal('1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004483 """
4484 return a.__neg__(context=self)
4485
4486 def multiply(self, a, b):
4487 """multiply multiplies two operands.
4488
4489 If either operand is a special value then the general rules apply.
4490 Otherwise, the operands are multiplied together ('long multiplication'),
4491 resulting in a number which may be as long as the sum of the lengths
4492 of the two operands.
4493
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004494 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004495 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004496 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004497 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004498 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004499 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004500 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004501 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004502 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004503 Decimal('4.28135971E+11')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004504 """
4505 return a.__mul__(b, context=self)
4506
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004507 def next_minus(self, a):
4508 """Returns the largest representable number smaller than a.
4509
4510 >>> c = ExtendedContext.copy()
4511 >>> c.Emin = -999
4512 >>> c.Emax = 999
4513 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004514 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004515 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004516 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004517 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004518 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004519 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004520 Decimal('9.99999999E+999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004521 """
4522 return a.next_minus(context=self)
4523
4524 def next_plus(self, a):
4525 """Returns the smallest representable number larger than a.
4526
4527 >>> c = ExtendedContext.copy()
4528 >>> c.Emin = -999
4529 >>> c.Emax = 999
4530 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004531 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004532 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004533 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004534 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004535 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004536 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004537 Decimal('-9.99999999E+999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004538 """
4539 return a.next_plus(context=self)
4540
4541 def next_toward(self, a, b):
4542 """Returns the number closest to a, in direction towards b.
4543
4544 The result is the closest representable number from the first
4545 operand (but not the first operand) that is in the direction
4546 towards the second operand, unless the operands have the same
4547 value.
4548
4549 >>> c = ExtendedContext.copy()
4550 >>> c.Emin = -999
4551 >>> c.Emax = 999
4552 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004553 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004554 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004555 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004556 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004557 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004558 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004559 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004560 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004561 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004562 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004563 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004564 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004565 Decimal('-0.00')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004566 """
4567 return a.next_toward(b, context=self)
4568
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004569 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004570 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004571
4572 Essentially a plus operation with all trailing zeros removed from the
4573 result.
4574
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004575 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004576 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004577 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004578 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004579 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004580 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004581 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004582 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004583 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004584 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004585 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004586 Decimal('0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004587 """
4588 return a.normalize(context=self)
4589
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004590 def number_class(self, a):
4591 """Returns an indication of the class of the operand.
4592
4593 The class is one of the following strings:
4594 -sNaN
4595 -NaN
4596 -Infinity
4597 -Normal
4598 -Subnormal
4599 -Zero
4600 +Zero
4601 +Subnormal
4602 +Normal
4603 +Infinity
4604
4605 >>> c = Context(ExtendedContext)
4606 >>> c.Emin = -999
4607 >>> c.Emax = 999
4608 >>> c.number_class(Decimal('Infinity'))
4609 '+Infinity'
4610 >>> c.number_class(Decimal('1E-10'))
4611 '+Normal'
4612 >>> c.number_class(Decimal('2.50'))
4613 '+Normal'
4614 >>> c.number_class(Decimal('0.1E-999'))
4615 '+Subnormal'
4616 >>> c.number_class(Decimal('0'))
4617 '+Zero'
4618 >>> c.number_class(Decimal('-0'))
4619 '-Zero'
4620 >>> c.number_class(Decimal('-0.1E-999'))
4621 '-Subnormal'
4622 >>> c.number_class(Decimal('-1E-10'))
4623 '-Normal'
4624 >>> c.number_class(Decimal('-2.50'))
4625 '-Normal'
4626 >>> c.number_class(Decimal('-Infinity'))
4627 '-Infinity'
4628 >>> c.number_class(Decimal('NaN'))
4629 'NaN'
4630 >>> c.number_class(Decimal('-NaN'))
4631 'NaN'
4632 >>> c.number_class(Decimal('sNaN'))
4633 'sNaN'
4634 """
4635 return a.number_class(context=self)
4636
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004637 def plus(self, a):
4638 """Plus corresponds to unary prefix plus in Python.
4639
4640 The operation is evaluated using the same rules as add; the
4641 operation plus(a) is calculated as add('0', a) where the '0'
4642 has the same exponent as the operand.
4643
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004644 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004645 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004646 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004647 Decimal('-1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004648 """
4649 return a.__pos__(context=self)
4650
4651 def power(self, a, b, modulo=None):
4652 """Raises a to the power of b, to modulo if given.
4653
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004654 With two arguments, compute a**b. If a is negative then b
4655 must be integral. The result will be inexact unless b is
4656 integral and the result is finite and can be expressed exactly
4657 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004658
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004659 With three arguments, compute (a**b) % modulo. For the
4660 three argument form, the following restrictions on the
4661 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004662
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004663 - all three arguments must be integral
4664 - b must be nonnegative
4665 - at least one of a or b must be nonzero
4666 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004667
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004668 The result of pow(a, b, modulo) is identical to the result
4669 that would be obtained by computing (a**b) % modulo with
4670 unbounded precision, but is computed more efficiently. It is
4671 always exact.
4672
4673 >>> c = ExtendedContext.copy()
4674 >>> c.Emin = -999
4675 >>> c.Emax = 999
4676 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004677 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004678 >>> c.power(Decimal('-2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004679 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004680 >>> c.power(Decimal('2'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004681 Decimal('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004682 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004683 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004684 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004685 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004686 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004687 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004688 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004689 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004690 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004691 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004692 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004693 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004694 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004695 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004696 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004697 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004698 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004699 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004700 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004701 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004702
4703 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004704 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004705 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004706 Decimal('-11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004707 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004708 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004709 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004710 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004711 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004712 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004713 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004714 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004715 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004716 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004717 """
4718 return a.__pow__(b, modulo, context=self)
4719
4720 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004721 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004722
4723 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004724 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004725 exponent is being increased), multiplied by a positive power of ten (if
4726 the exponent is being decreased), or is unchanged (if the exponent is
4727 already equal to that of the right-hand operand).
4728
4729 Unlike other operations, if the length of the coefficient after the
4730 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004731 operation condition is raised. This guarantees that, unless there is
4732 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004733 equal to that of the right-hand operand.
4734
4735 Also unlike other operations, quantize will never raise Underflow, even
4736 if the result is subnormal and inexact.
4737
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004738 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004739 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004740 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004741 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004742 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004743 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004744 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004745 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004746 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004747 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004748 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004749 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004750 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004751 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004752 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004753 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004754 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004755 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004756 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004757 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004758 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004759 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004760 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004761 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004762 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004763 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004764 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004765 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004766 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004767 Decimal('2E+2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004768 """
4769 return a.quantize(b, context=self)
4770
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004771 def radix(self):
4772 """Just returns 10, as this is Decimal, :)
4773
4774 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004775 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004776 """
4777 return Decimal(10)
4778
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004779 def remainder(self, a, b):
4780 """Returns the remainder from integer division.
4781
4782 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004783 calculating integer division as described for divide-integer, rounded
4784 to precision digits if necessary. The sign of the result, if
4785 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004786
4787 This operation will fail under the same conditions as integer division
4788 (that is, if integer division on the same two operands would fail, the
4789 remainder cannot be calculated).
4790
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004791 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004792 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004793 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004794 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004795 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004796 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004797 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004798 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004799 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004800 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004801 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004802 Decimal('1.0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004803 """
4804 return a.__mod__(b, context=self)
4805
4806 def remainder_near(self, a, b):
4807 """Returns to be "a - b * n", where n is the integer nearest the exact
4808 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004809 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004810 sign of a.
4811
4812 This operation will fail under the same conditions as integer division
4813 (that is, if integer division on the same two operands would fail, the
4814 remainder cannot be calculated).
4815
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004816 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004817 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004818 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004819 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004820 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004821 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004822 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004823 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004824 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004825 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004826 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004827 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004828 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004829 Decimal('-0.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004830 """
4831 return a.remainder_near(b, context=self)
4832
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004833 def rotate(self, a, b):
4834 """Returns a rotated copy of a, b times.
4835
4836 The coefficient of the result is a rotated copy of the digits in
4837 the coefficient of the first operand. The number of places of
4838 rotation is taken from the absolute value of the second operand,
4839 with the rotation being to the left if the second operand is
4840 positive or to the right otherwise.
4841
4842 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004843 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004844 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004845 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004846 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004847 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004848 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004849 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004850 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004851 Decimal('345678912')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004852 """
4853 return a.rotate(b, context=self)
4854
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004855 def same_quantum(self, a, b):
4856 """Returns True if the two operands have the same exponent.
4857
4858 The result is never affected by either the sign or the coefficient of
4859 either operand.
4860
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004861 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004862 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004863 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004864 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004865 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004866 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004867 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004868 True
4869 """
4870 return a.same_quantum(b)
4871
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004872 def scaleb (self, a, b):
4873 """Returns the first operand after adding the second value its exp.
4874
4875 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004876 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004877 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004878 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004879 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004880 Decimal('7.50E+3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004881 """
4882 return a.scaleb (b, context=self)
4883
4884 def shift(self, a, b):
4885 """Returns a shifted copy of a, b times.
4886
4887 The coefficient of the result is a shifted copy of the digits
4888 in the coefficient of the first operand. The number of places
4889 to shift is taken from the absolute value of the second operand,
4890 with the shift being to the left if the second operand is
4891 positive or to the right otherwise. Digits shifted into the
4892 coefficient are zeros.
4893
4894 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004895 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004896 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004897 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004898 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004899 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004900 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004901 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004902 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004903 Decimal('345678900')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004904 """
4905 return a.shift(b, context=self)
4906
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004907 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004908 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004909
4910 If the result must be inexact, it is rounded using the round-half-even
4911 algorithm.
4912
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004913 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004914 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004915 >>> ExtendedContext.sqrt(Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004916 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004917 >>> ExtendedContext.sqrt(Decimal('0.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004918 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004919 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004920 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004921 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004922 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004923 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004924 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004925 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004926 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004927 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004928 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004929 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004930 Decimal('3.16227766')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004931 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004932 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004933 """
4934 return a.sqrt(context=self)
4935
4936 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004937 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004938
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004939 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004940 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004941 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004942 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004943 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004944 Decimal('-0.77')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004945 """
4946 return a.__sub__(b, context=self)
4947
4948 def to_eng_string(self, a):
4949 """Converts a number to a string, using scientific notation.
4950
4951 The operation is not affected by the context.
4952 """
4953 return a.to_eng_string(context=self)
4954
4955 def to_sci_string(self, a):
4956 """Converts a number to a string, using scientific notation.
4957
4958 The operation is not affected by the context.
4959 """
4960 return a.__str__(context=self)
4961
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004962 def to_integral_exact(self, a):
4963 """Rounds to an integer.
4964
4965 When the operand has a negative exponent, the result is the same
4966 as using the quantize() operation using the given operand as the
4967 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4968 of the operand as the precision setting; Inexact and Rounded flags
4969 are allowed in this operation. The rounding mode is taken from the
4970 context.
4971
4972 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004973 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004974 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004975 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004976 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004977 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004978 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004979 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004980 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004981 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004982 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004983 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004984 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004985 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004986 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004987 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004988 """
4989 return a.to_integral_exact(context=self)
4990
4991 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004992 """Rounds to an integer.
4993
4994 When the operand has a negative exponent, the result is the same
4995 as using the quantize() operation using the given operand as the
4996 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4997 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00004998 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004999
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005000 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005001 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005002 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005003 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005004 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005005 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005006 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005007 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005008 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005009 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005010 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005011 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005012 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005013 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005014 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005015 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005016 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005017 return a.to_integral_value(context=self)
5018
5019 # the method name changed, but we provide also the old one, for compatibility
5020 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005021
5022class _WorkRep(object):
5023 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005024 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005025 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005026 # exp: None, int, or string
5027
5028 def __init__(self, value=None):
5029 if value is None:
5030 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005031 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005032 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005033 elif isinstance(value, Decimal):
5034 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005035 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005036 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005037 else:
5038 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005039 self.sign = value[0]
5040 self.int = value[1]
5041 self.exp = value[2]
5042
5043 def __repr__(self):
5044 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5045
5046 __str__ = __repr__
5047
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005048
5049
Christian Heimes2c181612007-12-17 20:04:13 +00005050def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005051 """Normalizes op1, op2 to have the same exp and length of coefficient.
5052
5053 Done during addition.
5054 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005055 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005056 tmp = op2
5057 other = op1
5058 else:
5059 tmp = op1
5060 other = op2
5061
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005062 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5063 # Then adding 10**exp to tmp has the same effect (after rounding)
5064 # as adding any positive quantity smaller than 10**exp; similarly
5065 # for subtraction. So if other is smaller than 10**exp we replace
5066 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00005067 tmp_len = len(str(tmp.int))
5068 other_len = len(str(other.int))
5069 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5070 if other_len + other.exp - 1 < exp:
5071 other.int = 1
5072 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005073
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005074 tmp.int *= 10 ** (tmp.exp - other.exp)
5075 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005076 return op1, op2
5077
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005078##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005079
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005080# This function from Tim Peters was taken from here:
5081# http://mail.python.org/pipermail/python-list/1999-July/007758.html
5082# The correction being in the function definition is for speed, and
5083# the whole function is not resolved with math.log because of avoiding
5084# the use of floats.
5085def _nbits(n, correction = {
5086 '0': 4, '1': 3, '2': 2, '3': 2,
5087 '4': 1, '5': 1, '6': 1, '7': 1,
5088 '8': 0, '9': 0, 'a': 0, 'b': 0,
5089 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
5090 """Number of bits in binary representation of the positive integer n,
5091 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005092 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005093 if n < 0:
5094 raise ValueError("The argument to _nbits should be nonnegative.")
5095 hex_n = "%x" % n
5096 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005097
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005098def _sqrt_nearest(n, a):
5099 """Closest integer to the square root of the positive integer n. a is
5100 an initial approximation to the square root. Any positive integer
5101 will do for a, but the closer a is to the square root of n the
5102 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005103
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005104 """
5105 if n <= 0 or a <= 0:
5106 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5107
5108 b=0
5109 while a != b:
5110 b, a = a, a--n//a>>1
5111 return a
5112
5113def _rshift_nearest(x, shift):
5114 """Given an integer x and a nonnegative integer shift, return closest
5115 integer to x / 2**shift; use round-to-even in case of a tie.
5116
5117 """
5118 b, q = 1 << shift, x >> shift
5119 return q + (2*(x & (b-1)) + (q&1) > b)
5120
5121def _div_nearest(a, b):
5122 """Closest integer to a/b, a and b positive integers; rounds to even
5123 in the case of a tie.
5124
5125 """
5126 q, r = divmod(a, b)
5127 return q + (2*r + (q&1) > b)
5128
5129def _ilog(x, M, L = 8):
5130 """Integer approximation to M*log(x/M), with absolute error boundable
5131 in terms only of x/M.
5132
5133 Given positive integers x and M, return an integer approximation to
5134 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5135 between the approximation and the exact result is at most 22. For
5136 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5137 both cases these are upper bounds on the error; it will usually be
5138 much smaller."""
5139
5140 # The basic algorithm is the following: let log1p be the function
5141 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5142 # the reduction
5143 #
5144 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5145 #
5146 # repeatedly until the argument to log1p is small (< 2**-L in
5147 # absolute value). For small y we can use the Taylor series
5148 # expansion
5149 #
5150 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5151 #
5152 # truncating at T such that y**T is small enough. The whole
5153 # computation is carried out in a form of fixed-point arithmetic,
5154 # with a real number z being represented by an integer
5155 # approximation to z*M. To avoid loss of precision, the y below
5156 # is actually an integer approximation to 2**R*y*M, where R is the
5157 # number of reductions performed so far.
5158
5159 y = x-M
5160 # argument reduction; R = number of reductions performed
5161 R = 0
5162 while (R <= L and abs(y) << L-R >= M or
5163 R > L and abs(y) >> R-L >= M):
5164 y = _div_nearest((M*y) << 1,
5165 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5166 R += 1
5167
5168 # Taylor series with T terms
5169 T = -int(-10*len(str(M))//(3*L))
5170 yshift = _rshift_nearest(y, R)
5171 w = _div_nearest(M, T)
5172 for k in range(T-1, 0, -1):
5173 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5174
5175 return _div_nearest(w*y, M)
5176
5177def _dlog10(c, e, p):
5178 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5179 approximation to 10**p * log10(c*10**e), with an absolute error of
5180 at most 1. Assumes that c*10**e is not exactly 1."""
5181
5182 # increase precision by 2; compensate for this by dividing
5183 # final result by 100
5184 p += 2
5185
5186 # write c*10**e as d*10**f with either:
5187 # f >= 0 and 1 <= d <= 10, or
5188 # f <= 0 and 0.1 <= d <= 1.
5189 # Thus for c*10**e close to 1, f = 0
5190 l = len(str(c))
5191 f = e+l - (e+l >= 1)
5192
5193 if p > 0:
5194 M = 10**p
5195 k = e+p-f
5196 if k >= 0:
5197 c *= 10**k
5198 else:
5199 c = _div_nearest(c, 10**-k)
5200
5201 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005202 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005203 log_d = _div_nearest(log_d*M, log_10)
5204 log_tenpower = f*M # exact
5205 else:
5206 log_d = 0 # error < 2.31
Neal Norwitz2f99b242008-08-24 05:48:10 +00005207 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005208
5209 return _div_nearest(log_tenpower+log_d, 100)
5210
5211def _dlog(c, e, p):
5212 """Given integers c, e and p with c > 0, compute an integer
5213 approximation to 10**p * log(c*10**e), with an absolute error of
5214 at most 1. Assumes that c*10**e is not exactly 1."""
5215
5216 # Increase precision by 2. The precision increase is compensated
5217 # for at the end with a division by 100.
5218 p += 2
5219
5220 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5221 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5222 # as 10**p * log(d) + 10**p*f * log(10).
5223 l = len(str(c))
5224 f = e+l - (e+l >= 1)
5225
5226 # compute approximation to 10**p*log(d), with error < 27
5227 if p > 0:
5228 k = e+p-f
5229 if k >= 0:
5230 c *= 10**k
5231 else:
5232 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5233
5234 # _ilog magnifies existing error in c by a factor of at most 10
5235 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5236 else:
5237 # p <= 0: just approximate the whole thing by 0; error < 2.31
5238 log_d = 0
5239
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005240 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005241 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005242 extra = len(str(abs(f)))-1
5243 if p + extra >= 0:
5244 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5245 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5246 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005247 else:
5248 f_log_ten = 0
5249 else:
5250 f_log_ten = 0
5251
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005252 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005253 return _div_nearest(f_log_ten + log_d, 100)
5254
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005255class _Log10Memoize(object):
5256 """Class to compute, store, and allow retrieval of, digits of the
5257 constant log(10) = 2.302585.... This constant is needed by
5258 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5259 def __init__(self):
5260 self.digits = "23025850929940456840179914546843642076011014886"
5261
5262 def getdigits(self, p):
5263 """Given an integer p >= 0, return floor(10**p)*log(10).
5264
5265 For example, self.getdigits(3) returns 2302.
5266 """
5267 # digits are stored as a string, for quick conversion to
5268 # integer in the case that we've already computed enough
5269 # digits; the stored digits should always be correct
5270 # (truncated, not rounded to nearest).
5271 if p < 0:
5272 raise ValueError("p should be nonnegative")
5273
5274 if p >= len(self.digits):
5275 # compute p+3, p+6, p+9, ... digits; continue until at
5276 # least one of the extra digits is nonzero
5277 extra = 3
5278 while True:
5279 # compute p+extra digits, correct to within 1ulp
5280 M = 10**(p+extra+2)
5281 digits = str(_div_nearest(_ilog(10*M, M), 100))
5282 if digits[-extra:] != '0'*extra:
5283 break
5284 extra += 3
5285 # keep all reliable digits so far; remove trailing zeros
5286 # and next nonzero digit
5287 self.digits = digits.rstrip('0')[:-1]
5288 return int(self.digits[:p+1])
5289
5290_log10_digits = _Log10Memoize().getdigits
5291
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005292def _iexp(x, M, L=8):
5293 """Given integers x and M, M > 0, such that x/M is small in absolute
5294 value, compute an integer approximation to M*exp(x/M). For 0 <=
5295 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5296 is usually much smaller)."""
5297
5298 # Algorithm: to compute exp(z) for a real number z, first divide z
5299 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5300 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5301 # series
5302 #
5303 # expm1(x) = x + x**2/2! + x**3/3! + ...
5304 #
5305 # Now use the identity
5306 #
5307 # expm1(2x) = expm1(x)*(expm1(x)+2)
5308 #
5309 # R times to compute the sequence expm1(z/2**R),
5310 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5311
5312 # Find R such that x/2**R/M <= 2**-L
5313 R = _nbits((x<<L)//M)
5314
5315 # Taylor series. (2**L)**T > M
5316 T = -int(-10*len(str(M))//(3*L))
5317 y = _div_nearest(x, T)
5318 Mshift = M<<R
5319 for i in range(T-1, 0, -1):
5320 y = _div_nearest(x*(Mshift + y), Mshift * i)
5321
5322 # Expansion
5323 for k in range(R-1, -1, -1):
5324 Mshift = M<<(k+2)
5325 y = _div_nearest(y*(y+Mshift), Mshift)
5326
5327 return M+y
5328
5329def _dexp(c, e, p):
5330 """Compute an approximation to exp(c*10**e), with p decimal places of
5331 precision.
5332
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005333 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005334
5335 10**(p-1) <= d <= 10**p, and
5336 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5337
5338 In other words, d*10**f is an approximation to exp(c*10**e) with p
5339 digits of precision, and with an error in d of at most 1. This is
5340 almost, but not quite, the same as the error being < 1ulp: when d
5341 = 10**(p-1) the error could be up to 10 ulp."""
5342
5343 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5344 p += 2
5345
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005346 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005347 extra = max(0, e + len(str(c)) - 1)
5348 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005349
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005350 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005351 # rounding down
5352 shift = e+q
5353 if shift >= 0:
5354 cshift = c*10**shift
5355 else:
5356 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005357 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005358
5359 # reduce remainder back to original precision
5360 rem = _div_nearest(rem, 10**extra)
5361
5362 # error in result of _iexp < 120; error after division < 0.62
5363 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5364
5365def _dpower(xc, xe, yc, ye, p):
5366 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5367 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5368
5369 10**(p-1) <= c <= 10**p, and
5370 (c-1)*10**e < x**y < (c+1)*10**e
5371
5372 in other words, c*10**e is an approximation to x**y with p digits
5373 of precision, and with an error in c of at most 1. (This is
5374 almost, but not quite, the same as the error being < 1ulp: when c
5375 == 10**(p-1) we can only guarantee error < 10ulp.)
5376
5377 We assume that: x is positive and not equal to 1, and y is nonzero.
5378 """
5379
5380 # Find b such that 10**(b-1) <= |y| <= 10**b
5381 b = len(str(abs(yc))) + ye
5382
5383 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5384 lxc = _dlog(xc, xe, p+b+1)
5385
5386 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5387 shift = ye-b
5388 if shift >= 0:
5389 pc = lxc*yc*10**shift
5390 else:
5391 pc = _div_nearest(lxc*yc, 10**-shift)
5392
5393 if pc == 0:
5394 # we prefer a result that isn't exactly 1; this makes it
5395 # easier to compute a correctly rounded result in __pow__
5396 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5397 coeff, exp = 10**(p-1)+1, 1-p
5398 else:
5399 coeff, exp = 10**p-1, -p
5400 else:
5401 coeff, exp = _dexp(pc, -(p+1), p+1)
5402 coeff = _div_nearest(coeff, 10)
5403 exp += 1
5404
5405 return coeff, exp
5406
5407def _log10_lb(c, correction = {
5408 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5409 '6': 23, '7': 16, '8': 10, '9': 5}):
5410 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5411 if c <= 0:
5412 raise ValueError("The argument to _log10_lb should be nonnegative.")
5413 str_c = str(c)
5414 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005415
Guido van Rossumd8faa362007-04-27 19:54:29 +00005416##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005417
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005418def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005419 """Convert other to Decimal.
5420
5421 Verifies that it's ok to use in an implicit construction.
5422 """
5423 if isinstance(other, Decimal):
5424 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005425 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005426 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005427 if raiseit:
5428 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005429 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005430
Guido van Rossumd8faa362007-04-27 19:54:29 +00005431##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005432
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005433# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005434# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005435
5436DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005437 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005438 traps=[DivisionByZero, Overflow, InvalidOperation],
5439 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005440 Emax=999999999,
5441 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005442 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005443)
5444
5445# Pre-made alternate contexts offered by the specification
5446# Don't change these; the user should be able to select these
5447# contexts and be able to reproduce results from other implementations
5448# of the spec.
5449
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005450BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005451 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005452 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5453 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005454)
5455
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005456ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005457 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005458 traps=[],
5459 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005460)
5461
5462
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005463##### crud for parsing strings #############################################
Christian Heimes23daade02008-02-25 12:39:23 +00005464#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005465# Regular expression used for parsing numeric strings. Additional
5466# comments:
5467#
5468# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5469# whitespace. But note that the specification disallows whitespace in
5470# a numeric string.
5471#
5472# 2. For finite numbers (not infinities and NaNs) the body of the
5473# number between the optional sign and the optional exponent must have
5474# at least one decimal digit, possibly after the decimal point. The
Antoine Pitroufd036452008-08-19 17:56:33 +00005475# lookahead expression '(?=[0-9]|\.[0-9])' checks this.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005476#
5477# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5478# other meaning for \d than the numbers [0-9].
5479
5480import re
Benjamin Peterson41181742008-07-02 20:22:54 +00005481_parser = re.compile(r""" # A numeric string consists of:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005482# \s*
Benjamin Peterson41181742008-07-02 20:22:54 +00005483 (?P<sign>[-+])? # an optional sign, followed by either...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005484 (
Benjamin Peterson41181742008-07-02 20:22:54 +00005485 (?=[0-9]|\.[0-9]) # ...a number (with at least one digit)
5486 (?P<int>[0-9]*) # having a (possibly empty) integer part
5487 (\.(?P<frac>[0-9]*))? # followed by an optional fractional part
5488 (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005489 |
Benjamin Peterson41181742008-07-02 20:22:54 +00005490 Inf(inity)? # ...an infinity, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005491 |
Benjamin Peterson41181742008-07-02 20:22:54 +00005492 (?P<signal>s)? # ...an (optionally signaling)
5493 NaN # NaN
5494 (?P<diag>[0-9]*) # with (possibly empty) diagnostic info.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005495 )
5496# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00005497 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005498""", re.VERBOSE | re.IGNORECASE).match
5499
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005500_all_zeros = re.compile('0*$').match
5501_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00005502
5503##### PEP3101 support functions ##############################################
5504# The functions parse_format_specifier and format_align have little to do
5505# with the Decimal class, and could potentially be reused for other pure
5506# Python numeric classes that want to implement __format__
5507#
5508# A format specifier for Decimal looks like:
5509#
5510# [[fill]align][sign][0][minimumwidth][.precision][type]
5511#
5512
5513_parse_format_specifier_regex = re.compile(r"""\A
5514(?:
5515 (?P<fill>.)?
5516 (?P<align>[<>=^])
5517)?
5518(?P<sign>[-+ ])?
5519(?P<zeropad>0)?
5520(?P<minimumwidth>(?!0)\d+)?
5521(?:\.(?P<precision>0|(?!0)\d+))?
5522(?P<type>[eEfFgG%])?
5523\Z
5524""", re.VERBOSE)
5525
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005526del re
5527
Christian Heimesf16baeb2008-02-29 14:57:44 +00005528def _parse_format_specifier(format_spec):
5529 """Parse and validate a format specifier.
5530
5531 Turns a standard numeric format specifier into a dict, with the
5532 following entries:
5533
5534 fill: fill character to pad field to minimum width
5535 align: alignment type, either '<', '>', '=' or '^'
5536 sign: either '+', '-' or ' '
5537 minimumwidth: nonnegative integer giving minimum width
5538 precision: nonnegative integer giving precision, or None
5539 type: one of the characters 'eEfFgG%', or None
5540 unicode: either True or False (always True for Python 3.x)
5541
5542 """
5543 m = _parse_format_specifier_regex.match(format_spec)
5544 if m is None:
5545 raise ValueError("Invalid format specifier: " + format_spec)
5546
5547 # get the dictionary
5548 format_dict = m.groupdict()
5549
5550 # defaults for fill and alignment
5551 fill = format_dict['fill']
5552 align = format_dict['align']
5553 if format_dict.pop('zeropad') is not None:
5554 # in the face of conflict, refuse the temptation to guess
5555 if fill is not None and fill != '0':
5556 raise ValueError("Fill character conflicts with '0'"
5557 " in format specifier: " + format_spec)
5558 if align is not None and align != '=':
5559 raise ValueError("Alignment conflicts with '0' in "
5560 "format specifier: " + format_spec)
5561 fill = '0'
5562 align = '='
5563 format_dict['fill'] = fill or ' '
5564 format_dict['align'] = align or '<'
5565
5566 if format_dict['sign'] is None:
5567 format_dict['sign'] = '-'
5568
5569 # turn minimumwidth and precision entries into integers.
5570 # minimumwidth defaults to 0; precision remains None if not given
5571 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5572 if format_dict['precision'] is not None:
5573 format_dict['precision'] = int(format_dict['precision'])
5574
5575 # if format type is 'g' or 'G' then a precision of 0 makes little
5576 # sense; convert it to 1. Same if format type is unspecified.
5577 if format_dict['precision'] == 0:
5578 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5579 format_dict['precision'] = 1
5580
5581 # record whether return type should be str or unicode
Christian Heimes295f4fa2008-02-29 15:03:39 +00005582 format_dict['unicode'] = True
Christian Heimesf16baeb2008-02-29 14:57:44 +00005583
5584 return format_dict
5585
5586def _format_align(body, spec_dict):
5587 """Given an unpadded, non-aligned numeric string, add padding and
5588 aligment to conform with the given format specifier dictionary (as
5589 output from parse_format_specifier).
5590
5591 It's assumed that if body is negative then it starts with '-'.
5592 Any leading sign ('-' or '+') is stripped from the body before
5593 applying the alignment and padding rules, and replaced in the
5594 appropriate position.
5595
5596 """
5597 # figure out the sign; we only examine the first character, so if
5598 # body has leading whitespace the results may be surprising.
5599 if len(body) > 0 and body[0] in '-+':
5600 sign = body[0]
5601 body = body[1:]
5602 else:
5603 sign = ''
5604
5605 if sign != '-':
5606 if spec_dict['sign'] in ' +':
5607 sign = spec_dict['sign']
5608 else:
5609 sign = ''
5610
5611 # how much extra space do we have to play with?
5612 minimumwidth = spec_dict['minimumwidth']
5613 fill = spec_dict['fill']
5614 padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5615
5616 align = spec_dict['align']
5617 if align == '<':
5618 result = padding + sign + body
5619 elif align == '>':
5620 result = sign + body + padding
5621 elif align == '=':
5622 result = sign + padding + body
5623 else: #align == '^'
5624 half = len(padding)//2
5625 result = padding[:half] + sign + body + padding[half:]
5626
Christian Heimesf16baeb2008-02-29 14:57:44 +00005627 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005628
Guido van Rossumd8faa362007-04-27 19:54:29 +00005629##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005630
Guido van Rossumd8faa362007-04-27 19:54:29 +00005631# Reusable defaults
Mark Dickinson627cf6a2009-01-03 12:11:47 +00005632_Infinity = Decimal('Inf')
5633_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonf9236412009-01-02 23:23:21 +00005634_NaN = Decimal('NaN')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00005635_Zero = Decimal(0)
5636_One = Decimal(1)
5637_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005638
Mark Dickinson627cf6a2009-01-03 12:11:47 +00005639# _SignedInfinity[sign] is infinity w/ that sign
5640_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005641
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005642
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005643
5644if __name__ == '__main__':
5645 import doctest, sys
5646 doctest.testmod(sys.modules[__name__])