blob: 4f9be21ccb311e55abce598962d97ae8d0478bf6 [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:
Mark Dickinsone6aad752009-01-25 10:48:51 +0000808 self_inf = self._isinfinity()
809 other_inf = other._isinfinity()
810 if self_inf == other_inf:
811 return 0
812 elif self_inf < other_inf:
813 return -1
814 else:
815 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000816
Mark Dickinsone6aad752009-01-25 10:48:51 +0000817 # check for zeros; Decimal('0') == Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000818 if not self:
819 if not other:
820 return 0
821 else:
822 return -((-1)**other._sign)
823 if not other:
824 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000825
Guido van Rossumd8faa362007-04-27 19:54:29 +0000826 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000827 if other._sign < self._sign:
828 return -1
829 if self._sign < other._sign:
830 return 1
831
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000832 self_adjusted = self.adjusted()
833 other_adjusted = other.adjusted()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000834 if self_adjusted == other_adjusted:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000835 self_padded = self._int + '0'*(self._exp - other._exp)
836 other_padded = other._int + '0'*(other._exp - self._exp)
Mark Dickinsone6aad752009-01-25 10:48:51 +0000837 if self_padded == other_padded:
838 return 0
839 elif self_padded < other_padded:
840 return -(-1)**self._sign
841 else:
842 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000843 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000844 return (-1)**self._sign
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000845 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000846 return -((-1)**self._sign)
847
Christian Heimes77c02eb2008-02-09 02:18:51 +0000848 # Note: The Decimal standard doesn't cover rich comparisons for
849 # Decimals. In particular, the specification is silent on the
850 # subject of what should happen for a comparison involving a NaN.
851 # We take the following approach:
852 #
853 # == comparisons involving a NaN always return False
854 # != comparisons involving a NaN always return True
855 # <, >, <= and >= comparisons involving a (quiet or signaling)
856 # NaN signal InvalidOperation, and return False if the
Christian Heimes3feef612008-02-11 06:19:17 +0000857 # InvalidOperation is not trapped.
Christian Heimes77c02eb2008-02-09 02:18:51 +0000858 #
859 # This behavior is designed to conform as closely as possible to
860 # that specified by IEEE 754.
861
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000862 def __eq__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000863 other = _convert_other(other)
864 if other is NotImplemented:
865 return other
866 if self.is_nan() or other.is_nan():
867 return False
868 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000869
870 def __ne__(self, other):
Christian Heimes77c02eb2008-02-09 02:18:51 +0000871 other = _convert_other(other)
872 if other is NotImplemented:
873 return other
874 if self.is_nan() or other.is_nan():
875 return True
876 return self._cmp(other) != 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000877
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000878
Christian Heimes77c02eb2008-02-09 02:18:51 +0000879 def __lt__(self, other, context=None):
880 other = _convert_other(other)
881 if other is NotImplemented:
882 return other
883 ans = self._compare_check_nans(other, context)
884 if ans:
885 return False
886 return self._cmp(other) < 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000887
Christian Heimes77c02eb2008-02-09 02:18:51 +0000888 def __le__(self, other, context=None):
889 other = _convert_other(other)
890 if other is NotImplemented:
891 return other
892 ans = self._compare_check_nans(other, context)
893 if ans:
894 return False
895 return self._cmp(other) <= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000896
Christian Heimes77c02eb2008-02-09 02:18:51 +0000897 def __gt__(self, other, context=None):
898 other = _convert_other(other)
899 if other is NotImplemented:
900 return other
901 ans = self._compare_check_nans(other, context)
902 if ans:
903 return False
904 return self._cmp(other) > 0
905
906 def __ge__(self, other, context=None):
907 other = _convert_other(other)
908 if other is NotImplemented:
909 return other
910 ans = self._compare_check_nans(other, context)
911 if ans:
912 return False
913 return self._cmp(other) >= 0
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000914
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000915 def compare(self, other, context=None):
916 """Compares one to another.
917
918 -1 => a < b
919 0 => a = b
920 1 => a > b
921 NaN => one is NaN
922 Like __cmp__, but returns Decimal instances.
923 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000924 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000925
Guido van Rossumd8faa362007-04-27 19:54:29 +0000926 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000927 if (self._is_special or other and other._is_special):
928 ans = self._check_nans(other, context)
929 if ans:
930 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000931
Christian Heimes77c02eb2008-02-09 02:18:51 +0000932 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000933
934 def __hash__(self):
935 """x.__hash__() <==> hash(x)"""
936 # Decimal integers must hash the same as the ints
Christian Heimes2380ac72008-01-09 00:17:24 +0000937 #
938 # The hash of a nonspecial noninteger Decimal must depend only
939 # on the value of that Decimal, and not on its representation.
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000940 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000941 if self._is_special:
942 if self._isnan():
943 raise TypeError('Cannot hash a NaN value.')
944 return hash(str(self))
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000945 if not self:
946 return 0
947 if self._isinteger():
948 op = _WorkRep(self.to_integral_value())
949 # to make computation feasible for Decimals with large
950 # exponent, we use the fact that hash(n) == hash(m) for
951 # any two nonzero integers n and m such that (i) n and m
952 # have the same sign, and (ii) n is congruent to m modulo
953 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
954 # hash((-1)**s*c*pow(10, e, 2**64-1).
955 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Christian Heimes2380ac72008-01-09 00:17:24 +0000956 # The value of a nonzero nonspecial Decimal instance is
957 # faithfully represented by the triple consisting of its sign,
958 # its adjusted exponent, and its coefficient with trailing
959 # zeros removed.
960 return hash((self._sign,
961 self._exp+len(self._int),
962 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000963
964 def as_tuple(self):
965 """Represents the number as a triple tuple.
966
967 To show the internals exactly as they are.
968 """
Christian Heimes25bb7832008-01-11 16:17:00 +0000969 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000970
971 def __repr__(self):
972 """Represents the number as an instance of Decimal."""
973 # Invariant: eval(repr(d)) == d
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000974 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000975
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000976 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000977 """Return string representation of the number in scientific notation.
978
979 Captures all of the information in the underlying representation.
980 """
981
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000982 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000983 if self._is_special:
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000984 if self._exp == 'F':
985 return sign + 'Infinity'
986 elif self._exp == 'n':
987 return sign + 'NaN' + self._int
988 else: # self._exp == 'N'
989 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000990
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000991 # number of digits of self._int to left of decimal point
992 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000993
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000994 # dotplace is number of digits of self._int to the left of the
995 # decimal point in the mantissa of the output string (that is,
996 # after adjusting the exponent)
997 if self._exp <= 0 and leftdigits > -6:
998 # no exponent required
999 dotplace = leftdigits
1000 elif not eng:
1001 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001002 dotplace = 1
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001003 elif self._int == '0':
1004 # engineering notation, zero
1005 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001006 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001007 # engineering notation, nonzero
1008 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001010 if dotplace <= 0:
1011 intpart = '0'
1012 fracpart = '.' + '0'*(-dotplace) + self._int
1013 elif dotplace >= len(self._int):
1014 intpart = self._int+'0'*(dotplace-len(self._int))
1015 fracpart = ''
1016 else:
1017 intpart = self._int[:dotplace]
1018 fracpart = '.' + self._int[dotplace:]
1019 if leftdigits == dotplace:
1020 exp = ''
1021 else:
1022 if context is None:
1023 context = getcontext()
1024 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1025
1026 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001027
1028 def to_eng_string(self, context=None):
1029 """Convert to engineering-type string.
1030
1031 Engineering notation has an exponent which is a multiple of 3, so there
1032 are up to 3 digits left of the decimal place.
1033
1034 Same rules for when in exponential and when as a value as in __str__.
1035 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001036 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001037
1038 def __neg__(self, context=None):
1039 """Returns a copy with the sign switched.
1040
1041 Rounds, if it has reason.
1042 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001043 if self._is_special:
1044 ans = self._check_nans(context=context)
1045 if ans:
1046 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001047
1048 if not self:
1049 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001050 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001051 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001052 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001053
1054 if context is None:
1055 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001056 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001057
1058 def __pos__(self, context=None):
1059 """Returns a copy, unless it is a sNaN.
1060
1061 Rounds the number (if more then precision digits)
1062 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001063 if self._is_special:
1064 ans = self._check_nans(context=context)
1065 if ans:
1066 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001067
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001068 if not self:
1069 # + (-0) = 0
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001070 ans = self.copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001071 else:
1072 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001073
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001074 if context is None:
1075 context = getcontext()
Christian Heimes2c181612007-12-17 20:04:13 +00001076 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001077
Christian Heimes2c181612007-12-17 20:04:13 +00001078 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001079 """Returns the absolute value of self.
1080
Christian Heimes2c181612007-12-17 20:04:13 +00001081 If the keyword argument 'round' is false, do not round. The
1082 expression self.__abs__(round=False) is equivalent to
1083 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001084 """
Christian Heimes2c181612007-12-17 20:04:13 +00001085 if not round:
1086 return self.copy_abs()
1087
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001088 if self._is_special:
1089 ans = self._check_nans(context=context)
1090 if ans:
1091 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001092
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001093 if self._sign:
1094 ans = self.__neg__(context=context)
1095 else:
1096 ans = self.__pos__(context=context)
1097
1098 return ans
1099
1100 def __add__(self, other, context=None):
1101 """Returns self + other.
1102
1103 -INF + INF (or the reverse) cause InvalidOperation errors.
1104 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001105 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001106 if other is NotImplemented:
1107 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001108
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001109 if context is None:
1110 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001111
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001112 if self._is_special or other._is_special:
1113 ans = self._check_nans(other, context)
1114 if ans:
1115 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001116
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001117 if self._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001118 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001119 if self._sign != other._sign and other._isinfinity():
1120 return context._raise_error(InvalidOperation, '-INF + INF')
1121 return Decimal(self)
1122 if other._isinfinity():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001123 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001124
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001125 exp = min(self._exp, other._exp)
1126 negativezero = 0
1127 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001128 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001129 negativezero = 1
1130
1131 if not self and not other:
1132 sign = min(self._sign, other._sign)
1133 if negativezero:
1134 sign = 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001135 ans = _dec_from_triple(sign, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001136 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001137 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001138 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001139 exp = max(exp, other._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001140 ans = other._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001141 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001142 return ans
1143 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001144 exp = max(exp, self._exp - context.prec-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001145 ans = self._rescale(exp, context.rounding)
Christian Heimes2c181612007-12-17 20:04:13 +00001146 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001147 return ans
1148
1149 op1 = _WorkRep(self)
1150 op2 = _WorkRep(other)
Christian Heimes2c181612007-12-17 20:04:13 +00001151 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001152
1153 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001154 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001155 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001156 if op1.int == op2.int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001157 ans = _dec_from_triple(negativezero, '0', exp)
Christian Heimes2c181612007-12-17 20:04:13 +00001158 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001159 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001160 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001161 op1, op2 = op2, op1
Guido van Rossumd8faa362007-04-27 19:54:29 +00001162 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001163 if op1.sign == 1:
1164 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001165 op1.sign, op2.sign = op2.sign, op1.sign
1166 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001167 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001168 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001169 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001170 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001171 op1.sign, op2.sign = (0, 0)
1172 else:
1173 result.sign = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +00001174 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001175
Raymond Hettinger17931de2004-10-27 06:21:46 +00001176 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001177 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001178 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001179 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001180
1181 result.exp = op1.exp
1182 ans = Decimal(result)
Christian Heimes2c181612007-12-17 20:04:13 +00001183 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001184 return ans
1185
1186 __radd__ = __add__
1187
1188 def __sub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001189 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001190 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001191 if other is NotImplemented:
1192 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001193
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001194 if self._is_special or other._is_special:
1195 ans = self._check_nans(other, context=context)
1196 if ans:
1197 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001198
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001199 # self - other is computed as self + other.copy_negate()
1200 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001201
1202 def __rsub__(self, other, context=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001203 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001204 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001205 if other is NotImplemented:
1206 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001207
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001208 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001209
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001210 def __mul__(self, other, context=None):
1211 """Return self * other.
1212
1213 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1214 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001215 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001216 if other is NotImplemented:
1217 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001218
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001219 if context is None:
1220 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001221
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001222 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001223
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001224 if self._is_special or other._is_special:
1225 ans = self._check_nans(other, context)
1226 if ans:
1227 return ans
1228
1229 if self._isinfinity():
1230 if not other:
1231 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001232 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001233
1234 if other._isinfinity():
1235 if not self:
1236 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001237 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001238
1239 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001240
1241 # Special case for multiplying by zero
1242 if not self or not other:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001243 ans = _dec_from_triple(resultsign, '0', resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001244 # Fixing in case the exponent is out of bounds
1245 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001246 return ans
1247
1248 # Special case for multiplying by power of 10
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001249 if self._int == '1':
1250 ans = _dec_from_triple(resultsign, other._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001251 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001252 return ans
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001253 if other._int == '1':
1254 ans = _dec_from_triple(resultsign, self._int, resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001255 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001256 return ans
1257
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001258 op1 = _WorkRep(self)
1259 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001260
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001261 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Christian Heimes2c181612007-12-17 20:04:13 +00001262 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001263
1264 return ans
1265 __rmul__ = __mul__
1266
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001267 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001268 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001269 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001270 if other is NotImplemented:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001271 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001272
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001273 if context is None:
1274 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001275
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001276 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001277
1278 if self._is_special or other._is_special:
1279 ans = self._check_nans(other, context)
1280 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001281 return ans
1282
1283 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001284 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001285
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001286 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001287 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001288
1289 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001290 context._raise_error(Clamped, 'Division by infinity')
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001291 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001292
1293 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001294 if not other:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001295 if not self:
1296 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001297 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001298
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001299 if not self:
1300 exp = self._exp - other._exp
1301 coeff = 0
1302 else:
1303 # OK, so neither = 0, INF or NaN
1304 shift = len(other._int) - len(self._int) + context.prec + 1
1305 exp = self._exp - other._exp - shift
1306 op1 = _WorkRep(self)
1307 op2 = _WorkRep(other)
1308 if shift >= 0:
1309 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1310 else:
1311 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1312 if remainder:
1313 # result is not exact; adjust to ensure correct rounding
1314 if coeff % 5 == 0:
1315 coeff += 1
1316 else:
1317 # result is exact; get as close to ideal exponent as possible
1318 ideal_exp = self._exp - other._exp
1319 while exp < ideal_exp and coeff % 10 == 0:
1320 coeff //= 10
1321 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001322
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001323 ans = _dec_from_triple(sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001324 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001325
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001326 def _divide(self, other, context):
1327 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001328
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001329 Assumes that neither self nor other is a NaN, that self is not
1330 infinite and that other is nonzero.
1331 """
1332 sign = self._sign ^ other._sign
1333 if other._isinfinity():
1334 ideal_exp = self._exp
1335 else:
1336 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001337
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001338 expdiff = self.adjusted() - other.adjusted()
1339 if not self or other._isinfinity() or expdiff <= -2:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001340 return (_dec_from_triple(sign, '0', 0),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001341 self._rescale(ideal_exp, context.rounding))
1342 if expdiff <= context.prec:
1343 op1 = _WorkRep(self)
1344 op2 = _WorkRep(other)
1345 if op1.exp >= op2.exp:
1346 op1.int *= 10**(op1.exp - op2.exp)
1347 else:
1348 op2.int *= 10**(op2.exp - op1.exp)
1349 q, r = divmod(op1.int, op2.int)
1350 if q < 10**context.prec:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001351 return (_dec_from_triple(sign, str(q), 0),
1352 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001353
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001354 # Here the quotient is too large to be representable
1355 ans = context._raise_error(DivisionImpossible,
1356 'quotient too large in //, % or divmod')
1357 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001358
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001359 def __rtruediv__(self, other, context=None):
1360 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001361 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001362 if other is NotImplemented:
1363 return other
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001364 return other.__truediv__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001365
1366 def __divmod__(self, other, context=None):
1367 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001368 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001369 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001370 other = _convert_other(other)
1371 if other is NotImplemented:
1372 return other
1373
1374 if context is None:
1375 context = getcontext()
1376
1377 ans = self._check_nans(other, context)
1378 if ans:
1379 return (ans, ans)
1380
1381 sign = self._sign ^ other._sign
1382 if self._isinfinity():
1383 if other._isinfinity():
1384 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1385 return ans, ans
1386 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001387 return (_SignedInfinity[sign],
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001388 context._raise_error(InvalidOperation, 'INF % x'))
1389
1390 if not other:
1391 if not self:
1392 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1393 return ans, ans
1394 else:
1395 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1396 context._raise_error(InvalidOperation, 'x % 0'))
1397
1398 quotient, remainder = self._divide(other, context)
Christian Heimes2c181612007-12-17 20:04:13 +00001399 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001400 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001401
1402 def __rdivmod__(self, other, context=None):
1403 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001404 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001405 if other is NotImplemented:
1406 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001407 return other.__divmod__(self, context=context)
1408
1409 def __mod__(self, other, context=None):
1410 """
1411 self % other
1412 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001413 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001414 if other is NotImplemented:
1415 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001416
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001417 if context is None:
1418 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001419
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001420 ans = self._check_nans(other, context)
1421 if ans:
1422 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001423
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001424 if self._isinfinity():
1425 return context._raise_error(InvalidOperation, 'INF % x')
1426 elif not other:
1427 if self:
1428 return context._raise_error(InvalidOperation, 'x % 0')
1429 else:
1430 return context._raise_error(DivisionUndefined, '0 % 0')
1431
1432 remainder = self._divide(other, context)[1]
Christian Heimes2c181612007-12-17 20:04:13 +00001433 remainder = remainder._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001434 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001435
1436 def __rmod__(self, other, context=None):
1437 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001438 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001439 if other is NotImplemented:
1440 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001441 return other.__mod__(self, context=context)
1442
1443 def remainder_near(self, other, context=None):
1444 """
1445 Remainder nearest to 0- abs(remainder-near) <= other/2
1446 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001447 if context is None:
1448 context = getcontext()
1449
1450 other = _convert_other(other, raiseit=True)
1451
1452 ans = self._check_nans(other, context)
1453 if ans:
1454 return ans
1455
1456 # self == +/-infinity -> InvalidOperation
1457 if self._isinfinity():
1458 return context._raise_error(InvalidOperation,
1459 'remainder_near(infinity, x)')
1460
1461 # other == 0 -> either InvalidOperation or DivisionUndefined
1462 if not other:
1463 if self:
1464 return context._raise_error(InvalidOperation,
1465 'remainder_near(x, 0)')
1466 else:
1467 return context._raise_error(DivisionUndefined,
1468 'remainder_near(0, 0)')
1469
1470 # other = +/-infinity -> remainder = self
1471 if other._isinfinity():
1472 ans = Decimal(self)
1473 return ans._fix(context)
1474
1475 # self = 0 -> remainder = self, with ideal exponent
1476 ideal_exponent = min(self._exp, other._exp)
1477 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001478 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001479 return ans._fix(context)
1480
1481 # catch most cases of large or small quotient
1482 expdiff = self.adjusted() - other.adjusted()
1483 if expdiff >= context.prec + 1:
1484 # expdiff >= prec+1 => abs(self/other) > 10**prec
1485 return context._raise_error(DivisionImpossible)
1486 if expdiff <= -2:
1487 # expdiff <= -2 => abs(self/other) < 0.1
1488 ans = self._rescale(ideal_exponent, context.rounding)
1489 return ans._fix(context)
1490
1491 # adjust both arguments to have the same exponent, then divide
1492 op1 = _WorkRep(self)
1493 op2 = _WorkRep(other)
1494 if op1.exp >= op2.exp:
1495 op1.int *= 10**(op1.exp - op2.exp)
1496 else:
1497 op2.int *= 10**(op2.exp - op1.exp)
1498 q, r = divmod(op1.int, op2.int)
1499 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1500 # 10**ideal_exponent. Apply correction to ensure that
1501 # abs(remainder) <= abs(other)/2
1502 if 2*r + (q&1) > op2.int:
1503 r -= op2.int
1504 q += 1
1505
1506 if q >= 10**context.prec:
1507 return context._raise_error(DivisionImpossible)
1508
1509 # result has same sign as self unless r is negative
1510 sign = self._sign
1511 if r < 0:
1512 sign = 1-sign
1513 r = -r
1514
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001515 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001516 return ans._fix(context)
1517
1518 def __floordiv__(self, other, context=None):
1519 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001520 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001521 if other is NotImplemented:
1522 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001523
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001524 if context is None:
1525 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001526
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001527 ans = self._check_nans(other, context)
1528 if ans:
1529 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001530
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001531 if self._isinfinity():
1532 if other._isinfinity():
1533 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001534 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001535 return _SignedInfinity[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001536
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001537 if not other:
1538 if self:
1539 return context._raise_error(DivisionByZero, 'x // 0',
1540 self._sign ^ other._sign)
1541 else:
1542 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001543
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001544 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001545
1546 def __rfloordiv__(self, other, context=None):
1547 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001548 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001549 if other is NotImplemented:
1550 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001551 return other.__floordiv__(self, context=context)
1552
1553 def __float__(self):
1554 """Float representation."""
1555 return float(str(self))
1556
1557 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001558 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001559 if self._is_special:
1560 if self._isnan():
1561 context = getcontext()
1562 return context._raise_error(InvalidContext)
1563 elif self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001564 raise OverflowError("Cannot convert infinity to int")
1565 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001566 if self._exp >= 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001567 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001568 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001569 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001570
Christian Heimes969fe572008-01-25 11:23:10 +00001571 __trunc__ = __int__
1572
Christian Heimes0bd4e112008-02-12 22:59:25 +00001573 def real(self):
1574 return self
Mark Dickinson315a20a2009-01-04 21:34:18 +00001575 real = property(real)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001576
Christian Heimes0bd4e112008-02-12 22:59:25 +00001577 def imag(self):
1578 return Decimal(0)
Mark Dickinson315a20a2009-01-04 21:34:18 +00001579 imag = property(imag)
Christian Heimes0bd4e112008-02-12 22:59:25 +00001580
1581 def conjugate(self):
1582 return self
1583
1584 def __complex__(self):
1585 return complex(float(self))
1586
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001587 def _fix_nan(self, context):
1588 """Decapitate the payload of a NaN to fit the context"""
1589 payload = self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001590
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001591 # maximum length of payload is precision if _clamp=0,
1592 # precision-1 if _clamp=1.
1593 max_payload_len = context.prec - context._clamp
1594 if len(payload) > max_payload_len:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001595 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1596 return _dec_from_triple(self._sign, payload, self._exp, True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001597 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001598
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001599 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001600 """Round if it is necessary to keep self within prec precision.
1601
1602 Rounds and fixes the exponent. Does not raise on a sNaN.
1603
1604 Arguments:
1605 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001606 context - context used.
1607 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001608
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001609 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001610 if self._isnan():
1611 # decapitate payload if necessary
1612 return self._fix_nan(context)
1613 else:
1614 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001615 return Decimal(self)
1616
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001617 # if self is zero then exponent should be between Etiny and
1618 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1619 Etiny = context.Etiny()
1620 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001621 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001622 exp_max = [context.Emax, Etop][context._clamp]
1623 new_exp = min(max(self._exp, Etiny), exp_max)
1624 if new_exp != self._exp:
1625 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001626 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001627 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001628 return Decimal(self)
1629
1630 # exp_min is the smallest allowable exponent of the result,
1631 # equal to max(self.adjusted()-context.prec+1, Etiny)
1632 exp_min = len(self._int) + self._exp - context.prec
1633 if exp_min > Etop:
1634 # overflow: exp_min > Etop iff self.adjusted() > Emax
1635 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001636 context._raise_error(Rounded)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001637 return context._raise_error(Overflow, 'above Emax', self._sign)
1638 self_is_subnormal = exp_min < Etiny
1639 if self_is_subnormal:
1640 context._raise_error(Subnormal)
1641 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001642
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001643 # round if self has too many digits
1644 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001645 context._raise_error(Rounded)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001646 digits = len(self._int) + self._exp - exp_min
1647 if digits < 0:
1648 self = _dec_from_triple(self._sign, '1', exp_min-1)
1649 digits = 0
1650 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1651 changed = this_function(digits)
1652 coeff = self._int[:digits] or '0'
1653 if changed == 1:
1654 coeff = str(int(coeff)+1)
1655 ans = _dec_from_triple(self._sign, coeff, exp_min)
1656
1657 if changed:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001658 context._raise_error(Inexact)
1659 if self_is_subnormal:
1660 context._raise_error(Underflow)
1661 if not ans:
1662 # raise Clamped on underflow to 0
1663 context._raise_error(Clamped)
1664 elif len(ans._int) == context.prec+1:
1665 # we get here only if rescaling rounds the
1666 # cofficient up to exactly 10**context.prec
1667 if ans._exp < Etop:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001668 ans = _dec_from_triple(ans._sign,
1669 ans._int[:-1], ans._exp+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001670 else:
1671 # Inexact and Rounded have already been raised
1672 ans = context._raise_error(Overflow, 'above Emax',
1673 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001674 return ans
1675
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001676 # fold down if _clamp == 1 and self has too few digits
1677 if context._clamp == 1 and self._exp > Etop:
1678 context._raise_error(Clamped)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001679 self_padded = self._int + '0'*(self._exp - Etop)
1680 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001681
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001682 # here self was representable to begin with; return unchanged
1683 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001684
1685 _pick_rounding_function = {}
1686
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001687 # for each of the rounding functions below:
1688 # self is a finite, nonzero Decimal
1689 # prec is an integer satisfying 0 <= prec < len(self._int)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001690 #
1691 # each function returns either -1, 0, or 1, as follows:
1692 # 1 indicates that self should be rounded up (away from zero)
1693 # 0 indicates that self should be truncated, and that all the
1694 # digits to be truncated are zeros (so the value is unchanged)
1695 # -1 indicates that there are nonzero digits to be truncated
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001696
1697 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001698 """Also known as round-towards-0, truncate."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001699 if _all_zeros(self._int, prec):
1700 return 0
1701 else:
1702 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001703
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001704 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001705 """Rounds away from 0."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001706 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001707
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001708 def _round_half_up(self, prec):
1709 """Rounds 5 up (away from 0)"""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001710 if self._int[prec] in '56789':
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001711 return 1
1712 elif _all_zeros(self._int, prec):
1713 return 0
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001714 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001715 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001716
1717 def _round_half_down(self, prec):
1718 """Round 5 down"""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001719 if _exact_half(self._int, prec):
1720 return -1
1721 else:
1722 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001723
1724 def _round_half_even(self, prec):
1725 """Round 5 to even, rest to nearest."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001726 if _exact_half(self._int, prec) and \
1727 (prec == 0 or self._int[prec-1] in '02468'):
1728 return -1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001729 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001730 return self._round_half_up(prec)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001731
1732 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001733 """Rounds up (not away from 0 if negative.)"""
1734 if self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001735 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001736 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001737 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001738
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001739 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001740 """Rounds down (not towards 0 if negative)"""
1741 if not self._sign:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001742 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001743 else:
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001744 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001745
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001746 def _round_05up(self, prec):
1747 """Round down unless digit prec-1 is 0 or 5."""
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001748 if prec and self._int[prec-1] not in '05':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001749 return self._round_down(prec)
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001750 else:
1751 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001752
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001753 def __round__(self, n=None):
1754 """Round self to the nearest integer, or to a given precision.
1755
1756 If only one argument is supplied, round a finite Decimal
1757 instance self to the nearest integer. If self is infinite or
1758 a NaN then a Python exception is raised. If self is finite
1759 and lies exactly halfway between two integers then it is
1760 rounded to the integer with even last digit.
1761
1762 >>> round(Decimal('123.456'))
1763 123
1764 >>> round(Decimal('-456.789'))
1765 -457
1766 >>> round(Decimal('-3.0'))
1767 -3
1768 >>> round(Decimal('2.5'))
1769 2
1770 >>> round(Decimal('3.5'))
1771 4
1772 >>> round(Decimal('Inf'))
1773 Traceback (most recent call last):
1774 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001775 OverflowError: cannot round an infinity
1776 >>> round(Decimal('NaN'))
1777 Traceback (most recent call last):
1778 ...
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001779 ValueError: cannot round a NaN
1780
1781 If a second argument n is supplied, self is rounded to n
1782 decimal places using the rounding mode for the current
1783 context.
1784
1785 For an integer n, round(self, -n) is exactly equivalent to
1786 self.quantize(Decimal('1En')).
1787
1788 >>> round(Decimal('123.456'), 0)
1789 Decimal('123')
1790 >>> round(Decimal('123.456'), 2)
1791 Decimal('123.46')
1792 >>> round(Decimal('123.456'), -2)
1793 Decimal('1E+2')
1794 >>> round(Decimal('-Infinity'), 37)
1795 Decimal('NaN')
1796 >>> round(Decimal('sNaN123'), 0)
1797 Decimal('NaN123')
1798
1799 """
1800 if n is not None:
1801 # two-argument form: use the equivalent quantize call
1802 if not isinstance(n, int):
1803 raise TypeError('Second argument to round should be integral')
1804 exp = _dec_from_triple(0, '1', -n)
1805 return self.quantize(exp)
1806
1807 # one-argument form
1808 if self._is_special:
1809 if self.is_nan():
1810 raise ValueError("cannot round a NaN")
1811 else:
1812 raise OverflowError("cannot round an infinity")
1813 return int(self._rescale(0, ROUND_HALF_EVEN))
1814
1815 def __floor__(self):
1816 """Return the floor of self, as an integer.
1817
1818 For a finite Decimal instance self, return the greatest
1819 integer n such that n <= self. If self is infinite or a NaN
1820 then a Python exception is raised.
1821
1822 """
1823 if self._is_special:
1824 if self.is_nan():
1825 raise ValueError("cannot round a NaN")
1826 else:
1827 raise OverflowError("cannot round an infinity")
1828 return int(self._rescale(0, ROUND_FLOOR))
1829
1830 def __ceil__(self):
1831 """Return the ceiling of self, as an integer.
1832
1833 For a finite Decimal instance self, return the least integer n
1834 such that n >= self. If self is infinite or a NaN then a
1835 Python exception is raised.
1836
1837 """
1838 if self._is_special:
1839 if self.is_nan():
1840 raise ValueError("cannot round a NaN")
1841 else:
1842 raise OverflowError("cannot round an infinity")
1843 return int(self._rescale(0, ROUND_CEILING))
1844
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001845 def fma(self, other, third, context=None):
1846 """Fused multiply-add.
1847
1848 Returns self*other+third with no rounding of the intermediate
1849 product self*other.
1850
1851 self and other are multiplied together, with no rounding of
1852 the result. The third operand is then added to the result,
1853 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001854 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001855
1856 other = _convert_other(other, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001857
1858 # compute product; raise InvalidOperation if either operand is
1859 # a signaling NaN or if the product is zero times infinity.
1860 if self._is_special or other._is_special:
1861 if context is None:
1862 context = getcontext()
1863 if self._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001864 return context._raise_error(InvalidOperation, 'sNaN', self)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001865 if other._exp == 'N':
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001866 return context._raise_error(InvalidOperation, 'sNaN', other)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001867 if self._exp == 'n':
1868 product = self
1869 elif other._exp == 'n':
1870 product = other
1871 elif self._exp == 'F':
1872 if not other:
1873 return context._raise_error(InvalidOperation,
1874 'INF * 0 in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001875 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001876 elif other._exp == 'F':
1877 if not self:
1878 return context._raise_error(InvalidOperation,
1879 '0 * INF in fma')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00001880 product = _SignedInfinity[self._sign ^ other._sign]
Christian Heimes8b0facf2007-12-04 19:30:01 +00001881 else:
1882 product = _dec_from_triple(self._sign ^ other._sign,
1883 str(int(self._int) * int(other._int)),
1884 self._exp + other._exp)
1885
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001886 third = _convert_other(third, raiseit=True)
Christian Heimes8b0facf2007-12-04 19:30:01 +00001887 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001888
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001889 def _power_modulo(self, other, modulo, context=None):
1890 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001891
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001892 # if can't convert other and modulo to Decimal, raise
1893 # TypeError; there's no point returning NotImplemented (no
1894 # equivalent of __rpow__ for three argument pow)
1895 other = _convert_other(other, raiseit=True)
1896 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001897
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001898 if context is None:
1899 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001900
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001901 # deal with NaNs: if there are any sNaNs then first one wins,
1902 # (i.e. behaviour for NaNs is identical to that of fma)
1903 self_is_nan = self._isnan()
1904 other_is_nan = other._isnan()
1905 modulo_is_nan = modulo._isnan()
1906 if self_is_nan or other_is_nan or modulo_is_nan:
1907 if self_is_nan == 2:
1908 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001909 self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001910 if other_is_nan == 2:
1911 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001912 other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001913 if modulo_is_nan == 2:
1914 return context._raise_error(InvalidOperation, 'sNaN',
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00001915 modulo)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001916 if self_is_nan:
1917 return self._fix_nan(context)
1918 if other_is_nan:
1919 return other._fix_nan(context)
1920 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001921
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001922 # check inputs: we apply same restrictions as Python's pow()
1923 if not (self._isinteger() and
1924 other._isinteger() and
1925 modulo._isinteger()):
1926 return context._raise_error(InvalidOperation,
1927 'pow() 3rd argument not allowed '
1928 'unless all arguments are integers')
1929 if other < 0:
1930 return context._raise_error(InvalidOperation,
1931 'pow() 2nd argument cannot be '
1932 'negative when 3rd argument specified')
1933 if not modulo:
1934 return context._raise_error(InvalidOperation,
1935 'pow() 3rd argument cannot be 0')
1936
1937 # additional restriction for decimal: the modulus must be less
1938 # than 10**prec in absolute value
1939 if modulo.adjusted() >= context.prec:
1940 return context._raise_error(InvalidOperation,
1941 'insufficient precision: pow() 3rd '
1942 'argument must not have more than '
1943 'precision digits')
1944
1945 # define 0**0 == NaN, for consistency with two-argument pow
1946 # (even though it hurts!)
1947 if not other and not self:
1948 return context._raise_error(InvalidOperation,
1949 'at least one of pow() 1st argument '
1950 'and 2nd argument must be nonzero ;'
1951 '0**0 is not defined')
1952
1953 # compute sign of result
1954 if other._iseven():
1955 sign = 0
1956 else:
1957 sign = self._sign
1958
1959 # convert modulo to a Python integer, and self and other to
1960 # Decimal integers (i.e. force their exponents to be >= 0)
1961 modulo = abs(int(modulo))
1962 base = _WorkRep(self.to_integral_value())
1963 exponent = _WorkRep(other.to_integral_value())
1964
1965 # compute result using integer pow()
1966 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1967 for i in range(exponent.exp):
1968 base = pow(base, 10, modulo)
1969 base = pow(base, exponent.int, modulo)
1970
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00001971 return _dec_from_triple(sign, str(base), 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001972
1973 def _power_exact(self, other, p):
1974 """Attempt to compute self**other exactly.
1975
1976 Given Decimals self and other and an integer p, attempt to
1977 compute an exact result for the power self**other, with p
1978 digits of precision. Return None if self**other is not
1979 exactly representable in p digits.
1980
1981 Assumes that elimination of special cases has already been
1982 performed: self and other must both be nonspecial; self must
1983 be positive and not numerically equal to 1; other must be
1984 nonzero. For efficiency, other._exp should not be too large,
1985 so that 10**abs(other._exp) is a feasible calculation."""
1986
1987 # In the comments below, we write x for the value of self and
1988 # y for the value of other. Write x = xc*10**xe and y =
1989 # yc*10**ye.
1990
1991 # The main purpose of this method is to identify the *failure*
1992 # of x**y to be exactly representable with as little effort as
1993 # possible. So we look for cheap and easy tests that
1994 # eliminate the possibility of x**y being exact. Only if all
1995 # these tests are passed do we go on to actually compute x**y.
1996
1997 # Here's the main idea. First normalize both x and y. We
1998 # express y as a rational m/n, with m and n relatively prime
1999 # and n>0. Then for x**y to be exactly representable (at
2000 # *any* precision), xc must be the nth power of a positive
2001 # integer and xe must be divisible by n. If m is negative
2002 # then additionally xc must be a power of either 2 or 5, hence
2003 # a power of 2**n or 5**n.
2004 #
2005 # There's a limit to how small |y| can be: if y=m/n as above
2006 # then:
2007 #
2008 # (1) if xc != 1 then for the result to be representable we
2009 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
2010 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
2011 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
2012 # representable.
2013 #
2014 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
2015 # |y| < 1/|xe| then the result is not representable.
2016 #
2017 # Note that since x is not equal to 1, at least one of (1) and
2018 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2019 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2020 #
2021 # There's also a limit to how large y can be, at least if it's
2022 # positive: the normalized result will have coefficient xc**y,
2023 # so if it's representable then xc**y < 10**p, and y <
2024 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
2025 # not exactly representable.
2026
2027 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2028 # so |y| < 1/xe and the result is not representable.
2029 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2030 # < 1/nbits(xc).
2031
2032 x = _WorkRep(self)
2033 xc, xe = x.int, x.exp
2034 while xc % 10 == 0:
2035 xc //= 10
2036 xe += 1
2037
2038 y = _WorkRep(other)
2039 yc, ye = y.int, y.exp
2040 while yc % 10 == 0:
2041 yc //= 10
2042 ye += 1
2043
2044 # case where xc == 1: result is 10**(xe*y), with xe*y
2045 # required to be an integer
2046 if xc == 1:
2047 if ye >= 0:
2048 exponent = xe*yc*10**ye
2049 else:
2050 exponent, remainder = divmod(xe*yc, 10**-ye)
2051 if remainder:
2052 return None
2053 if y.sign == 1:
2054 exponent = -exponent
2055 # if other is a nonnegative integer, use ideal exponent
2056 if other._isinteger() and other._sign == 0:
2057 ideal_exponent = self._exp*int(other)
2058 zeros = min(exponent-ideal_exponent, p-1)
2059 else:
2060 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002061 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002062
2063 # case where y is negative: xc must be either a power
2064 # of 2 or a power of 5.
2065 if y.sign == 1:
2066 last_digit = xc % 10
2067 if last_digit in (2,4,6,8):
2068 # quick test for power of 2
2069 if xc & -xc != xc:
2070 return None
2071 # now xc is a power of 2; e is its exponent
2072 e = _nbits(xc)-1
2073 # find e*y and xe*y; both must be integers
2074 if ye >= 0:
2075 y_as_int = yc*10**ye
2076 e = e*y_as_int
2077 xe = xe*y_as_int
2078 else:
2079 ten_pow = 10**-ye
2080 e, remainder = divmod(e*yc, ten_pow)
2081 if remainder:
2082 return None
2083 xe, remainder = divmod(xe*yc, ten_pow)
2084 if remainder:
2085 return None
2086
2087 if e*65 >= p*93: # 93/65 > log(10)/log(5)
2088 return None
2089 xc = 5**e
2090
2091 elif last_digit == 5:
2092 # e >= log_5(xc) if xc is a power of 5; we have
2093 # equality all the way up to xc=5**2658
2094 e = _nbits(xc)*28//65
2095 xc, remainder = divmod(5**e, xc)
2096 if remainder:
2097 return None
2098 while xc % 5 == 0:
2099 xc //= 5
2100 e -= 1
2101 if ye >= 0:
2102 y_as_integer = yc*10**ye
2103 e = e*y_as_integer
2104 xe = xe*y_as_integer
2105 else:
2106 ten_pow = 10**-ye
2107 e, remainder = divmod(e*yc, ten_pow)
2108 if remainder:
2109 return None
2110 xe, remainder = divmod(xe*yc, ten_pow)
2111 if remainder:
2112 return None
2113 if e*3 >= p*10: # 10/3 > log(10)/log(2)
2114 return None
2115 xc = 2**e
2116 else:
2117 return None
2118
2119 if xc >= 10**p:
2120 return None
2121 xe = -e-xe
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002122 return _dec_from_triple(0, str(xc), xe)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002123
2124 # now y is positive; find m and n such that y = m/n
2125 if ye >= 0:
2126 m, n = yc*10**ye, 1
2127 else:
2128 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2129 return None
2130 xc_bits = _nbits(xc)
2131 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2132 return None
2133 m, n = yc, 10**(-ye)
2134 while m % 2 == n % 2 == 0:
2135 m //= 2
2136 n //= 2
2137 while m % 5 == n % 5 == 0:
2138 m //= 5
2139 n //= 5
2140
2141 # compute nth root of xc*10**xe
2142 if n > 1:
2143 # if 1 < xc < 2**n then xc isn't an nth power
2144 if xc != 1 and xc_bits <= n:
2145 return None
2146
2147 xe, rem = divmod(xe, n)
2148 if rem != 0:
2149 return None
2150
2151 # compute nth root of xc using Newton's method
2152 a = 1 << -(-_nbits(xc)//n) # initial estimate
2153 while True:
2154 q, r = divmod(xc, a**(n-1))
2155 if a <= q:
2156 break
2157 else:
2158 a = (a*(n-1) + q)//n
2159 if not (a == q and r == 0):
2160 return None
2161 xc = a
2162
2163 # now xc*10**xe is the nth root of the original xc*10**xe
2164 # compute mth power of xc*10**xe
2165
2166 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2167 # 10**p and the result is not representable.
2168 if xc > 1 and m > p*100//_log10_lb(xc):
2169 return None
2170 xc = xc**m
2171 xe *= m
2172 if xc > 10**p:
2173 return None
2174
2175 # by this point the result *is* exactly representable
2176 # adjust the exponent to get as close as possible to the ideal
2177 # exponent, if necessary
2178 str_xc = str(xc)
2179 if other._isinteger() and other._sign == 0:
2180 ideal_exponent = self._exp*int(other)
2181 zeros = min(xe-ideal_exponent, p-len(str_xc))
2182 else:
2183 zeros = 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002184 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002185
2186 def __pow__(self, other, modulo=None, context=None):
2187 """Return self ** other [ % modulo].
2188
2189 With two arguments, compute self**other.
2190
2191 With three arguments, compute (self**other) % modulo. For the
2192 three argument form, the following restrictions on the
2193 arguments hold:
2194
2195 - all three arguments must be integral
2196 - other must be nonnegative
2197 - either self or other (or both) must be nonzero
2198 - modulo must be nonzero and must have at most p digits,
2199 where p is the context precision.
2200
2201 If any of these restrictions is violated the InvalidOperation
2202 flag is raised.
2203
2204 The result of pow(self, other, modulo) is identical to the
2205 result that would be obtained by computing (self**other) %
2206 modulo with unbounded precision, but is computed more
2207 efficiently. It is always exact.
2208 """
2209
2210 if modulo is not None:
2211 return self._power_modulo(other, modulo, context)
2212
2213 other = _convert_other(other)
2214 if other is NotImplemented:
2215 return other
2216
2217 if context is None:
2218 context = getcontext()
2219
2220 # either argument is a NaN => result is NaN
2221 ans = self._check_nans(other, context)
2222 if ans:
2223 return ans
2224
2225 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2226 if not other:
2227 if not self:
2228 return context._raise_error(InvalidOperation, '0 ** 0')
2229 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002230 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002231
2232 # result has sign 1 iff self._sign is 1 and other is an odd integer
2233 result_sign = 0
2234 if self._sign == 1:
2235 if other._isinteger():
2236 if not other._iseven():
2237 result_sign = 1
2238 else:
2239 # -ve**noninteger = NaN
2240 # (-0)**noninteger = 0**noninteger
2241 if self:
2242 return context._raise_error(InvalidOperation,
2243 'x ** y with x negative and y not an integer')
2244 # negate self, without doing any unwanted rounding
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002245 self = self.copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002246
2247 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2248 if not self:
2249 if other._sign == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002250 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002251 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002252 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002253
2254 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002255 if self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002256 if other._sign == 0:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002257 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002258 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002259 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002260
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002261 # 1**other = 1, but the choice of exponent and the flags
2262 # depend on the exponent of self, and on whether other is a
2263 # positive integer, a negative integer, or neither
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002264 if self == _One:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002265 if other._isinteger():
2266 # exp = max(self._exp*max(int(other), 0),
2267 # 1-context.prec) but evaluating int(other) directly
2268 # is dangerous until we know other is small (other
2269 # could be 1e999999999)
2270 if other._sign == 1:
2271 multiplier = 0
2272 elif other > context.prec:
2273 multiplier = context.prec
2274 else:
2275 multiplier = int(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002276
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002277 exp = self._exp * multiplier
2278 if exp < 1-context.prec:
2279 exp = 1-context.prec
2280 context._raise_error(Rounded)
2281 else:
2282 context._raise_error(Inexact)
2283 context._raise_error(Rounded)
2284 exp = 1-context.prec
2285
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002286 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002287
2288 # compute adjusted exponent of self
2289 self_adj = self.adjusted()
2290
2291 # self ** infinity is infinity if self > 1, 0 if self < 1
2292 # self ** -infinity is infinity if self < 1, 0 if self > 1
2293 if other._isinfinity():
2294 if (other._sign == 0) == (self_adj < 0):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002295 return _dec_from_triple(result_sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002296 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002297 return _SignedInfinity[result_sign]
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002298
2299 # from here on, the result always goes through the call
2300 # to _fix at the end of this function.
2301 ans = None
2302
2303 # crude test to catch cases of extreme overflow/underflow. If
2304 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2305 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2306 # self**other >= 10**(Emax+1), so overflow occurs. The test
2307 # for underflow is similar.
2308 bound = self._log10_exp_bound() + other.adjusted()
2309 if (self_adj >= 0) == (other._sign == 0):
2310 # self > 1 and other +ve, or self < 1 and other -ve
2311 # possibility of overflow
2312 if bound >= len(str(context.Emax)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002313 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002314 else:
2315 # self > 1 and other -ve, or self < 1 and other +ve
2316 # possibility of underflow to 0
2317 Etiny = context.Etiny()
2318 if bound >= len(str(-Etiny)):
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002319 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002320
2321 # try for an exact result with precision +1
2322 if ans is None:
2323 ans = self._power_exact(other, context.prec + 1)
2324 if ans is not None and result_sign == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002325 ans = _dec_from_triple(1, ans._int, ans._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002326
2327 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2328 if ans is None:
2329 p = context.prec
2330 x = _WorkRep(self)
2331 xc, xe = x.int, x.exp
2332 y = _WorkRep(other)
2333 yc, ye = y.int, y.exp
2334 if y.sign == 1:
2335 yc = -yc
2336
2337 # compute correctly rounded result: start with precision +3,
2338 # then increase precision until result is unambiguously roundable
2339 extra = 3
2340 while True:
2341 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2342 if coeff % (5*10**(len(str(coeff))-p-1)):
2343 break
2344 extra += 3
2345
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002346 ans = _dec_from_triple(result_sign, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002347
2348 # the specification says that for non-integer other we need to
2349 # raise Inexact, even when the result is actually exact. In
2350 # the same way, we need to raise Underflow here if the result
2351 # is subnormal. (The call to _fix will take care of raising
2352 # Rounded and Subnormal, as usual.)
2353 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002354 context._raise_error(Inexact)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002355 # pad with zeros up to length context.prec+1 if necessary
2356 if len(ans._int) <= context.prec:
2357 expdiff = context.prec+1 - len(ans._int)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002358 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2359 ans._exp-expdiff)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002360 if ans.adjusted() < context.Emin:
2361 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002362
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002363 # unlike exp, ln and log10, the power function respects the
2364 # rounding mode; no need to use ROUND_HALF_EVEN here
2365 ans = ans._fix(context)
2366 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002367
2368 def __rpow__(self, other, context=None):
2369 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002370 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002371 if other is NotImplemented:
2372 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002373 return other.__pow__(self, context=context)
2374
2375 def normalize(self, context=None):
2376 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002377
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002378 if context is None:
2379 context = getcontext()
2380
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002381 if self._is_special:
2382 ans = self._check_nans(context=context)
2383 if ans:
2384 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002385
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002386 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002387 if dup._isinfinity():
2388 return dup
2389
2390 if not dup:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002391 return _dec_from_triple(dup._sign, '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002392 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002393 end = len(dup._int)
2394 exp = dup._exp
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002395 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002396 exp += 1
2397 end -= 1
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002398 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002399
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002400 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002401 """Quantize self so its exponent is the same as that of exp.
2402
2403 Similar to self._rescale(exp._exp) but with error checking.
2404 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002405 exp = _convert_other(exp, raiseit=True)
2406
2407 if context is None:
2408 context = getcontext()
2409 if rounding is None:
2410 rounding = context.rounding
2411
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002412 if self._is_special or exp._is_special:
2413 ans = self._check_nans(exp, context)
2414 if ans:
2415 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002416
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002417 if exp._isinfinity() or self._isinfinity():
2418 if exp._isinfinity() and self._isinfinity():
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002419 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002420 return context._raise_error(InvalidOperation,
2421 'quantize with one INF')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002422
2423 # if we're not watching exponents, do a simple rescale
2424 if not watchexp:
2425 ans = self._rescale(exp._exp, rounding)
2426 # raise Inexact and Rounded where appropriate
2427 if ans._exp > self._exp:
2428 context._raise_error(Rounded)
2429 if ans != self:
2430 context._raise_error(Inexact)
2431 return ans
2432
2433 # exp._exp should be between Etiny and Emax
2434 if not (context.Etiny() <= exp._exp <= context.Emax):
2435 return context._raise_error(InvalidOperation,
2436 'target exponent out of bounds in quantize')
2437
2438 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002439 ans = _dec_from_triple(self._sign, '0', exp._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002440 return ans._fix(context)
2441
2442 self_adjusted = self.adjusted()
2443 if self_adjusted > context.Emax:
2444 return context._raise_error(InvalidOperation,
2445 'exponent of quantize result too large for current context')
2446 if self_adjusted - exp._exp + 1 > context.prec:
2447 return context._raise_error(InvalidOperation,
2448 'quantize result has too many digits for current context')
2449
2450 ans = self._rescale(exp._exp, rounding)
2451 if ans.adjusted() > context.Emax:
2452 return context._raise_error(InvalidOperation,
2453 'exponent of quantize result too large for current context')
2454 if len(ans._int) > context.prec:
2455 return context._raise_error(InvalidOperation,
2456 'quantize result has too many digits for current context')
2457
2458 # raise appropriate flags
2459 if ans._exp > self._exp:
2460 context._raise_error(Rounded)
2461 if ans != self:
2462 context._raise_error(Inexact)
2463 if ans and ans.adjusted() < context.Emin:
2464 context._raise_error(Subnormal)
2465
2466 # call to fix takes care of any necessary folddown
2467 ans = ans._fix(context)
2468 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002469
2470 def same_quantum(self, other):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002471 """Return True if self and other have the same exponent; otherwise
2472 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002473
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002474 If either operand is a special value, the following rules are used:
2475 * return True if both operands are infinities
2476 * return True if both operands are NaNs
2477 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002478 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002479 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002480 if self._is_special or other._is_special:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002481 return (self.is_nan() and other.is_nan() or
2482 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002483 return self._exp == other._exp
2484
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002485 def _rescale(self, exp, rounding):
2486 """Rescale self so that the exponent is exp, either by padding with zeros
2487 or by truncating digits, using the given rounding mode.
2488
2489 Specials are returned without change. This operation is
2490 quiet: it raises no flags, and uses no information from the
2491 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002492
2493 exp = exp to scale to (an integer)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002494 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002495 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002496 if self._is_special:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002497 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002498 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002499 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002500
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002501 if self._exp >= exp:
2502 # pad answer with zeros if necessary
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002503 return _dec_from_triple(self._sign,
2504 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002505
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002506 # too many digits; round and lose data. If self.adjusted() <
2507 # exp-1, replace self by 10**(exp-1) before rounding
2508 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002509 if digits < 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002510 self = _dec_from_triple(self._sign, '1', exp-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002511 digits = 0
2512 this_function = getattr(self, self._pick_rounding_function[rounding])
Christian Heimescbf3b5c2007-12-03 21:02:03 +00002513 changed = this_function(digits)
2514 coeff = self._int[:digits] or '0'
2515 if changed == 1:
2516 coeff = str(int(coeff)+1)
2517 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002518
Christian Heimesf16baeb2008-02-29 14:57:44 +00002519 def _round(self, places, rounding):
2520 """Round a nonzero, nonspecial Decimal to a fixed number of
2521 significant figures, using the given rounding mode.
2522
2523 Infinities, NaNs and zeros are returned unaltered.
2524
2525 This operation is quiet: it raises no flags, and uses no
2526 information from the context.
2527
2528 """
2529 if places <= 0:
2530 raise ValueError("argument should be at least 1 in _round")
2531 if self._is_special or not self:
2532 return Decimal(self)
2533 ans = self._rescale(self.adjusted()+1-places, rounding)
2534 # it can happen that the rescale alters the adjusted exponent;
2535 # for example when rounding 99.97 to 3 significant figures.
2536 # When this happens we end up with an extra 0 at the end of
2537 # the number; a second rescale fixes this.
2538 if ans.adjusted() != self.adjusted():
2539 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2540 return ans
2541
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002542 def to_integral_exact(self, rounding=None, context=None):
2543 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002544
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002545 If no rounding mode is specified, take the rounding mode from
2546 the context. This method raises the Rounded and Inexact flags
2547 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002548
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002549 See also: to_integral_value, which does exactly the same as
2550 this method except that it doesn't raise Inexact or Rounded.
2551 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002552 if self._is_special:
2553 ans = self._check_nans(context=context)
2554 if ans:
2555 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002556 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002557 if self._exp >= 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002558 return Decimal(self)
2559 if not self:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002560 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002561 if context is None:
2562 context = getcontext()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002563 if rounding is None:
2564 rounding = context.rounding
2565 context._raise_error(Rounded)
2566 ans = self._rescale(0, rounding)
2567 if ans != self:
2568 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002569 return ans
2570
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002571 def to_integral_value(self, rounding=None, context=None):
2572 """Rounds to the nearest integer, without raising inexact, rounded."""
2573 if context is None:
2574 context = getcontext()
2575 if rounding is None:
2576 rounding = context.rounding
2577 if self._is_special:
2578 ans = self._check_nans(context=context)
2579 if ans:
2580 return ans
2581 return Decimal(self)
2582 if self._exp >= 0:
2583 return Decimal(self)
2584 else:
2585 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002586
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002587 # the method name changed, but we provide also the old one, for compatibility
2588 to_integral = to_integral_value
2589
2590 def sqrt(self, context=None):
2591 """Return the square root of self."""
Christian Heimes0348fb62008-03-26 12:55:56 +00002592 if context is None:
2593 context = getcontext()
2594
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002595 if self._is_special:
2596 ans = self._check_nans(context=context)
2597 if ans:
2598 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002599
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002600 if self._isinfinity() and self._sign == 0:
2601 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002602
2603 if not self:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002604 # exponent = self._exp // 2. sqrt(-0) = -0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002605 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002606 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002607
2608 if self._sign == 1:
2609 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2610
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002611 # At this point self represents a positive number. Let p be
2612 # the desired precision and express self in the form c*100**e
2613 # with c a positive real number and e an integer, c and e
2614 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2615 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2616 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2617 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2618 # the closest integer to sqrt(c) with the even integer chosen
2619 # in the case of a tie.
2620 #
2621 # To ensure correct rounding in all cases, we use the
2622 # following trick: we compute the square root to an extra
2623 # place (precision p+1 instead of precision p), rounding down.
2624 # Then, if the result is inexact and its last digit is 0 or 5,
2625 # we increase the last digit to 1 or 6 respectively; if it's
2626 # exact we leave the last digit alone. Now the final round to
2627 # p places (or fewer in the case of underflow) will round
2628 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002629
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002630 # use an extra digit of precision
2631 prec = context.prec+1
2632
2633 # write argument in the form c*100**e where e = self._exp//2
2634 # is the 'ideal' exponent, to be used if the square root is
2635 # exactly representable. l is the number of 'digits' of c in
2636 # base 100, so that 100**(l-1) <= c < 100**l.
2637 op = _WorkRep(self)
2638 e = op.exp >> 1
2639 if op.exp & 1:
2640 c = op.int * 10
2641 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002642 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002643 c = op.int
2644 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002645
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002646 # rescale so that c has exactly prec base 100 'digits'
2647 shift = prec-l
2648 if shift >= 0:
2649 c *= 100**shift
2650 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002651 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002652 c, remainder = divmod(c, 100**-shift)
2653 exact = not remainder
2654 e -= shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002655
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002656 # find n = floor(sqrt(c)) using Newton's method
2657 n = 10**prec
2658 while True:
2659 q = c//n
2660 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002661 break
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002662 else:
2663 n = n + q >> 1
2664 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002665
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002666 if exact:
2667 # result is exact; rescale to use ideal exponent e
2668 if shift >= 0:
2669 # assert n % 10**shift == 0
2670 n //= 10**shift
2671 else:
2672 n *= 10**-shift
2673 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002674 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002675 # result is not exact; fix last digit as described above
2676 if n % 5 == 0:
2677 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002678
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002679 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002680
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002681 # round, and fit to current context
2682 context = context._shallow_copy()
2683 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002684 ans = ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002685 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002686
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002687 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002688
2689 def max(self, other, context=None):
2690 """Returns the larger value.
2691
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002692 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002693 NaN (and signals if one is sNaN). Also rounds.
2694 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002695 other = _convert_other(other, raiseit=True)
2696
2697 if context is None:
2698 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002699
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002700 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002701 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002702 # number is always returned
2703 sn = self._isnan()
2704 on = other._isnan()
2705 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002706 if on == 1 and sn == 0:
2707 return self._fix(context)
2708 if sn == 1 and on == 0:
2709 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002710 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002711
Christian Heimes77c02eb2008-02-09 02:18:51 +00002712 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002713 if c == 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002714 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002715 # then an ordering is applied:
2716 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002717 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002718 # positive sign and min returns the operand with the negative sign
2719 #
Guido van Rossumd8faa362007-04-27 19:54:29 +00002720 # If the signs are the same then the exponent is used to select
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002721 # the result. This is exactly the ordering used in compare_total.
2722 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002723
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002724 if c == -1:
2725 ans = other
2726 else:
2727 ans = self
2728
Christian Heimes2c181612007-12-17 20:04:13 +00002729 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002730
2731 def min(self, other, context=None):
2732 """Returns the smaller value.
2733
Guido van Rossumd8faa362007-04-27 19:54:29 +00002734 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002735 NaN (and signals if one is sNaN). Also rounds.
2736 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002737 other = _convert_other(other, raiseit=True)
2738
2739 if context is None:
2740 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002741
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002742 if self._is_special or other._is_special:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002743 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002744 # number is always returned
2745 sn = self._isnan()
2746 on = other._isnan()
2747 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00002748 if on == 1 and sn == 0:
2749 return self._fix(context)
2750 if sn == 1 and on == 0:
2751 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002752 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002753
Christian Heimes77c02eb2008-02-09 02:18:51 +00002754 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002755 if c == 0:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002756 c = self.compare_total(other)
2757
2758 if c == -1:
2759 ans = self
2760 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002761 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002762
Christian Heimes2c181612007-12-17 20:04:13 +00002763 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002764
2765 def _isinteger(self):
2766 """Returns whether self is an integer"""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002767 if self._is_special:
2768 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002769 if self._exp >= 0:
2770 return True
2771 rest = self._int[self._exp:]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002772 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002773
2774 def _iseven(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002775 """Returns True if self is even. Assumes self is an integer."""
2776 if not self or self._exp > 0:
2777 return True
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002778 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002779
2780 def adjusted(self):
2781 """Return the adjusted exponent of self"""
2782 try:
2783 return self._exp + len(self._int) - 1
Guido van Rossumd8faa362007-04-27 19:54:29 +00002784 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002785 except TypeError:
2786 return 0
2787
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002788 def canonical(self, context=None):
2789 """Returns the same Decimal object.
2790
2791 As we do not have different encodings for the same number, the
2792 received object already is in its canonical form.
2793 """
2794 return self
2795
2796 def compare_signal(self, other, context=None):
2797 """Compares self to the other operand numerically.
2798
2799 It's pretty much like compare(), but all NaNs signal, with signaling
2800 NaNs taking precedence over quiet NaNs.
2801 """
Christian Heimes77c02eb2008-02-09 02:18:51 +00002802 other = _convert_other(other, raiseit = True)
2803 ans = self._compare_check_nans(other, context)
2804 if ans:
2805 return ans
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002806 return self.compare(other, context=context)
2807
2808 def compare_total(self, other):
2809 """Compares self to other using the abstract representations.
2810
2811 This is not like the standard compare, which use their numerical
2812 value. Note that a total ordering is defined for all possible abstract
2813 representations.
2814 """
2815 # if one is negative and the other is positive, it's easy
2816 if self._sign and not other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002817 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002818 if not self._sign and other._sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002819 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002820 sign = self._sign
2821
2822 # let's handle both NaN types
2823 self_nan = self._isnan()
2824 other_nan = other._isnan()
2825 if self_nan or other_nan:
2826 if self_nan == other_nan:
2827 if self._int < other._int:
2828 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002829 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002830 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002831 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002832 if self._int > other._int:
2833 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002834 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002835 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002836 return _One
2837 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002838
2839 if sign:
2840 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002841 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002842 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002843 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002844 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002845 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002846 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002847 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002848 else:
2849 if self_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002850 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002851 if other_nan == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002852 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002853 if self_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002854 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002855 if other_nan == 2:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002856 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002857
2858 if self < other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002859 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002860 if self > other:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002861 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002862
2863 if self._exp < other._exp:
2864 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002865 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002866 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002867 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002868 if self._exp > other._exp:
2869 if sign:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002870 return _NegativeOne
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002871 else:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002872 return _One
2873 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002874
2875
2876 def compare_total_mag(self, other):
2877 """Compares self to other using abstract repr., ignoring sign.
2878
2879 Like compare_total, but with operand's sign ignored and assumed to be 0.
2880 """
2881 s = self.copy_abs()
2882 o = other.copy_abs()
2883 return s.compare_total(o)
2884
2885 def copy_abs(self):
2886 """Returns a copy with the sign set to 0. """
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002887 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002888
2889 def copy_negate(self):
2890 """Returns a copy with the sign inverted."""
2891 if self._sign:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002892 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002893 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002894 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002895
2896 def copy_sign(self, other):
2897 """Returns self with the sign of other."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002898 return _dec_from_triple(other._sign, self._int,
2899 self._exp, self._is_special)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002900
2901 def exp(self, context=None):
2902 """Returns e ** self."""
2903
2904 if context is None:
2905 context = getcontext()
2906
2907 # exp(NaN) = NaN
2908 ans = self._check_nans(context=context)
2909 if ans:
2910 return ans
2911
2912 # exp(-Infinity) = 0
2913 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002914 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002915
2916 # exp(0) = 1
2917 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00002918 return _One
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002919
2920 # exp(Infinity) = Infinity
2921 if self._isinfinity() == 1:
2922 return Decimal(self)
2923
2924 # the result is now guaranteed to be inexact (the true
2925 # mathematical result is transcendental). There's no need to
2926 # raise Rounded and Inexact here---they'll always be raised as
2927 # a result of the call to _fix.
2928 p = context.prec
2929 adj = self.adjusted()
2930
2931 # we only need to do any computation for quite a small range
2932 # of adjusted exponents---for example, -29 <= adj <= 10 for
2933 # the default context. For smaller exponent the result is
2934 # indistinguishable from 1 at the given precision, while for
2935 # larger exponent the result either overflows or underflows.
2936 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2937 # overflow
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002938 ans = _dec_from_triple(0, '1', context.Emax+1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002939 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2940 # underflow to 0
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002941 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002942 elif self._sign == 0 and adj < -p:
2943 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002944 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002945 elif self._sign == 1 and adj < -p-1:
2946 # p+1 digits; final round will raise correct flags
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002947 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002948 # general case
2949 else:
2950 op = _WorkRep(self)
2951 c, e = op.int, op.exp
2952 if op.sign == 1:
2953 c = -c
2954
2955 # compute correctly rounded result: increase precision by
2956 # 3 digits at a time until we get an unambiguously
2957 # roundable result
2958 extra = 3
2959 while True:
2960 coeff, exp = _dexp(c, e, p+extra)
2961 if coeff % (5*10**(len(str(coeff))-p-1)):
2962 break
2963 extra += 3
2964
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002965 ans = _dec_from_triple(0, str(coeff), exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002966
2967 # at this stage, ans should round correctly with *any*
2968 # rounding mode, not just with ROUND_HALF_EVEN
2969 context = context._shallow_copy()
2970 rounding = context._set_rounding(ROUND_HALF_EVEN)
2971 ans = ans._fix(context)
2972 context.rounding = rounding
2973
2974 return ans
2975
2976 def is_canonical(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002977 """Return True if self is canonical; otherwise return False.
2978
2979 Currently, the encoding of a Decimal instance is always
2980 canonical, so this method returns True for any Decimal.
2981 """
2982 return True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002983
2984 def is_finite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002985 """Return True if self is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002986
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002987 A Decimal instance is considered finite if it is neither
2988 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002989 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002990 return not self._is_special
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002991
2992 def is_infinite(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002993 """Return True if self is infinite; otherwise return False."""
2994 return self._exp == 'F'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002995
2996 def is_nan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002997 """Return True if self is a qNaN or sNaN; otherwise return False."""
2998 return self._exp in ('n', 'N')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002999
3000 def is_normal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003001 """Return True if self is a normal number; otherwise return False."""
3002 if self._is_special or not self:
3003 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003004 if context is None:
3005 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003006 return context.Emin <= self.adjusted() <= context.Emax
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003007
3008 def is_qnan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003009 """Return True if self is a quiet NaN; otherwise return False."""
3010 return self._exp == 'n'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003011
3012 def is_signed(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003013 """Return True if self is negative; otherwise return False."""
3014 return self._sign == 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003015
3016 def is_snan(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003017 """Return True if self is a signaling NaN; otherwise return False."""
3018 return self._exp == 'N'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003019
3020 def is_subnormal(self, context=None):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003021 """Return True if self is subnormal; otherwise return False."""
3022 if self._is_special or not self:
3023 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003024 if context is None:
3025 context = getcontext()
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003026 return self.adjusted() < context.Emin
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003027
3028 def is_zero(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003029 """Return True if self is a zero; otherwise return False."""
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003030 return not self._is_special and self._int == '0'
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003031
3032 def _ln_exp_bound(self):
3033 """Compute a lower bound for the adjusted exponent of self.ln().
3034 In other words, compute r such that self.ln() >= 10**r. Assumes
3035 that self is finite and positive and that self != 1.
3036 """
3037
3038 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
3039 adj = self._exp + len(self._int) - 1
3040 if adj >= 1:
3041 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
3042 return len(str(adj*23//10)) - 1
3043 if adj <= -2:
3044 # argument <= 0.1
3045 return len(str((-1-adj)*23//10)) - 1
3046 op = _WorkRep(self)
3047 c, e = op.int, op.exp
3048 if adj == 0:
3049 # 1 < self < 10
3050 num = str(c-10**-e)
3051 den = str(c)
3052 return len(num) - len(den) - (num < den)
3053 # adj == -1, 0.1 <= self < 1
3054 return e + len(str(10**-e - c)) - 1
3055
3056
3057 def ln(self, context=None):
3058 """Returns the natural (base e) logarithm of self."""
3059
3060 if context is None:
3061 context = getcontext()
3062
3063 # ln(NaN) = NaN
3064 ans = self._check_nans(context=context)
3065 if ans:
3066 return ans
3067
3068 # ln(0.0) == -Infinity
3069 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003070 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003071
3072 # ln(Infinity) = Infinity
3073 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003074 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003075
3076 # ln(1.0) == 0.0
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003077 if self == _One:
3078 return _Zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003079
3080 # ln(negative) raises InvalidOperation
3081 if self._sign == 1:
3082 return context._raise_error(InvalidOperation,
3083 'ln of a negative value')
3084
3085 # result is irrational, so necessarily inexact
3086 op = _WorkRep(self)
3087 c, e = op.int, op.exp
3088 p = context.prec
3089
3090 # correctly rounded result: repeatedly increase precision by 3
3091 # until we get an unambiguously roundable result
3092 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3093 while True:
3094 coeff = _dlog(c, e, places)
3095 # assert len(str(abs(coeff)))-p >= 1
3096 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3097 break
3098 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003099 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003100
3101 context = context._shallow_copy()
3102 rounding = context._set_rounding(ROUND_HALF_EVEN)
3103 ans = ans._fix(context)
3104 context.rounding = rounding
3105 return ans
3106
3107 def _log10_exp_bound(self):
3108 """Compute a lower bound for the adjusted exponent of self.log10().
3109 In other words, find r such that self.log10() >= 10**r.
3110 Assumes that self is finite and positive and that self != 1.
3111 """
3112
3113 # For x >= 10 or x < 0.1 we only need a bound on the integer
3114 # part of log10(self), and this comes directly from the
3115 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3116 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3117 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3118
3119 adj = self._exp + len(self._int) - 1
3120 if adj >= 1:
3121 # self >= 10
3122 return len(str(adj))-1
3123 if adj <= -2:
3124 # self < 0.1
3125 return len(str(-1-adj))-1
3126 op = _WorkRep(self)
3127 c, e = op.int, op.exp
3128 if adj == 0:
3129 # 1 < self < 10
3130 num = str(c-10**-e)
3131 den = str(231*c)
3132 return len(num) - len(den) - (num < den) + 2
3133 # adj == -1, 0.1 <= self < 1
3134 num = str(10**-e-c)
3135 return len(num) + e - (num < "231") - 1
3136
3137 def log10(self, context=None):
3138 """Returns the base 10 logarithm of self."""
3139
3140 if context is None:
3141 context = getcontext()
3142
3143 # log10(NaN) = NaN
3144 ans = self._check_nans(context=context)
3145 if ans:
3146 return ans
3147
3148 # log10(0.0) == -Infinity
3149 if not self:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003150 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003151
3152 # log10(Infinity) = Infinity
3153 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003154 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003155
3156 # log10(negative or -Infinity) raises InvalidOperation
3157 if self._sign == 1:
3158 return context._raise_error(InvalidOperation,
3159 'log10 of a negative value')
3160
3161 # log10(10**n) = n
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003162 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003163 # answer may need rounding
3164 ans = Decimal(self._exp + len(self._int) - 1)
3165 else:
3166 # result is irrational, so necessarily inexact
3167 op = _WorkRep(self)
3168 c, e = op.int, op.exp
3169 p = context.prec
3170
3171 # correctly rounded result: repeatedly increase precision
3172 # until result is unambiguously roundable
3173 places = p-self._log10_exp_bound()+2
3174 while True:
3175 coeff = _dlog10(c, e, places)
3176 # assert len(str(abs(coeff)))-p >= 1
3177 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3178 break
3179 places += 3
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003180 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003181
3182 context = context._shallow_copy()
3183 rounding = context._set_rounding(ROUND_HALF_EVEN)
3184 ans = ans._fix(context)
3185 context.rounding = rounding
3186 return ans
3187
3188 def logb(self, context=None):
3189 """ Returns the exponent of the magnitude of self's MSD.
3190
3191 The result is the integer which is the exponent of the magnitude
3192 of the most significant digit of self (as though it were truncated
3193 to a single digit while maintaining the value of that digit and
3194 without limiting the resulting exponent).
3195 """
3196 # logb(NaN) = NaN
3197 ans = self._check_nans(context=context)
3198 if ans:
3199 return ans
3200
3201 if context is None:
3202 context = getcontext()
3203
3204 # logb(+/-Inf) = +Inf
3205 if self._isinfinity():
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003206 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003207
3208 # logb(0) = -Inf, DivisionByZero
3209 if not self:
3210 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3211
3212 # otherwise, simply return the adjusted exponent of self, as a
3213 # Decimal. Note that no attempt is made to fit the result
3214 # into the current context.
3215 return Decimal(self.adjusted())
3216
3217 def _islogical(self):
3218 """Return True if self is a logical operand.
3219
Christian Heimes679db4a2008-01-18 09:56:22 +00003220 For being logical, it must be a finite number with a sign of 0,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003221 an exponent of 0, and a coefficient whose digits must all be
3222 either 0 or 1.
3223 """
3224 if self._sign != 0 or self._exp != 0:
3225 return False
3226 for dig in self._int:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003227 if dig not in '01':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003228 return False
3229 return True
3230
3231 def _fill_logical(self, context, opa, opb):
3232 dif = context.prec - len(opa)
3233 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003234 opa = '0'*dif + opa
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003235 elif dif < 0:
3236 opa = opa[-context.prec:]
3237 dif = context.prec - len(opb)
3238 if dif > 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003239 opb = '0'*dif + opb
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003240 elif dif < 0:
3241 opb = opb[-context.prec:]
3242 return opa, opb
3243
3244 def logical_and(self, other, context=None):
3245 """Applies an 'and' operation between self and other's digits."""
3246 if context is None:
3247 context = getcontext()
3248 if not self._islogical() or not other._islogical():
3249 return context._raise_error(InvalidOperation)
3250
3251 # fill to context.prec
3252 (opa, opb) = self._fill_logical(context, self._int, other._int)
3253
3254 # make the operation, and clean starting zeroes
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003255 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3256 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003257
3258 def logical_invert(self, context=None):
3259 """Invert all its digits."""
3260 if context is None:
3261 context = getcontext()
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003262 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3263 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003264
3265 def logical_or(self, other, context=None):
3266 """Applies an 'or' operation between self and other's digits."""
3267 if context is None:
3268 context = getcontext()
3269 if not self._islogical() or not other._islogical():
3270 return context._raise_error(InvalidOperation)
3271
3272 # fill to context.prec
3273 (opa, opb) = self._fill_logical(context, self._int, other._int)
3274
3275 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003276 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003277 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003278
3279 def logical_xor(self, other, context=None):
3280 """Applies an 'xor' operation between self and other's digits."""
3281 if context is None:
3282 context = getcontext()
3283 if not self._islogical() or not other._islogical():
3284 return context._raise_error(InvalidOperation)
3285
3286 # fill to context.prec
3287 (opa, opb) = self._fill_logical(context, self._int, other._int)
3288
3289 # make the operation, and clean starting zeroes
Mark Dickinson315a20a2009-01-04 21:34:18 +00003290 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003291 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003292
3293 def max_mag(self, other, context=None):
3294 """Compares the values numerically with their sign ignored."""
3295 other = _convert_other(other, raiseit=True)
3296
3297 if context is None:
3298 context = getcontext()
3299
3300 if self._is_special or other._is_special:
3301 # If one operand is a quiet NaN and the other is number, then the
3302 # number is always returned
3303 sn = self._isnan()
3304 on = other._isnan()
3305 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003306 if on == 1 and sn == 0:
3307 return self._fix(context)
3308 if sn == 1 and on == 0:
3309 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003310 return self._check_nans(other, context)
3311
Christian Heimes77c02eb2008-02-09 02:18:51 +00003312 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003313 if c == 0:
3314 c = self.compare_total(other)
3315
3316 if c == -1:
3317 ans = other
3318 else:
3319 ans = self
3320
Christian Heimes2c181612007-12-17 20:04:13 +00003321 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003322
3323 def min_mag(self, other, context=None):
3324 """Compares the values numerically with their sign ignored."""
3325 other = _convert_other(other, raiseit=True)
3326
3327 if context is None:
3328 context = getcontext()
3329
3330 if self._is_special or other._is_special:
3331 # If one operand is a quiet NaN and the other is number, then the
3332 # number is always returned
3333 sn = self._isnan()
3334 on = other._isnan()
3335 if sn or on:
Facundo Batista708d5812008-12-11 04:20:07 +00003336 if on == 1 and sn == 0:
3337 return self._fix(context)
3338 if sn == 1 and on == 0:
3339 return other._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003340 return self._check_nans(other, context)
3341
Christian Heimes77c02eb2008-02-09 02:18:51 +00003342 c = self.copy_abs()._cmp(other.copy_abs())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003343 if c == 0:
3344 c = self.compare_total(other)
3345
3346 if c == -1:
3347 ans = self
3348 else:
3349 ans = other
3350
Christian Heimes2c181612007-12-17 20:04:13 +00003351 return ans._fix(context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003352
3353 def next_minus(self, context=None):
3354 """Returns the largest representable number smaller than itself."""
3355 if context is None:
3356 context = getcontext()
3357
3358 ans = self._check_nans(context=context)
3359 if ans:
3360 return ans
3361
3362 if self._isinfinity() == -1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003363 return _NegativeInfinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003364 if self._isinfinity() == 1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003365 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003366
3367 context = context.copy()
3368 context._set_rounding(ROUND_FLOOR)
3369 context._ignore_all_flags()
3370 new_self = self._fix(context)
3371 if new_self != self:
3372 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003373 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3374 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003375
3376 def next_plus(self, context=None):
3377 """Returns the smallest representable number larger than itself."""
3378 if context is None:
3379 context = getcontext()
3380
3381 ans = self._check_nans(context=context)
3382 if ans:
3383 return ans
3384
3385 if self._isinfinity() == 1:
Mark Dickinson627cf6a2009-01-03 12:11:47 +00003386 return _Infinity
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003387 if self._isinfinity() == -1:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003388 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003389
3390 context = context.copy()
3391 context._set_rounding(ROUND_CEILING)
3392 context._ignore_all_flags()
3393 new_self = self._fix(context)
3394 if new_self != self:
3395 return new_self
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003396 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3397 context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003398
3399 def next_toward(self, other, context=None):
3400 """Returns the number closest to self, in the direction towards other.
3401
3402 The result is the closest representable number to self
3403 (excluding self) that is in the direction towards other,
3404 unless both have the same value. If the two operands are
3405 numerically equal, then the result is a copy of self with the
3406 sign set to be the same as the sign of other.
3407 """
3408 other = _convert_other(other, raiseit=True)
3409
3410 if context is None:
3411 context = getcontext()
3412
3413 ans = self._check_nans(other, context)
3414 if ans:
3415 return ans
3416
Christian Heimes77c02eb2008-02-09 02:18:51 +00003417 comparison = self._cmp(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003418 if comparison == 0:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003419 return self.copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003420
3421 if comparison == -1:
3422 ans = self.next_plus(context)
3423 else: # comparison == 1
3424 ans = self.next_minus(context)
3425
3426 # decide which flags to raise using value of ans
3427 if ans._isinfinity():
3428 context._raise_error(Overflow,
3429 'Infinite result from next_toward',
3430 ans._sign)
3431 context._raise_error(Rounded)
3432 context._raise_error(Inexact)
3433 elif ans.adjusted() < context.Emin:
3434 context._raise_error(Underflow)
3435 context._raise_error(Subnormal)
3436 context._raise_error(Rounded)
3437 context._raise_error(Inexact)
3438 # if precision == 1 then we don't raise Clamped for a
3439 # result 0E-Etiny.
3440 if not ans:
3441 context._raise_error(Clamped)
3442
3443 return ans
3444
3445 def number_class(self, context=None):
3446 """Returns an indication of the class of self.
3447
3448 The class is one of the following strings:
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003449 sNaN
3450 NaN
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003451 -Infinity
3452 -Normal
3453 -Subnormal
3454 -Zero
3455 +Zero
3456 +Subnormal
3457 +Normal
3458 +Infinity
3459 """
3460 if self.is_snan():
3461 return "sNaN"
3462 if self.is_qnan():
3463 return "NaN"
3464 inf = self._isinfinity()
3465 if inf == 1:
3466 return "+Infinity"
3467 if inf == -1:
3468 return "-Infinity"
3469 if self.is_zero():
3470 if self._sign:
3471 return "-Zero"
3472 else:
3473 return "+Zero"
3474 if context is None:
3475 context = getcontext()
3476 if self.is_subnormal(context=context):
3477 if self._sign:
3478 return "-Subnormal"
3479 else:
3480 return "+Subnormal"
3481 # just a normal, regular, boring number, :)
3482 if self._sign:
3483 return "-Normal"
3484 else:
3485 return "+Normal"
3486
3487 def radix(self):
3488 """Just returns 10, as this is Decimal, :)"""
3489 return Decimal(10)
3490
3491 def rotate(self, other, context=None):
3492 """Returns a rotated copy of self, value-of-other times."""
3493 if context is None:
3494 context = getcontext()
3495
3496 ans = self._check_nans(other, context)
3497 if ans:
3498 return ans
3499
3500 if other._exp != 0:
3501 return context._raise_error(InvalidOperation)
3502 if not (-context.prec <= int(other) <= context.prec):
3503 return context._raise_error(InvalidOperation)
3504
3505 if self._isinfinity():
3506 return Decimal(self)
3507
3508 # get values, pad if necessary
3509 torot = int(other)
3510 rotdig = self._int
3511 topad = context.prec - len(rotdig)
3512 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003513 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003514
3515 # let's rotate!
3516 rotated = rotdig[torot:] + rotdig[:torot]
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003517 return _dec_from_triple(self._sign,
3518 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003519
3520 def scaleb (self, other, context=None):
3521 """Returns self operand after adding the second value to its exp."""
3522 if context is None:
3523 context = getcontext()
3524
3525 ans = self._check_nans(other, context)
3526 if ans:
3527 return ans
3528
3529 if other._exp != 0:
3530 return context._raise_error(InvalidOperation)
3531 liminf = -2 * (context.Emax + context.prec)
3532 limsup = 2 * (context.Emax + context.prec)
3533 if not (liminf <= int(other) <= limsup):
3534 return context._raise_error(InvalidOperation)
3535
3536 if self._isinfinity():
3537 return Decimal(self)
3538
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003539 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003540 d = d._fix(context)
3541 return d
3542
3543 def shift(self, other, context=None):
3544 """Returns a shifted copy of self, value-of-other times."""
3545 if context is None:
3546 context = getcontext()
3547
3548 ans = self._check_nans(other, context)
3549 if ans:
3550 return ans
3551
3552 if other._exp != 0:
3553 return context._raise_error(InvalidOperation)
3554 if not (-context.prec <= int(other) <= context.prec):
3555 return context._raise_error(InvalidOperation)
3556
3557 if self._isinfinity():
3558 return Decimal(self)
3559
3560 # get values, pad if necessary
3561 torot = int(other)
3562 if not torot:
3563 return Decimal(self)
3564 rotdig = self._int
3565 topad = context.prec - len(rotdig)
3566 if topad:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003567 rotdig = '0'*topad + rotdig
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003568
3569 # let's shift!
3570 if torot < 0:
3571 rotated = rotdig[:torot]
3572 else:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003573 rotated = rotdig + '0'*torot
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003574 rotated = rotated[-context.prec:]
3575
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003576 return _dec_from_triple(self._sign,
3577 rotated.lstrip('0') or '0', self._exp)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003578
Guido van Rossumd8faa362007-04-27 19:54:29 +00003579 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003580 def __reduce__(self):
3581 return (self.__class__, (str(self),))
3582
3583 def __copy__(self):
3584 if type(self) == Decimal:
3585 return self # I'm immutable; therefore I am my own clone
3586 return self.__class__(str(self))
3587
3588 def __deepcopy__(self, memo):
3589 if type(self) == Decimal:
3590 return self # My components are also immutable
3591 return self.__class__(str(self))
3592
Christian Heimesf16baeb2008-02-29 14:57:44 +00003593 # PEP 3101 support. See also _parse_format_specifier and _format_align
3594 def __format__(self, specifier, context=None):
3595 """Format a Decimal instance according to the given specifier.
3596
3597 The specifier should be a standard format specifier, with the
3598 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3599 'F', 'g', 'G', and '%' are supported. If the formatting type
3600 is omitted it defaults to 'g' or 'G', depending on the value
3601 of context.capitals.
3602
3603 At this time the 'n' format specifier type (which is supposed
3604 to use the current locale) is not supported.
3605 """
3606
3607 # Note: PEP 3101 says that if the type is not present then
3608 # there should be at least one digit after the decimal point.
3609 # We take the liberty of ignoring this requirement for
3610 # Decimal---it's presumably there to make sure that
3611 # format(float, '') behaves similarly to str(float).
3612 if context is None:
3613 context = getcontext()
3614
3615 spec = _parse_format_specifier(specifier)
3616
3617 # special values don't care about the type or precision...
3618 if self._is_special:
3619 return _format_align(str(self), spec)
3620
3621 # a type of None defaults to 'g' or 'G', depending on context
3622 # if type is '%', adjust exponent of self accordingly
3623 if spec['type'] is None:
3624 spec['type'] = ['g', 'G'][context.capitals]
3625 elif spec['type'] == '%':
3626 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3627
3628 # round if necessary, taking rounding mode from the context
3629 rounding = context.rounding
3630 precision = spec['precision']
3631 if precision is not None:
3632 if spec['type'] in 'eE':
3633 self = self._round(precision+1, rounding)
3634 elif spec['type'] in 'gG':
3635 if len(self._int) > precision:
3636 self = self._round(precision, rounding)
3637 elif spec['type'] in 'fF%':
3638 self = self._rescale(-precision, rounding)
3639 # special case: zeros with a positive exponent can't be
3640 # represented in fixed point; rescale them to 0e0.
3641 elif not self and self._exp > 0 and spec['type'] in 'fF%':
3642 self = self._rescale(0, rounding)
3643
3644 # figure out placement of the decimal point
3645 leftdigits = self._exp + len(self._int)
3646 if spec['type'] in 'fF%':
3647 dotplace = leftdigits
3648 elif spec['type'] in 'eE':
3649 if not self and precision is not None:
3650 dotplace = 1 - precision
3651 else:
3652 dotplace = 1
3653 elif spec['type'] in 'gG':
3654 if self._exp <= 0 and leftdigits > -6:
3655 dotplace = leftdigits
3656 else:
3657 dotplace = 1
3658
3659 # figure out main part of numeric string...
3660 if dotplace <= 0:
3661 num = '0.' + '0'*(-dotplace) + self._int
3662 elif dotplace >= len(self._int):
3663 # make sure we're not padding a '0' with extra zeros on the right
3664 assert dotplace==len(self._int) or self._int != '0'
3665 num = self._int + '0'*(dotplace-len(self._int))
3666 else:
3667 num = self._int[:dotplace] + '.' + self._int[dotplace:]
3668
3669 # ...then the trailing exponent, or trailing '%'
3670 if leftdigits != dotplace or spec['type'] in 'eE':
3671 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3672 num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3673 elif spec['type'] == '%':
3674 num = num + '%'
3675
3676 # add sign
3677 if self._sign == 1:
3678 num = '-' + num
3679 return _format_align(num, spec)
3680
3681
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00003682def _dec_from_triple(sign, coefficient, exponent, special=False):
3683 """Create a decimal instance directly, without any validation,
3684 normalization (e.g. removal of leading zeros) or argument
3685 conversion.
3686
3687 This function is for *internal use only*.
3688 """
3689
3690 self = object.__new__(Decimal)
3691 self._sign = sign
3692 self._int = coefficient
3693 self._exp = exponent
3694 self._is_special = special
3695
3696 return self
3697
Guido van Rossumd8faa362007-04-27 19:54:29 +00003698##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003699
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003700
3701# get rounding method function:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003702rounding_functions = [name for name in Decimal.__dict__.keys()
3703 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003704for name in rounding_functions:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003705 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003706 globalname = name[1:].upper()
3707 val = globals()[globalname]
3708 Decimal._pick_rounding_function[val] = name
3709
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003710del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003711
Thomas Wouters89f507f2006-12-13 04:49:30 +00003712class _ContextManager(object):
3713 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003714
Thomas Wouters89f507f2006-12-13 04:49:30 +00003715 Sets a copy of the supplied context in __enter__() and restores
3716 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003717 """
3718 def __init__(self, new_context):
Thomas Wouters89f507f2006-12-13 04:49:30 +00003719 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003720 def __enter__(self):
3721 self.saved_context = getcontext()
3722 setcontext(self.new_context)
3723 return self.new_context
3724 def __exit__(self, t, v, tb):
3725 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003726
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003727class Context(object):
3728 """Contains the context for a Decimal instance.
3729
3730 Contains:
3731 prec - precision (for use in rounding, division, square roots..)
Guido van Rossumd8faa362007-04-27 19:54:29 +00003732 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003733 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003734 raised when it is caused. Otherwise, a value is
3735 substituted in.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003736 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003737 (Whether or not the trap_enabler is set)
3738 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003739 Emin - Minimum exponent
3740 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003741 capitals - If 1, 1*10^1 is printed as 1E+1.
3742 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003743 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003744 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003745
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003746 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003747 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003748 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003749 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003750 _ignored_flags=None):
3751 if flags is None:
3752 flags = []
3753 if _ignored_flags is None:
3754 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003755 if not isinstance(flags, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003756 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerbf440692004-07-10 14:14:37 +00003757 if traps is not None and not isinstance(traps, dict):
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003758 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003759 for name, val in locals().items():
3760 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003761 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003762 else:
3763 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003764 del self.self
3765
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003766 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003767 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003768 s = []
Guido van Rossumd8faa362007-04-27 19:54:29 +00003769 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3770 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3771 % vars(self))
3772 names = [f.__name__ for f, v in self.flags.items() if v]
3773 s.append('flags=[' + ', '.join(names) + ']')
3774 names = [t.__name__ for t, v in self.traps.items() if v]
3775 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003776 return ', '.join(s) + ')'
3777
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003778 def clear_flags(self):
3779 """Reset all flags to zero"""
3780 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003781 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003782
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003783 def _shallow_copy(self):
3784 """Returns a shallow copy from self."""
Christian Heimes2c181612007-12-17 20:04:13 +00003785 nc = Context(self.prec, self.rounding, self.traps,
3786 self.flags, self.Emin, self.Emax,
3787 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003788 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003789
3790 def copy(self):
3791 """Returns a deep copy from self."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00003792 nc = Context(self.prec, self.rounding, self.traps.copy(),
Christian Heimes2c181612007-12-17 20:04:13 +00003793 self.flags.copy(), self.Emin, self.Emax,
3794 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003795 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003796 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003797
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003798 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003799 """Handles an error
3800
3801 If the flag is in _ignored_flags, returns the default response.
Raymond Hettinger86173da2008-02-01 20:38:12 +00003802 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003803 trap_enabler is set, it reaises the exception. Otherwise, it returns
Raymond Hettinger86173da2008-02-01 20:38:12 +00003804 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003805 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003806 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003807 if error in self._ignored_flags:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003808 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003809 return error().handle(self, *args)
3810
Raymond Hettinger86173da2008-02-01 20:38:12 +00003811 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003812 if not self.traps[error]:
Guido van Rossumd8faa362007-04-27 19:54:29 +00003813 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003814 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003815
3816 # Errors should only be risked on copies of the context
Guido van Rossumd8faa362007-04-27 19:54:29 +00003817 # self._ignored_flags = []
Collin Winterce36ad82007-08-30 01:19:48 +00003818 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003819
3820 def _ignore_all_flags(self):
3821 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003822 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003823
3824 def _ignore_flags(self, *flags):
3825 """Ignore the flags, if they are raised"""
3826 # Do not mutate-- This way, copies of a context leave the original
3827 # alone.
3828 self._ignored_flags = (self._ignored_flags + list(flags))
3829 return list(flags)
3830
3831 def _regard_flags(self, *flags):
3832 """Stop ignoring the flags, if they are raised"""
3833 if flags and isinstance(flags[0], (tuple,list)):
3834 flags = flags[0]
3835 for flag in flags:
3836 self._ignored_flags.remove(flag)
3837
Nick Coghland1abd252008-07-15 15:46:38 +00003838 # We inherit object.__hash__, so we must deny this explicitly
3839 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003840
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003841 def Etiny(self):
3842 """Returns Etiny (= Emin - prec + 1)"""
3843 return int(self.Emin - self.prec + 1)
3844
3845 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003846 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003847 return int(self.Emax - self.prec + 1)
3848
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003849 def _set_rounding(self, type):
3850 """Sets the rounding type.
3851
3852 Sets the rounding type, and returns the current (previous)
3853 rounding type. Often used like:
3854
3855 context = context.copy()
3856 # so you don't change the calling context
3857 # if an error occurs in the middle.
3858 rounding = context._set_rounding(ROUND_UP)
3859 val = self.__sub__(other, context=context)
3860 context._set_rounding(rounding)
3861
3862 This will make it round up for that operation.
3863 """
3864 rounding = self.rounding
3865 self.rounding= type
3866 return rounding
3867
Raymond Hettingerfed52962004-07-14 15:41:57 +00003868 def create_decimal(self, num='0'):
Christian Heimesa62da1d2008-01-12 19:39:10 +00003869 """Creates a new Decimal instance but using self as context.
3870
3871 This method implements the to-number operation of the
3872 IBM Decimal specification."""
3873
3874 if isinstance(num, str) and num != num.strip():
3875 return self._raise_error(ConversionSyntax,
3876 "no trailing or leading whitespace is "
3877 "permitted.")
3878
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003879 d = Decimal(num, context=self)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003880 if d._isnan() and len(d._int) > self.prec - self._clamp:
3881 return self._raise_error(ConversionSyntax,
3882 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003883 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003884
Raymond Hettinger771ed762009-01-03 19:20:32 +00003885 def create_decimal_from_float(self, f):
3886 """Creates a new Decimal instance from a float but rounding using self
3887 as the context.
3888
3889 >>> context = Context(prec=5, rounding=ROUND_DOWN)
3890 >>> context.create_decimal_from_float(3.1415926535897932)
3891 Decimal('3.1415')
3892 >>> context = Context(prec=5, traps=[Inexact])
3893 >>> context.create_decimal_from_float(3.1415926535897932)
3894 Traceback (most recent call last):
3895 ...
3896 decimal.Inexact: None
3897
3898 """
3899 d = Decimal.from_float(f) # An exact conversion
3900 return d._fix(self) # Apply the context rounding
3901
Guido van Rossumd8faa362007-04-27 19:54:29 +00003902 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003903 def abs(self, a):
3904 """Returns the absolute value of the operand.
3905
3906 If the operand is negative, the result is the same as using the minus
Guido van Rossumd8faa362007-04-27 19:54:29 +00003907 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003908 the plus operation on the operand.
3909
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003910 >>> ExtendedContext.abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003911 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003912 >>> ExtendedContext.abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003913 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003914 >>> ExtendedContext.abs(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003915 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003916 >>> ExtendedContext.abs(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003917 Decimal('101.5')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003918 """
3919 return a.__abs__(context=self)
3920
3921 def add(self, a, b):
3922 """Return the sum of the two operands.
3923
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003924 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003925 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003926 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003927 Decimal('1.02E+4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003928 """
3929 return a.__add__(b, context=self)
3930
3931 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003932 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003933
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003934 def canonical(self, a):
3935 """Returns the same Decimal object.
3936
3937 As we do not have different encodings for the same number, the
3938 received object already is in its canonical form.
3939
3940 >>> ExtendedContext.canonical(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003941 Decimal('2.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003942 """
3943 return a.canonical(context=self)
3944
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003945 def compare(self, a, b):
3946 """Compares values numerically.
3947
3948 If the signs of the operands differ, a value representing each operand
3949 ('-1' if the operand is less than zero, '0' if the operand is zero or
3950 negative zero, or '1' if the operand is greater than zero) is used in
3951 place of that operand for the comparison instead of the actual
3952 operand.
3953
3954 The comparison is then effected by subtracting the second operand from
3955 the first and then returning a value according to the result of the
3956 subtraction: '-1' if the result is less than zero, '0' if the result is
3957 zero or negative zero, or '1' if the result is greater than zero.
3958
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003959 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003960 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003961 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003962 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003963 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003964 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003965 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003966 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003967 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003968 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003969 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003970 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003971 """
3972 return a.compare(b, context=self)
3973
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003974 def compare_signal(self, a, b):
3975 """Compares the values of the two operands numerically.
3976
3977 It's pretty much like compare(), but all NaNs signal, with signaling
3978 NaNs taking precedence over quiet NaNs.
3979
3980 >>> c = ExtendedContext
3981 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003982 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003983 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003984 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003985 >>> c.flags[InvalidOperation] = 0
3986 >>> print(c.flags[InvalidOperation])
3987 0
3988 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003989 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003990 >>> print(c.flags[InvalidOperation])
3991 1
3992 >>> c.flags[InvalidOperation] = 0
3993 >>> print(c.flags[InvalidOperation])
3994 0
3995 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00003996 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003997 >>> print(c.flags[InvalidOperation])
3998 1
3999 """
4000 return a.compare_signal(b, context=self)
4001
4002 def compare_total(self, a, b):
4003 """Compares two operands using their abstract representation.
4004
4005 This is not like the standard compare, which use their numerical
4006 value. Note that a total ordering is defined for all possible abstract
4007 representations.
4008
4009 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004010 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004011 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004012 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004013 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004014 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004015 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004016 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004017 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004018 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004019 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004020 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004021 """
4022 return a.compare_total(b)
4023
4024 def compare_total_mag(self, a, b):
4025 """Compares two operands using their abstract representation ignoring sign.
4026
4027 Like compare_total, but with operand's sign ignored and assumed to be 0.
4028 """
4029 return a.compare_total_mag(b)
4030
4031 def copy_abs(self, a):
4032 """Returns a copy of the operand with the sign set to 0.
4033
4034 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004035 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004036 >>> ExtendedContext.copy_abs(Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004037 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004038 """
4039 return a.copy_abs()
4040
4041 def copy_decimal(self, a):
4042 """Returns a copy of the decimal objet.
4043
4044 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004045 Decimal('2.1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004046 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004047 Decimal('-1.00')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004048 """
4049 return Decimal(a)
4050
4051 def copy_negate(self, a):
4052 """Returns a copy of the operand with the sign inverted.
4053
4054 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004055 Decimal('-101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004056 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004057 Decimal('101.5')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004058 """
4059 return a.copy_negate()
4060
4061 def copy_sign(self, a, b):
4062 """Copies the second operand's sign to the first one.
4063
4064 In detail, it returns a copy of the first operand with the sign
4065 equal to the sign of the second operand.
4066
4067 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004068 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004069 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004070 Decimal('1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004071 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004072 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004073 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004074 Decimal('-1.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004075 """
4076 return a.copy_sign(b)
4077
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004078 def divide(self, a, b):
4079 """Decimal division in a specified context.
4080
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004081 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004082 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004083 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004084 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004085 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004086 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004087 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004088 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004089 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004090 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004091 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004092 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004093 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004094 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004095 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004096 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004097 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004098 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004099 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004100 Decimal('1.20E+6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004101 """
Neal Norwitzbcc0db82006-03-24 08:14:36 +00004102 return a.__truediv__(b, context=self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004103
4104 def divide_int(self, a, b):
4105 """Divides two numbers and returns the integer part of the result.
4106
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004107 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004108 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004109 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004110 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004111 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004112 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004113 """
4114 return a.__floordiv__(b, context=self)
4115
4116 def divmod(self, a, b):
4117 return a.__divmod__(b, context=self)
4118
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004119 def exp(self, a):
4120 """Returns e ** a.
4121
4122 >>> c = ExtendedContext.copy()
4123 >>> c.Emin = -999
4124 >>> c.Emax = 999
4125 >>> c.exp(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004126 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004127 >>> c.exp(Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004128 Decimal('0.367879441')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004129 >>> c.exp(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004130 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004131 >>> c.exp(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004132 Decimal('2.71828183')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004133 >>> c.exp(Decimal('0.693147181'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004134 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004135 >>> c.exp(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004136 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004137 """
4138 return a.exp(context=self)
4139
4140 def fma(self, a, b, c):
4141 """Returns a multiplied by b, plus c.
4142
4143 The first two operands are multiplied together, using multiply,
4144 the third operand is then added to the result of that
4145 multiplication, using add, all with only one final rounding.
4146
4147 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004148 Decimal('22')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004149 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004150 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004151 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004152 Decimal('1.38435736E+12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004153 """
4154 return a.fma(b, c, context=self)
4155
4156 def is_canonical(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004157 """Return True if the operand is canonical; otherwise return False.
4158
4159 Currently, the encoding of a Decimal instance is always
4160 canonical, so this method returns True for any Decimal.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004161
4162 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004163 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004164 """
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004165 return a.is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004166
4167 def is_finite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004168 """Return True if the operand is finite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004169
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004170 A Decimal instance is considered finite if it is neither
4171 infinite nor a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004172
4173 >>> ExtendedContext.is_finite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004174 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004175 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004176 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004177 >>> ExtendedContext.is_finite(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004178 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004179 >>> ExtendedContext.is_finite(Decimal('Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004180 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004181 >>> ExtendedContext.is_finite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004182 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004183 """
4184 return a.is_finite()
4185
4186 def is_infinite(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004187 """Return True if the operand is infinite; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004188
4189 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004190 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004191 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004192 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004193 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004194 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004195 """
4196 return a.is_infinite()
4197
4198 def is_nan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004199 """Return True if the operand is a qNaN or sNaN;
4200 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004201
4202 >>> ExtendedContext.is_nan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004203 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004204 >>> ExtendedContext.is_nan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004205 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004206 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004207 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004208 """
4209 return a.is_nan()
4210
4211 def is_normal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004212 """Return True if the operand is a normal number;
4213 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004214
4215 >>> c = ExtendedContext.copy()
4216 >>> c.Emin = -999
4217 >>> c.Emax = 999
4218 >>> c.is_normal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004219 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004220 >>> c.is_normal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004221 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004222 >>> c.is_normal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004223 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004224 >>> c.is_normal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004225 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004226 >>> c.is_normal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004227 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004228 """
4229 return a.is_normal(context=self)
4230
4231 def is_qnan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004232 """Return True if the operand is a quiet NaN; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004233
4234 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004235 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004236 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004237 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004238 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004239 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004240 """
4241 return a.is_qnan()
4242
4243 def is_signed(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004244 """Return True if the operand is negative; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004245
4246 >>> ExtendedContext.is_signed(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004247 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004248 >>> ExtendedContext.is_signed(Decimal('-12'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004249 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004250 >>> ExtendedContext.is_signed(Decimal('-0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004251 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004252 """
4253 return a.is_signed()
4254
4255 def is_snan(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004256 """Return True if the operand is a signaling NaN;
4257 otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004258
4259 >>> ExtendedContext.is_snan(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004260 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004261 >>> ExtendedContext.is_snan(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004262 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004263 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004264 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004265 """
4266 return a.is_snan()
4267
4268 def is_subnormal(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004269 """Return True if the operand is subnormal; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004270
4271 >>> c = ExtendedContext.copy()
4272 >>> c.Emin = -999
4273 >>> c.Emax = 999
4274 >>> c.is_subnormal(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004275 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004276 >>> c.is_subnormal(Decimal('0.1E-999'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004277 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004278 >>> c.is_subnormal(Decimal('0.00'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004279 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004280 >>> c.is_subnormal(Decimal('-Inf'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004281 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004282 >>> c.is_subnormal(Decimal('NaN'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004283 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004284 """
4285 return a.is_subnormal(context=self)
4286
4287 def is_zero(self, a):
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004288 """Return True if the operand is a zero; otherwise return False.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004289
4290 >>> ExtendedContext.is_zero(Decimal('0'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004291 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004292 >>> ExtendedContext.is_zero(Decimal('2.50'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004293 False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004294 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Guido van Rossum8ce8a782007-11-01 19:42:39 +00004295 True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004296 """
4297 return a.is_zero()
4298
4299 def ln(self, a):
4300 """Returns the natural (base e) logarithm of the operand.
4301
4302 >>> c = ExtendedContext.copy()
4303 >>> c.Emin = -999
4304 >>> c.Emax = 999
4305 >>> c.ln(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004306 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004307 >>> c.ln(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004308 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004309 >>> c.ln(Decimal('2.71828183'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004310 Decimal('1.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004311 >>> c.ln(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004312 Decimal('2.30258509')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004313 >>> c.ln(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004314 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004315 """
4316 return a.ln(context=self)
4317
4318 def log10(self, a):
4319 """Returns the base 10 logarithm of the operand.
4320
4321 >>> c = ExtendedContext.copy()
4322 >>> c.Emin = -999
4323 >>> c.Emax = 999
4324 >>> c.log10(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004325 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004326 >>> c.log10(Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004327 Decimal('-3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004328 >>> c.log10(Decimal('1.000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004329 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004330 >>> c.log10(Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004331 Decimal('0.301029996')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004332 >>> c.log10(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004333 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004334 >>> c.log10(Decimal('70'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004335 Decimal('1.84509804')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004336 >>> c.log10(Decimal('+Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004337 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004338 """
4339 return a.log10(context=self)
4340
4341 def logb(self, a):
4342 """ Returns the exponent of the magnitude of the operand's MSD.
4343
4344 The result is the integer which is the exponent of the magnitude
4345 of the most significant digit of the operand (as though the
4346 operand were truncated to a single digit while maintaining the
4347 value of that digit and without limiting the resulting exponent).
4348
4349 >>> ExtendedContext.logb(Decimal('250'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004350 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004351 >>> ExtendedContext.logb(Decimal('2.50'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004352 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004353 >>> ExtendedContext.logb(Decimal('0.03'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004354 Decimal('-2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004355 >>> ExtendedContext.logb(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004356 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004357 """
4358 return a.logb(context=self)
4359
4360 def logical_and(self, a, b):
4361 """Applies the logical operation 'and' between each operand's digits.
4362
4363 The operands must be both logical numbers.
4364
4365 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004366 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004367 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004368 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004369 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004370 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004371 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004372 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004373 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004374 Decimal('1000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004375 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004376 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004377 """
4378 return a.logical_and(b, context=self)
4379
4380 def logical_invert(self, a):
4381 """Invert all the digits in the operand.
4382
4383 The operand must be a logical number.
4384
4385 >>> ExtendedContext.logical_invert(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004386 Decimal('111111111')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004387 >>> ExtendedContext.logical_invert(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004388 Decimal('111111110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004389 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004390 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004391 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004392 Decimal('10101010')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004393 """
4394 return a.logical_invert(context=self)
4395
4396 def logical_or(self, a, b):
4397 """Applies the logical operation 'or' between each operand's digits.
4398
4399 The operands must be both logical numbers.
4400
4401 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004402 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004403 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004404 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004405 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004406 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004407 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004408 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004409 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004410 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004411 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004412 Decimal('1110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004413 """
4414 return a.logical_or(b, context=self)
4415
4416 def logical_xor(self, a, b):
4417 """Applies the logical operation 'xor' between each operand's digits.
4418
4419 The operands must be both logical numbers.
4420
4421 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004422 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004423 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004424 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004425 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004426 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004427 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004428 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004429 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004430 Decimal('110')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004431 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004432 Decimal('1101')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004433 """
4434 return a.logical_xor(b, context=self)
4435
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004436 def max(self, a,b):
4437 """max compares two values numerically and returns the maximum.
4438
4439 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004440 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004441 operation. If they are numerically equal then the left-hand operand
4442 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004443 infinity) of the two operands is chosen as the result.
4444
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004445 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004446 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004447 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004448 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004449 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004450 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004451 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004452 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004453 """
4454 return a.max(b, context=self)
4455
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004456 def max_mag(self, a, b):
4457 """Compares the values numerically with their sign ignored."""
4458 return a.max_mag(b, context=self)
4459
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004460 def min(self, a,b):
4461 """min compares two values numerically and returns the minimum.
4462
4463 If either operand is a NaN then the general rules apply.
Christian Heimes679db4a2008-01-18 09:56:22 +00004464 Otherwise, the operands are compared as though by the compare
Guido van Rossumd8faa362007-04-27 19:54:29 +00004465 operation. If they are numerically equal then the left-hand operand
4466 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004467 infinity) of the two operands is chosen as the result.
4468
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004469 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004470 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004471 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004472 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004473 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004474 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004475 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004476 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004477 """
4478 return a.min(b, context=self)
4479
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004480 def min_mag(self, a, b):
4481 """Compares the values numerically with their sign ignored."""
4482 return a.min_mag(b, context=self)
4483
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004484 def minus(self, a):
4485 """Minus corresponds to unary prefix minus in Python.
4486
4487 The operation is evaluated using the same rules as subtract; the
4488 operation minus(a) is calculated as subtract('0', a) where the '0'
4489 has the same exponent as the operand.
4490
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004491 >>> ExtendedContext.minus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004492 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004493 >>> ExtendedContext.minus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004494 Decimal('1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004495 """
4496 return a.__neg__(context=self)
4497
4498 def multiply(self, a, b):
4499 """multiply multiplies two operands.
4500
4501 If either operand is a special value then the general rules apply.
4502 Otherwise, the operands are multiplied together ('long multiplication'),
4503 resulting in a number which may be as long as the sum of the lengths
4504 of the two operands.
4505
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004506 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004507 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004508 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004509 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004510 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004511 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004512 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004513 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004514 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004515 Decimal('4.28135971E+11')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004516 """
4517 return a.__mul__(b, context=self)
4518
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004519 def next_minus(self, a):
4520 """Returns the largest representable number smaller than a.
4521
4522 >>> c = ExtendedContext.copy()
4523 >>> c.Emin = -999
4524 >>> c.Emax = 999
4525 >>> ExtendedContext.next_minus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004526 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004527 >>> c.next_minus(Decimal('1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004528 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004529 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004530 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004531 >>> c.next_minus(Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004532 Decimal('9.99999999E+999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004533 """
4534 return a.next_minus(context=self)
4535
4536 def next_plus(self, a):
4537 """Returns the smallest representable number larger than a.
4538
4539 >>> c = ExtendedContext.copy()
4540 >>> c.Emin = -999
4541 >>> c.Emax = 999
4542 >>> ExtendedContext.next_plus(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004543 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004544 >>> c.next_plus(Decimal('-1E-1007'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004545 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004546 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004547 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004548 >>> c.next_plus(Decimal('-Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004549 Decimal('-9.99999999E+999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004550 """
4551 return a.next_plus(context=self)
4552
4553 def next_toward(self, a, b):
4554 """Returns the number closest to a, in direction towards b.
4555
4556 The result is the closest representable number from the first
4557 operand (but not the first operand) that is in the direction
4558 towards the second operand, unless the operands have the same
4559 value.
4560
4561 >>> c = ExtendedContext.copy()
4562 >>> c.Emin = -999
4563 >>> c.Emax = 999
4564 >>> c.next_toward(Decimal('1'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004565 Decimal('1.00000001')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004566 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004567 Decimal('-0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004568 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004569 Decimal('-1.00000002')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004570 >>> c.next_toward(Decimal('1'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004571 Decimal('0.999999999')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004572 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004573 Decimal('0E-1007')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004574 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004575 Decimal('-1.00000004')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004576 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004577 Decimal('-0.00')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004578 """
4579 return a.next_toward(b, context=self)
4580
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004581 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004582 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004583
4584 Essentially a plus operation with all trailing zeros removed from the
4585 result.
4586
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004587 >>> ExtendedContext.normalize(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004588 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004589 >>> ExtendedContext.normalize(Decimal('-2.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004590 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004591 >>> ExtendedContext.normalize(Decimal('1.200'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004592 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004593 >>> ExtendedContext.normalize(Decimal('-120'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004594 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004595 >>> ExtendedContext.normalize(Decimal('120.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004596 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004597 >>> ExtendedContext.normalize(Decimal('0.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004598 Decimal('0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004599 """
4600 return a.normalize(context=self)
4601
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004602 def number_class(self, a):
4603 """Returns an indication of the class of the operand.
4604
4605 The class is one of the following strings:
4606 -sNaN
4607 -NaN
4608 -Infinity
4609 -Normal
4610 -Subnormal
4611 -Zero
4612 +Zero
4613 +Subnormal
4614 +Normal
4615 +Infinity
4616
4617 >>> c = Context(ExtendedContext)
4618 >>> c.Emin = -999
4619 >>> c.Emax = 999
4620 >>> c.number_class(Decimal('Infinity'))
4621 '+Infinity'
4622 >>> c.number_class(Decimal('1E-10'))
4623 '+Normal'
4624 >>> c.number_class(Decimal('2.50'))
4625 '+Normal'
4626 >>> c.number_class(Decimal('0.1E-999'))
4627 '+Subnormal'
4628 >>> c.number_class(Decimal('0'))
4629 '+Zero'
4630 >>> c.number_class(Decimal('-0'))
4631 '-Zero'
4632 >>> c.number_class(Decimal('-0.1E-999'))
4633 '-Subnormal'
4634 >>> c.number_class(Decimal('-1E-10'))
4635 '-Normal'
4636 >>> c.number_class(Decimal('-2.50'))
4637 '-Normal'
4638 >>> c.number_class(Decimal('-Infinity'))
4639 '-Infinity'
4640 >>> c.number_class(Decimal('NaN'))
4641 'NaN'
4642 >>> c.number_class(Decimal('-NaN'))
4643 'NaN'
4644 >>> c.number_class(Decimal('sNaN'))
4645 'sNaN'
4646 """
4647 return a.number_class(context=self)
4648
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004649 def plus(self, a):
4650 """Plus corresponds to unary prefix plus in Python.
4651
4652 The operation is evaluated using the same rules as add; the
4653 operation plus(a) is calculated as add('0', a) where the '0'
4654 has the same exponent as the operand.
4655
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004656 >>> ExtendedContext.plus(Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004657 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004658 >>> ExtendedContext.plus(Decimal('-1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004659 Decimal('-1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004660 """
4661 return a.__pos__(context=self)
4662
4663 def power(self, a, b, modulo=None):
4664 """Raises a to the power of b, to modulo if given.
4665
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004666 With two arguments, compute a**b. If a is negative then b
4667 must be integral. The result will be inexact unless b is
4668 integral and the result is finite and can be expressed exactly
4669 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004670
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004671 With three arguments, compute (a**b) % modulo. For the
4672 three argument form, the following restrictions on the
4673 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004674
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004675 - all three arguments must be integral
4676 - b must be nonnegative
4677 - at least one of a or b must be nonzero
4678 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004679
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004680 The result of pow(a, b, modulo) is identical to the result
4681 that would be obtained by computing (a**b) % modulo with
4682 unbounded precision, but is computed more efficiently. It is
4683 always exact.
4684
4685 >>> c = ExtendedContext.copy()
4686 >>> c.Emin = -999
4687 >>> c.Emax = 999
4688 >>> c.power(Decimal('2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004689 Decimal('8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004690 >>> c.power(Decimal('-2'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004691 Decimal('-8')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004692 >>> c.power(Decimal('2'), Decimal('-3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004693 Decimal('0.125')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004694 >>> c.power(Decimal('1.7'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004695 Decimal('69.7575744')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004696 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004697 Decimal('2.00000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004698 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004699 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004700 >>> c.power(Decimal('Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004701 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004702 >>> c.power(Decimal('Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004703 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004704 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004705 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004706 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004707 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004708 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004709 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004710 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004711 Decimal('Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004712 >>> c.power(Decimal('0'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004713 Decimal('NaN')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004714
4715 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004716 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004717 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004718 Decimal('-11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004719 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004720 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004721 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004722 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004723 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004724 Decimal('11729830')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004725 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004726 Decimal('-0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004727 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004728 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004729 """
4730 return a.__pow__(b, modulo, context=self)
4731
4732 def quantize(self, a, b):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004733 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004734
4735 The coefficient of the result is derived from that of the left-hand
Guido van Rossumd8faa362007-04-27 19:54:29 +00004736 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004737 exponent is being increased), multiplied by a positive power of ten (if
4738 the exponent is being decreased), or is unchanged (if the exponent is
4739 already equal to that of the right-hand operand).
4740
4741 Unlike other operations, if the length of the coefficient after the
4742 quantize operation would be greater than precision then an Invalid
Guido van Rossumd8faa362007-04-27 19:54:29 +00004743 operation condition is raised. This guarantees that, unless there is
4744 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004745 equal to that of the right-hand operand.
4746
4747 Also unlike other operations, quantize will never raise Underflow, even
4748 if the result is subnormal and inexact.
4749
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004750 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004751 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004752 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004753 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004754 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004755 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004756 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004757 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004758 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004759 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004760 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004761 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004762 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004763 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004764 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004765 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004766 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004767 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004768 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004769 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004770 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004771 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004772 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004773 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004774 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004775 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004776 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004777 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004778 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004779 Decimal('2E+2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004780 """
4781 return a.quantize(b, context=self)
4782
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004783 def radix(self):
4784 """Just returns 10, as this is Decimal, :)
4785
4786 >>> ExtendedContext.radix()
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004787 Decimal('10')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004788 """
4789 return Decimal(10)
4790
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004791 def remainder(self, a, b):
4792 """Returns the remainder from integer division.
4793
4794 The result is the residue of the dividend after the operation of
Guido van Rossumd8faa362007-04-27 19:54:29 +00004795 calculating integer division as described for divide-integer, rounded
4796 to precision digits if necessary. The sign of the result, if
4797 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004798
4799 This operation will fail under the same conditions as integer division
4800 (that is, if integer division on the same two operands would fail, the
4801 remainder cannot be calculated).
4802
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004803 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004804 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004805 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004806 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004807 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004808 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004809 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004810 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004811 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004812 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004813 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004814 Decimal('1.0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004815 """
4816 return a.__mod__(b, context=self)
4817
4818 def remainder_near(self, a, b):
4819 """Returns to be "a - b * n", where n is the integer nearest the exact
4820 value of "x / b" (if two integers are equally near then the even one
Guido van Rossumd8faa362007-04-27 19:54:29 +00004821 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004822 sign of a.
4823
4824 This operation will fail under the same conditions as integer division
4825 (that is, if integer division on the same two operands would fail, the
4826 remainder cannot be calculated).
4827
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004828 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004829 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004830 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004831 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004832 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004833 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004834 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004835 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004836 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004837 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004838 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004839 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004840 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004841 Decimal('-0.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004842 """
4843 return a.remainder_near(b, context=self)
4844
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004845 def rotate(self, a, b):
4846 """Returns a rotated copy of a, b times.
4847
4848 The coefficient of the result is a rotated copy of the digits in
4849 the coefficient of the first operand. The number of places of
4850 rotation is taken from the absolute value of the second operand,
4851 with the rotation being to the left if the second operand is
4852 positive or to the right otherwise.
4853
4854 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004855 Decimal('400000003')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004856 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004857 Decimal('12')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004858 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004859 Decimal('891234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004860 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004861 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004862 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004863 Decimal('345678912')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004864 """
4865 return a.rotate(b, context=self)
4866
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004867 def same_quantum(self, a, b):
4868 """Returns True if the two operands have the same exponent.
4869
4870 The result is never affected by either the sign or the coefficient of
4871 either operand.
4872
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004873 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004874 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004875 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004876 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004877 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004878 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004879 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004880 True
4881 """
4882 return a.same_quantum(b)
4883
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004884 def scaleb (self, a, b):
4885 """Returns the first operand after adding the second value its exp.
4886
4887 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004888 Decimal('0.0750')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004889 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004890 Decimal('7.50')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004891 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004892 Decimal('7.50E+3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004893 """
4894 return a.scaleb (b, context=self)
4895
4896 def shift(self, a, b):
4897 """Returns a shifted copy of a, b times.
4898
4899 The coefficient of the result is a shifted copy of the digits
4900 in the coefficient of the first operand. The number of places
4901 to shift is taken from the absolute value of the second operand,
4902 with the shift being to the left if the second operand is
4903 positive or to the right otherwise. Digits shifted into the
4904 coefficient are zeros.
4905
4906 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004907 Decimal('400000000')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004908 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004909 Decimal('0')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004910 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004911 Decimal('1234567')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004912 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004913 Decimal('123456789')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004914 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004915 Decimal('345678900')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004916 """
4917 return a.shift(b, context=self)
4918
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004919 def sqrt(self, a):
Guido van Rossumd8faa362007-04-27 19:54:29 +00004920 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004921
4922 If the result must be inexact, it is rounded using the round-half-even
4923 algorithm.
4924
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004925 >>> ExtendedContext.sqrt(Decimal('0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004926 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004927 >>> ExtendedContext.sqrt(Decimal('-0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004928 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004929 >>> ExtendedContext.sqrt(Decimal('0.39'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004930 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004931 >>> ExtendedContext.sqrt(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004932 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004933 >>> ExtendedContext.sqrt(Decimal('1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004934 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004935 >>> ExtendedContext.sqrt(Decimal('1.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004936 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004937 >>> ExtendedContext.sqrt(Decimal('1.00'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004938 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004939 >>> ExtendedContext.sqrt(Decimal('7'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004940 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004941 >>> ExtendedContext.sqrt(Decimal('10'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004942 Decimal('3.16227766')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004943 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004944 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004945 """
4946 return a.sqrt(context=self)
4947
4948 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004949 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004950
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004951 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004952 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004953 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004954 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004955 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004956 Decimal('-0.77')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004957 """
4958 return a.__sub__(b, context=self)
4959
4960 def to_eng_string(self, a):
4961 """Converts a number to a string, using scientific notation.
4962
4963 The operation is not affected by the context.
4964 """
4965 return a.to_eng_string(context=self)
4966
4967 def to_sci_string(self, a):
4968 """Converts a number to a string, using scientific notation.
4969
4970 The operation is not affected by the context.
4971 """
4972 return a.__str__(context=self)
4973
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004974 def to_integral_exact(self, a):
4975 """Rounds to an integer.
4976
4977 When the operand has a negative exponent, the result is the same
4978 as using the quantize() operation using the given operand as the
4979 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4980 of the operand as the precision setting; Inexact and Rounded flags
4981 are allowed in this operation. The rounding mode is taken from the
4982 context.
4983
4984 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004985 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004986 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004987 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004988 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004989 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004990 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004991 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004992 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004993 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004994 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004995 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004996 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004997 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004998 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00004999 Decimal('-Infinity')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005000 """
5001 return a.to_integral_exact(context=self)
5002
5003 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005004 """Rounds to an integer.
5005
5006 When the operand has a negative exponent, the result is the same
5007 as using the quantize() operation using the given operand as the
5008 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5009 of the operand as the precision setting, except that no flags will
Guido van Rossumd8faa362007-04-27 19:54:29 +00005010 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005011
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005012 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005013 Decimal('2')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005014 >>> ExtendedContext.to_integral_value(Decimal('100'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005015 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005016 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005017 Decimal('100')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005018 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005019 Decimal('102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005020 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005021 Decimal('-102')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005022 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005023 Decimal('1.0E+6')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005024 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005025 Decimal('7.89E+77')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005026 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Christian Heimes68f5fbe2008-02-14 08:27:37 +00005027 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005028 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005029 return a.to_integral_value(context=self)
5030
5031 # the method name changed, but we provide also the old one, for compatibility
5032 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005033
5034class _WorkRep(object):
5035 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005036 # sign: 0 or 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005037 # int: int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005038 # exp: None, int, or string
5039
5040 def __init__(self, value=None):
5041 if value is None:
5042 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005043 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005044 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005045 elif isinstance(value, Decimal):
5046 self.sign = value._sign
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005047 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005048 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005049 else:
5050 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005051 self.sign = value[0]
5052 self.int = value[1]
5053 self.exp = value[2]
5054
5055 def __repr__(self):
5056 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5057
5058 __str__ = __repr__
5059
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005060
5061
Christian Heimes2c181612007-12-17 20:04:13 +00005062def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005063 """Normalizes op1, op2 to have the same exp and length of coefficient.
5064
5065 Done during addition.
5066 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005067 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005068 tmp = op2
5069 other = op1
5070 else:
5071 tmp = op1
5072 other = op2
5073
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005074 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5075 # Then adding 10**exp to tmp has the same effect (after rounding)
5076 # as adding any positive quantity smaller than 10**exp; similarly
5077 # for subtraction. So if other is smaller than 10**exp we replace
5078 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Christian Heimes2c181612007-12-17 20:04:13 +00005079 tmp_len = len(str(tmp.int))
5080 other_len = len(str(other.int))
5081 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5082 if other_len + other.exp - 1 < exp:
5083 other.int = 1
5084 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005085
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005086 tmp.int *= 10 ** (tmp.exp - other.exp)
5087 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005088 return op1, op2
5089
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005090##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005091
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005092# This function from Tim Peters was taken from here:
5093# http://mail.python.org/pipermail/python-list/1999-July/007758.html
5094# The correction being in the function definition is for speed, and
5095# the whole function is not resolved with math.log because of avoiding
5096# the use of floats.
5097def _nbits(n, correction = {
5098 '0': 4, '1': 3, '2': 2, '3': 2,
5099 '4': 1, '5': 1, '6': 1, '7': 1,
5100 '8': 0, '9': 0, 'a': 0, 'b': 0,
5101 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
5102 """Number of bits in binary representation of the positive integer n,
5103 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005104 """
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005105 if n < 0:
5106 raise ValueError("The argument to _nbits should be nonnegative.")
5107 hex_n = "%x" % n
5108 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005109
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005110def _sqrt_nearest(n, a):
5111 """Closest integer to the square root of the positive integer n. a is
5112 an initial approximation to the square root. Any positive integer
5113 will do for a, but the closer a is to the square root of n the
5114 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005115
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005116 """
5117 if n <= 0 or a <= 0:
5118 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5119
5120 b=0
5121 while a != b:
5122 b, a = a, a--n//a>>1
5123 return a
5124
5125def _rshift_nearest(x, shift):
5126 """Given an integer x and a nonnegative integer shift, return closest
5127 integer to x / 2**shift; use round-to-even in case of a tie.
5128
5129 """
5130 b, q = 1 << shift, x >> shift
5131 return q + (2*(x & (b-1)) + (q&1) > b)
5132
5133def _div_nearest(a, b):
5134 """Closest integer to a/b, a and b positive integers; rounds to even
5135 in the case of a tie.
5136
5137 """
5138 q, r = divmod(a, b)
5139 return q + (2*r + (q&1) > b)
5140
5141def _ilog(x, M, L = 8):
5142 """Integer approximation to M*log(x/M), with absolute error boundable
5143 in terms only of x/M.
5144
5145 Given positive integers x and M, return an integer approximation to
5146 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5147 between the approximation and the exact result is at most 22. For
5148 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5149 both cases these are upper bounds on the error; it will usually be
5150 much smaller."""
5151
5152 # The basic algorithm is the following: let log1p be the function
5153 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5154 # the reduction
5155 #
5156 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5157 #
5158 # repeatedly until the argument to log1p is small (< 2**-L in
5159 # absolute value). For small y we can use the Taylor series
5160 # expansion
5161 #
5162 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5163 #
5164 # truncating at T such that y**T is small enough. The whole
5165 # computation is carried out in a form of fixed-point arithmetic,
5166 # with a real number z being represented by an integer
5167 # approximation to z*M. To avoid loss of precision, the y below
5168 # is actually an integer approximation to 2**R*y*M, where R is the
5169 # number of reductions performed so far.
5170
5171 y = x-M
5172 # argument reduction; R = number of reductions performed
5173 R = 0
5174 while (R <= L and abs(y) << L-R >= M or
5175 R > L and abs(y) >> R-L >= M):
5176 y = _div_nearest((M*y) << 1,
5177 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5178 R += 1
5179
5180 # Taylor series with T terms
5181 T = -int(-10*len(str(M))//(3*L))
5182 yshift = _rshift_nearest(y, R)
5183 w = _div_nearest(M, T)
5184 for k in range(T-1, 0, -1):
5185 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5186
5187 return _div_nearest(w*y, M)
5188
5189def _dlog10(c, e, p):
5190 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5191 approximation to 10**p * log10(c*10**e), with an absolute error of
5192 at most 1. Assumes that c*10**e is not exactly 1."""
5193
5194 # increase precision by 2; compensate for this by dividing
5195 # final result by 100
5196 p += 2
5197
5198 # write c*10**e as d*10**f with either:
5199 # f >= 0 and 1 <= d <= 10, or
5200 # f <= 0 and 0.1 <= d <= 1.
5201 # Thus for c*10**e close to 1, f = 0
5202 l = len(str(c))
5203 f = e+l - (e+l >= 1)
5204
5205 if p > 0:
5206 M = 10**p
5207 k = e+p-f
5208 if k >= 0:
5209 c *= 10**k
5210 else:
5211 c = _div_nearest(c, 10**-k)
5212
5213 log_d = _ilog(c, M) # error < 5 + 22 = 27
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005214 log_10 = _log10_digits(p) # error < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005215 log_d = _div_nearest(log_d*M, log_10)
5216 log_tenpower = f*M # exact
5217 else:
5218 log_d = 0 # error < 2.31
Neal Norwitz2f99b242008-08-24 05:48:10 +00005219 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005220
5221 return _div_nearest(log_tenpower+log_d, 100)
5222
5223def _dlog(c, e, p):
5224 """Given integers c, e and p with c > 0, compute an integer
5225 approximation to 10**p * log(c*10**e), with an absolute error of
5226 at most 1. Assumes that c*10**e is not exactly 1."""
5227
5228 # Increase precision by 2. The precision increase is compensated
5229 # for at the end with a division by 100.
5230 p += 2
5231
5232 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5233 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5234 # as 10**p * log(d) + 10**p*f * log(10).
5235 l = len(str(c))
5236 f = e+l - (e+l >= 1)
5237
5238 # compute approximation to 10**p*log(d), with error < 27
5239 if p > 0:
5240 k = e+p-f
5241 if k >= 0:
5242 c *= 10**k
5243 else:
5244 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5245
5246 # _ilog magnifies existing error in c by a factor of at most 10
5247 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5248 else:
5249 # p <= 0: just approximate the whole thing by 0; error < 2.31
5250 log_d = 0
5251
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005252 # compute approximation to f*10**p*log(10), with error < 11.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005253 if f:
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005254 extra = len(str(abs(f)))-1
5255 if p + extra >= 0:
5256 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5257 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5258 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005259 else:
5260 f_log_ten = 0
5261 else:
5262 f_log_ten = 0
5263
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005264 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005265 return _div_nearest(f_log_ten + log_d, 100)
5266
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005267class _Log10Memoize(object):
5268 """Class to compute, store, and allow retrieval of, digits of the
5269 constant log(10) = 2.302585.... This constant is needed by
5270 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5271 def __init__(self):
5272 self.digits = "23025850929940456840179914546843642076011014886"
5273
5274 def getdigits(self, p):
5275 """Given an integer p >= 0, return floor(10**p)*log(10).
5276
5277 For example, self.getdigits(3) returns 2302.
5278 """
5279 # digits are stored as a string, for quick conversion to
5280 # integer in the case that we've already computed enough
5281 # digits; the stored digits should always be correct
5282 # (truncated, not rounded to nearest).
5283 if p < 0:
5284 raise ValueError("p should be nonnegative")
5285
5286 if p >= len(self.digits):
5287 # compute p+3, p+6, p+9, ... digits; continue until at
5288 # least one of the extra digits is nonzero
5289 extra = 3
5290 while True:
5291 # compute p+extra digits, correct to within 1ulp
5292 M = 10**(p+extra+2)
5293 digits = str(_div_nearest(_ilog(10*M, M), 100))
5294 if digits[-extra:] != '0'*extra:
5295 break
5296 extra += 3
5297 # keep all reliable digits so far; remove trailing zeros
5298 # and next nonzero digit
5299 self.digits = digits.rstrip('0')[:-1]
5300 return int(self.digits[:p+1])
5301
5302_log10_digits = _Log10Memoize().getdigits
5303
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005304def _iexp(x, M, L=8):
5305 """Given integers x and M, M > 0, such that x/M is small in absolute
5306 value, compute an integer approximation to M*exp(x/M). For 0 <=
5307 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5308 is usually much smaller)."""
5309
5310 # Algorithm: to compute exp(z) for a real number z, first divide z
5311 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5312 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5313 # series
5314 #
5315 # expm1(x) = x + x**2/2! + x**3/3! + ...
5316 #
5317 # Now use the identity
5318 #
5319 # expm1(2x) = expm1(x)*(expm1(x)+2)
5320 #
5321 # R times to compute the sequence expm1(z/2**R),
5322 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5323
5324 # Find R such that x/2**R/M <= 2**-L
5325 R = _nbits((x<<L)//M)
5326
5327 # Taylor series. (2**L)**T > M
5328 T = -int(-10*len(str(M))//(3*L))
5329 y = _div_nearest(x, T)
5330 Mshift = M<<R
5331 for i in range(T-1, 0, -1):
5332 y = _div_nearest(x*(Mshift + y), Mshift * i)
5333
5334 # Expansion
5335 for k in range(R-1, -1, -1):
5336 Mshift = M<<(k+2)
5337 y = _div_nearest(y*(y+Mshift), Mshift)
5338
5339 return M+y
5340
5341def _dexp(c, e, p):
5342 """Compute an approximation to exp(c*10**e), with p decimal places of
5343 precision.
5344
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005345 Returns integers d, f such that:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005346
5347 10**(p-1) <= d <= 10**p, and
5348 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5349
5350 In other words, d*10**f is an approximation to exp(c*10**e) with p
5351 digits of precision, and with an error in d of at most 1. This is
5352 almost, but not quite, the same as the error being < 1ulp: when d
5353 = 10**(p-1) the error could be up to 10 ulp."""
5354
5355 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5356 p += 2
5357
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005358 # compute log(10) with extra precision = adjusted exponent of c*10**e
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005359 extra = max(0, e + len(str(c)) - 1)
5360 q = p + extra
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005361
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005362 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005363 # rounding down
5364 shift = e+q
5365 if shift >= 0:
5366 cshift = c*10**shift
5367 else:
5368 cshift = c//10**-shift
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005369 quot, rem = divmod(cshift, _log10_digits(q))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005370
5371 # reduce remainder back to original precision
5372 rem = _div_nearest(rem, 10**extra)
5373
5374 # error in result of _iexp < 120; error after division < 0.62
5375 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5376
5377def _dpower(xc, xe, yc, ye, p):
5378 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5379 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5380
5381 10**(p-1) <= c <= 10**p, and
5382 (c-1)*10**e < x**y < (c+1)*10**e
5383
5384 in other words, c*10**e is an approximation to x**y with p digits
5385 of precision, and with an error in c of at most 1. (This is
5386 almost, but not quite, the same as the error being < 1ulp: when c
5387 == 10**(p-1) we can only guarantee error < 10ulp.)
5388
5389 We assume that: x is positive and not equal to 1, and y is nonzero.
5390 """
5391
5392 # Find b such that 10**(b-1) <= |y| <= 10**b
5393 b = len(str(abs(yc))) + ye
5394
5395 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5396 lxc = _dlog(xc, xe, p+b+1)
5397
5398 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5399 shift = ye-b
5400 if shift >= 0:
5401 pc = lxc*yc*10**shift
5402 else:
5403 pc = _div_nearest(lxc*yc, 10**-shift)
5404
5405 if pc == 0:
5406 # we prefer a result that isn't exactly 1; this makes it
5407 # easier to compute a correctly rounded result in __pow__
5408 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5409 coeff, exp = 10**(p-1)+1, 1-p
5410 else:
5411 coeff, exp = 10**p-1, -p
5412 else:
5413 coeff, exp = _dexp(pc, -(p+1), p+1)
5414 coeff = _div_nearest(coeff, 10)
5415 exp += 1
5416
5417 return coeff, exp
5418
5419def _log10_lb(c, correction = {
5420 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5421 '6': 23, '7': 16, '8': 10, '9': 5}):
5422 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5423 if c <= 0:
5424 raise ValueError("The argument to _log10_lb should be nonnegative.")
5425 str_c = str(c)
5426 return 100*len(str_c) - correction[str_c[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005427
Guido van Rossumd8faa362007-04-27 19:54:29 +00005428##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005429
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005430def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005431 """Convert other to Decimal.
5432
5433 Verifies that it's ok to use in an implicit construction.
5434 """
5435 if isinstance(other, Decimal):
5436 return other
Walter Dörwaldaa97f042007-05-03 21:05:51 +00005437 if isinstance(other, int):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005438 return Decimal(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005439 if raiseit:
5440 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005441 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005442
Guido van Rossumd8faa362007-04-27 19:54:29 +00005443##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005444
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005445# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005446# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005447
5448DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005449 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005450 traps=[DivisionByZero, Overflow, InvalidOperation],
5451 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005452 Emax=999999999,
5453 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005454 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005455)
5456
5457# Pre-made alternate contexts offered by the specification
5458# Don't change these; the user should be able to select these
5459# contexts and be able to reproduce results from other implementations
5460# of the spec.
5461
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005462BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005463 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005464 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5465 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005466)
5467
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005468ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005469 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005470 traps=[],
5471 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005472)
5473
5474
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005475##### crud for parsing strings #############################################
Christian Heimes23daade02008-02-25 12:39:23 +00005476#
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005477# Regular expression used for parsing numeric strings. Additional
5478# comments:
5479#
5480# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5481# whitespace. But note that the specification disallows whitespace in
5482# a numeric string.
5483#
5484# 2. For finite numbers (not infinities and NaNs) the body of the
5485# number between the optional sign and the optional exponent must have
5486# at least one decimal digit, possibly after the decimal point. The
Antoine Pitroufd036452008-08-19 17:56:33 +00005487# lookahead expression '(?=[0-9]|\.[0-9])' checks this.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005488#
5489# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5490# other meaning for \d than the numbers [0-9].
5491
5492import re
Benjamin Peterson41181742008-07-02 20:22:54 +00005493_parser = re.compile(r""" # A numeric string consists of:
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005494# \s*
Benjamin Peterson41181742008-07-02 20:22:54 +00005495 (?P<sign>[-+])? # an optional sign, followed by either...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005496 (
Benjamin Peterson41181742008-07-02 20:22:54 +00005497 (?=[0-9]|\.[0-9]) # ...a number (with at least one digit)
5498 (?P<int>[0-9]*) # having a (possibly empty) integer part
5499 (\.(?P<frac>[0-9]*))? # followed by an optional fractional part
5500 (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005501 |
Benjamin Peterson41181742008-07-02 20:22:54 +00005502 Inf(inity)? # ...an infinity, or...
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005503 |
Benjamin Peterson41181742008-07-02 20:22:54 +00005504 (?P<signal>s)? # ...an (optionally signaling)
5505 NaN # NaN
5506 (?P<diag>[0-9]*) # with (possibly empty) diagnostic info.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005507 )
5508# \s*
Christian Heimesa62da1d2008-01-12 19:39:10 +00005509 \Z
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005510""", re.VERBOSE | re.IGNORECASE).match
5511
Christian Heimescbf3b5c2007-12-03 21:02:03 +00005512_all_zeros = re.compile('0*$').match
5513_exact_half = re.compile('50*$').match
Christian Heimesf16baeb2008-02-29 14:57:44 +00005514
5515##### PEP3101 support functions ##############################################
5516# The functions parse_format_specifier and format_align have little to do
5517# with the Decimal class, and could potentially be reused for other pure
5518# Python numeric classes that want to implement __format__
5519#
5520# A format specifier for Decimal looks like:
5521#
5522# [[fill]align][sign][0][minimumwidth][.precision][type]
5523#
5524
5525_parse_format_specifier_regex = re.compile(r"""\A
5526(?:
5527 (?P<fill>.)?
5528 (?P<align>[<>=^])
5529)?
5530(?P<sign>[-+ ])?
5531(?P<zeropad>0)?
5532(?P<minimumwidth>(?!0)\d+)?
5533(?:\.(?P<precision>0|(?!0)\d+))?
5534(?P<type>[eEfFgG%])?
5535\Z
5536""", re.VERBOSE)
5537
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005538del re
5539
Christian Heimesf16baeb2008-02-29 14:57:44 +00005540def _parse_format_specifier(format_spec):
5541 """Parse and validate a format specifier.
5542
5543 Turns a standard numeric format specifier into a dict, with the
5544 following entries:
5545
5546 fill: fill character to pad field to minimum width
5547 align: alignment type, either '<', '>', '=' or '^'
5548 sign: either '+', '-' or ' '
5549 minimumwidth: nonnegative integer giving minimum width
5550 precision: nonnegative integer giving precision, or None
5551 type: one of the characters 'eEfFgG%', or None
5552 unicode: either True or False (always True for Python 3.x)
5553
5554 """
5555 m = _parse_format_specifier_regex.match(format_spec)
5556 if m is None:
5557 raise ValueError("Invalid format specifier: " + format_spec)
5558
5559 # get the dictionary
5560 format_dict = m.groupdict()
5561
5562 # defaults for fill and alignment
5563 fill = format_dict['fill']
5564 align = format_dict['align']
5565 if format_dict.pop('zeropad') is not None:
5566 # in the face of conflict, refuse the temptation to guess
5567 if fill is not None and fill != '0':
5568 raise ValueError("Fill character conflicts with '0'"
5569 " in format specifier: " + format_spec)
5570 if align is not None and align != '=':
5571 raise ValueError("Alignment conflicts with '0' in "
5572 "format specifier: " + format_spec)
5573 fill = '0'
5574 align = '='
5575 format_dict['fill'] = fill or ' '
5576 format_dict['align'] = align or '<'
5577
5578 if format_dict['sign'] is None:
5579 format_dict['sign'] = '-'
5580
5581 # turn minimumwidth and precision entries into integers.
5582 # minimumwidth defaults to 0; precision remains None if not given
5583 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5584 if format_dict['precision'] is not None:
5585 format_dict['precision'] = int(format_dict['precision'])
5586
5587 # if format type is 'g' or 'G' then a precision of 0 makes little
5588 # sense; convert it to 1. Same if format type is unspecified.
5589 if format_dict['precision'] == 0:
5590 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5591 format_dict['precision'] = 1
5592
5593 # record whether return type should be str or unicode
Christian Heimes295f4fa2008-02-29 15:03:39 +00005594 format_dict['unicode'] = True
Christian Heimesf16baeb2008-02-29 14:57:44 +00005595
5596 return format_dict
5597
5598def _format_align(body, spec_dict):
5599 """Given an unpadded, non-aligned numeric string, add padding and
5600 aligment to conform with the given format specifier dictionary (as
5601 output from parse_format_specifier).
5602
5603 It's assumed that if body is negative then it starts with '-'.
5604 Any leading sign ('-' or '+') is stripped from the body before
5605 applying the alignment and padding rules, and replaced in the
5606 appropriate position.
5607
5608 """
5609 # figure out the sign; we only examine the first character, so if
5610 # body has leading whitespace the results may be surprising.
5611 if len(body) > 0 and body[0] in '-+':
5612 sign = body[0]
5613 body = body[1:]
5614 else:
5615 sign = ''
5616
5617 if sign != '-':
5618 if spec_dict['sign'] in ' +':
5619 sign = spec_dict['sign']
5620 else:
5621 sign = ''
5622
5623 # how much extra space do we have to play with?
5624 minimumwidth = spec_dict['minimumwidth']
5625 fill = spec_dict['fill']
5626 padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5627
5628 align = spec_dict['align']
5629 if align == '<':
5630 result = padding + sign + body
5631 elif align == '>':
5632 result = sign + body + padding
5633 elif align == '=':
5634 result = sign + padding + body
5635 else: #align == '^'
5636 half = len(padding)//2
5637 result = padding[:half] + sign + body + padding[half:]
5638
Christian Heimesf16baeb2008-02-29 14:57:44 +00005639 return result
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00005640
Guido van Rossumd8faa362007-04-27 19:54:29 +00005641##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005642
Guido van Rossumd8faa362007-04-27 19:54:29 +00005643# Reusable defaults
Mark Dickinson627cf6a2009-01-03 12:11:47 +00005644_Infinity = Decimal('Inf')
5645_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonf9236412009-01-02 23:23:21 +00005646_NaN = Decimal('NaN')
Mark Dickinson627cf6a2009-01-03 12:11:47 +00005647_Zero = Decimal(0)
5648_One = Decimal(1)
5649_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005650
Mark Dickinson627cf6a2009-01-03 12:11:47 +00005651# _SignedInfinity[sign] is infinity w/ that sign
5652_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005653
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005654
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005655
5656if __name__ == '__main__':
5657 import doctest, sys
5658 doctest.testmod(sys.modules[__name__])